|
| 1 | +"""Code-graph cache ownership: root markers and orphan pruning (issue #711). |
| 2 | +
|
| 3 | +Every project or worktree where a session opens gets its own graph under |
| 4 | +``~/.cache/cortex/code-graphs/<project key>/`` (0.6 to 1.1 GB each, measured |
| 5 | +2026-10-10 on a development machine, issue #711). Nothing tied a directory to |
| 6 | +the project it was built from, so a deleted worktree left its graph behind. |
| 7 | +
|
| 8 | +Cortex now writes its own marker, ``cortex-root.json``, next to the graph it |
| 9 | +asks the upstream analyzer to build. The upstream ``meta.json`` belongs to the |
| 10 | +automatised-pipeline (ADR-0052: it writes it "for cortex-viz") and its schema |
| 11 | +is not defined in this repository, so it is never read or rewritten here. |
| 12 | +
|
| 13 | +Pruning rule: a graph directory whose marker names a root that no longer exists |
| 14 | +is removed; no session can be using a graph whose project directory is gone. A |
| 15 | +directory without a readable marker cannot be tied to a root, so it is reported |
| 16 | +and kept, never deleted on a guess. |
| 17 | +""" |
| 18 | + |
| 19 | +from __future__ import annotations |
| 20 | + |
| 21 | +import dataclasses |
| 22 | +import json |
| 23 | +import logging |
| 24 | +import shutil |
| 25 | +from pathlib import Path |
| 26 | + |
| 27 | +logger = logging.getLogger(__name__) |
| 28 | + |
| 29 | +ROOT_MARKER = "cortex-root.json" |
| 30 | + |
| 31 | + |
| 32 | +@dataclasses.dataclass(frozen=True) |
| 33 | +class PruneReport: |
| 34 | + """Outcome of one pruning pass over a code-graph cache directory.""" |
| 35 | + |
| 36 | + removed: tuple[str, ...] |
| 37 | + unattributed: tuple[str, ...] |
| 38 | + failed: tuple[str, ...] |
| 39 | + |
| 40 | + |
| 41 | +def default_cache_dir() -> Path: |
| 42 | + """The cache directory ``ingest_codebase`` writes graphs into by default.""" |
| 43 | + return Path.home() / ".cache" / "cortex" / "code-graphs" |
| 44 | + |
| 45 | + |
| 46 | +def write_root_marker(graph_dir: str | Path, project_root: str | Path) -> None: |
| 47 | + """Record ``project_root`` (resolved) as the root ``graph_dir`` was built from.""" |
| 48 | + target = Path(graph_dir).expanduser() |
| 49 | + target.mkdir(parents=True, exist_ok=True) |
| 50 | + root = str(Path(project_root).expanduser().resolve()) |
| 51 | + payload = json.dumps({"project_root": root}, indent=2) + "\n" |
| 52 | + tmp = target / (ROOT_MARKER + ".tmp") |
| 53 | + tmp.write_text(payload, encoding="utf-8") |
| 54 | + tmp.replace(target / ROOT_MARKER) |
| 55 | + |
| 56 | + |
| 57 | +def read_root_marker(graph_dir: Path) -> str | None: |
| 58 | + """The recorded project root, or None when the marker is absent or unreadable.""" |
| 59 | + try: |
| 60 | + data = json.loads((graph_dir / ROOT_MARKER).read_text(encoding="utf-8")) |
| 61 | + except (OSError, ValueError): |
| 62 | + return None |
| 63 | + root = data.get("project_root") if isinstance(data, dict) else None |
| 64 | + return root if isinstance(root, str) and root else None |
| 65 | + |
| 66 | + |
| 67 | +def prune_orphan_graphs(cache_dir: str | Path) -> PruneReport: |
| 68 | + """Remove graphs whose recorded root is gone; report the unattributed ones.""" |
| 69 | + base = Path(cache_dir).expanduser() |
| 70 | + removed: list[str] = [] |
| 71 | + unattributed: list[str] = [] |
| 72 | + failed: list[str] = [] |
| 73 | + if not base.is_dir(): |
| 74 | + return PruneReport((), (), ()) |
| 75 | + for entry in sorted(base.iterdir()): |
| 76 | + if not entry.is_dir(): |
| 77 | + continue |
| 78 | + root = read_root_marker(entry) |
| 79 | + if root is None: |
| 80 | + unattributed.append(entry.name) |
| 81 | + elif not Path(root).exists(): |
| 82 | + try: |
| 83 | + shutil.rmtree(entry) |
| 84 | + removed.append(entry.name) |
| 85 | + except OSError as exc: |
| 86 | + logger.warning("could not prune orphan graph %s: %s", entry, exc) |
| 87 | + failed.append(entry.name) |
| 88 | + _log_report(base, removed, unattributed) |
| 89 | + return PruneReport(tuple(removed), tuple(unattributed), tuple(failed)) |
| 90 | + |
| 91 | + |
| 92 | +def _log_report(base: Path, removed: list[str], unattributed: list[str]) -> None: |
| 93 | + if removed: |
| 94 | + logger.info("pruned %d orphan code graph(s): %s", len(removed), removed) |
| 95 | + if unattributed: |
| 96 | + logger.warning( |
| 97 | + "%d code graph(s) under %s carry no %s and cannot be tied to a " |
| 98 | + "project root; kept, remove by hand if unused: %s", |
| 99 | + len(unattributed), |
| 100 | + base, |
| 101 | + ROOT_MARKER, |
| 102 | + unattributed, |
| 103 | + ) |
0 commit comments