Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(dead-code): build the live graph the way update builds it (#3520)

Raghav Chamadiya7e039d495dd5
diff --git a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
index 7af37fb2d..2d76e576f 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -12,6 +12,7 @@ from rich.table import Table
from repowise.cli.helpers import (
console,
get_head_commit,
+ load_config,
load_state,
repo_index_session,
resolve_command_target,
@@ -102,84 +103,39 @@ def _finding_order(f: DeadCodeFindingData) -> tuple:
def _analyze_live(repo_path: Path, config: dict, notices: Any) -> DeadCodeReport:
- """Parse the working tree and run the analyzer over it."""
+ """Parse the working tree and run the analyzer over it.
+
+ The graph is the one ``update`` builds (same file set, framework and
+ dynamic-hint edges), so a live answer differs from the stored one only by
+ the code that changed. ``read_only`` keeps this command from writing into
+ the index.
+ """
from repowise.core.analysis.dead_code import DeadCodeAnalyzer
- from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+ from repowise.core.ingestion.git_indexer import GitIndexer
+ from repowise.core.pipeline.incremental import build_repo_graph
- # Ingest — honor the persisted submodule flags so the analyzed file set
- # matches what `init` indexed (a flagless traverser on a submodule-indexed
- # repo would drop submodule files and skew reachability).
state = load_state(repo_path)
- include_submodules = bool(state.get("include_submodules", False))
- include_nested_repos = bool(state.get("include_nested_repos", False))
-
- traverser = FileTraverser(
- repo_path,
- include_submodules=include_submodules,
- include_nested_repos=include_nested_repos,
- )
- file_infos = list(traverser.traverse())
- parser = ASTParser()
- graph_builder = GraphBuilder(
+ _parsed, source_map, graph_builder, _structure, _count = build_repo_graph(
repo_path,
- include_submodules=include_submodules,
- include_nested_repos=include_nested_repos,
+ list(load_config(repo_path).get("exclude_patterns") or []),
+ collect_sources=True,
+ include_submodules=bool(state.get("include_submodules", False)),
+ include_nested_repos=bool(state.get("include_nested_repos", False)),
+ log=notices.print,
+ read_only=True,
)
- # Kept alongside the parse so the analyzer's marker prepasses reuse these
- # bytes instead of re-reading the repo four more times.
- source_map: dict[str, bytes] = {}
- for fi in file_infos:
- try:
- source = Path(fi.abs_path).read_bytes()
- parsed = parser.parse_file(fi, source)
- graph_builder.add_file(parsed)
- source_map[fi.path] = source
- except Exception:
- pass
-
- from repowise.core.ingestion import wire_tsconfig_resolver
-
- wire_tsconfig_resolver(
- graph_builder,
- repo_path,
- include_submodules=include_submodules,
- include_nested_repos=include_nested_repos,
- )
- graph_builder.set_source_map(source_map)
- graph_builder.build()
-
- # Framework-aware synthetic edges (Django, Laravel, TYPO3, ...). Without
- # this, convention-loaded files appear as in_degree=0 unreachable — false
- # positives in the dead-code report.
- try:
- from repowise.core.generation.editor_files.tech_stack import detect_tech_stack
-
- tech_items = detect_tech_stack(repo_path)
- graph_builder.add_framework_edges([item.name for item in tech_items])
- except Exception as fw_exc:
- # Silence here is the worst of the three sites: the comment above says
- # these edges exist to stop false positives, so a swallowed failure
- # hands the user a longer report and calls it the answer.
- notices.print(
- f"[yellow]Framework edge detection skipped: {fw_exc}; "
- "convention-loaded files may report as unreachable.[/yellow]"
- )
-
# Git metadata (best effort)
git_meta_map: dict = {}
try:
- from repowise.core.ingestion.git_indexer import GitIndexer
-
- git_indexer = GitIndexer(repo_path)
- _, metadata_list = run_async(git_indexer.index_repo(""))
+ _, metadata_list = run_async(GitIndexer(repo_path, read_only=True).index_repo(""))
git_meta_map = {m["file_path"]: m for m in metadata_list}
except Exception:
pass
# parsed_files powers the source-scan rescues (dynamic-import markers,
- # bundler resolve.alias targets, export-alias maps) — without it those
- # classes false-positive on the CLI path while init stays clean.
+ # bundler resolve.alias targets, export-alias maps).
+ stats = graph_builder.traversal_stats
analyzer = DeadCodeAnalyzer(
graph_builder.graph(),
git_meta_map,
@@ -188,10 +144,7 @@ def _analyze_live(repo_path: Path, config: dict, notices: Any) -> DeadCodeReport
repo_root=repo_path,
unindexed_source_files=[
(skipped.path, skipped.reason)
- for skipped in (
- *traverser.stats.skipped_source_files,
- *traverser.stats.unknown_language_files,
- )
+ for skipped in (*stats.skipped_source_files, *stats.unknown_language_files)
],
dotnet_index=getattr(graph_builder, "dotnet_index", None),
)
diff --git a/packages/core/src/repowise/core/ingestion/git_commit_index.py b/packages/core/src/repowise/core/ingestion/git_commit_index.py
index b8cf5a906..06f5c958b 100644
--- a/packages/core/src/repowise/core/ingestion/git_commit_index.py
+++ b/packages/core/src/repowise/core/ingestion/git_commit_index.py
@@ -112,7 +112,9 @@ def _record_ts(record: str) -> int:
return 0
-def _window_records(repo: object, depth: int, cache_dir: Path | None) -> list[str]:
+def _window_records(
+ repo: object, depth: int, cache_dir: Path | None, *, cache_writable: bool = True
+) -> list[str]:
"""The raw log records of the newest ``depth`` non-merge commits.
Git computes ``--numstat`` for every commit in the window, and on a
@@ -122,6 +124,8 @@ def _window_records(repo: object, depth: int, cache_dir: Path | None) -> list[st
only for ``cached_head..HEAD``. The merged list is ordered the way the
full walk orders it (committer time, newest first) and cut to ``depth``,
so the parse below sees the same records a fresh walk would produce.
+ ``cache_writable=False`` reads the cache but leaves it as it was, for the
+ commands that only read the repo.
A cached HEAD that is not an ancestor of the current one (a rebase, a
reset) or a cache of another depth or version is discarded and the full
@@ -143,7 +147,8 @@ def _window_records(repo: object, depth: int, cache_dir: Path | None) -> list[st
records = None
if records is None:
records = _log_records(repo, f"-{depth}")
- _write_window_cache(cache_path, head, depth, records)
+ if cache_writable:
+ _write_window_cache(cache_path, head, depth, records)
return records
@@ -434,6 +439,7 @@ def load_commit_index(
provenance_classifier: object | None = None,
trace_index: object | None = None,
cache_dir: Path | None = None,
+ cache_writable: bool = True,
stats_sink: dict[str, int | bool] | None = None,
renames: RenameTrail | None = None,
) -> dict[str, list[_CommitRec]]:
@@ -506,7 +512,12 @@ def load_commit_index(
return {}
try:
- records = _window_records(repo, depth, cache_dir if since_ts is None else None)
+ records = _window_records(
+ repo,
+ depth,
+ cache_dir if since_ts is None else None,
+ cache_writable=cache_writable,
+ )
except Exception as exc:
logger.warning("repo_commit_index_failed", error=str(exc))
return {}
@@ -731,6 +742,7 @@ def load_sampled_commit_index(
provenance_classifier: object | None = None,
trace_index: object | None = None,
cache_dir: Path | None = None,
+ cache_writable: bool = True,
) -> HistorySample:
"""Resolve the recent, deep, and fallback sampling lanes once.
@@ -753,6 +765,7 @@ def load_sampled_commit_index(
provenance_classifier=provenance_classifier,
trace_index=trace_index,
cache_dir=cache_dir,
+ cache_writable=cache_writable,
stats_sink=recent_stats,
renames=renames,
)
diff --git a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
index db7bb8b82..0e584bc86 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -194,6 +194,7 @@ class GitIndexer:
exclude_patterns: list[str] | None = None,
record_episodes: bool = False,
max_workers: int | None = None,
+ read_only: bool = False,
) -> None:
self.repo_path = Path(repo_path)
self.commit_limit = commit_limit or _DEFAULT_COMMIT_LIMIT
@@ -205,6 +206,9 @@ class GitIndexer:
# episodes would make two nominally read-only commands persist rows
# naming files the repo excludes, and those rows outlive every prune.
self.record_episodes = record_episodes
+ # Same reason: a read-only command reads the commit-window cache but
+ # never rewrites it.
+ self.read_only = read_only
self.max_workers = max_workers
# Read once: which forge's merge messages name a commit's PR or MR.
self.forge = detect_forge(self.repo_path)
@@ -310,6 +314,7 @@ class GitIndexer:
provenance_classifier=prov_clf,
trace_index=trace_index,
cache_dir=self._window_cache_dir(),
+ cache_writable=not self.read_only,
)
commit_index = sample.commits
fallback_files = sample.fallback_files
@@ -673,6 +678,7 @@ class GitIndexer:
provenance_classifier=prov_clf,
trace_index=trace_index,
cache_dir=self._window_cache_dir(),
+ cache_writable=not self.read_only,
)
commit_index = sample.commits
fallback_files = sample.fallback_files
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 5c3cb623b..10b72b4c3 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -59,12 +59,17 @@ def build_repo_graph(
include_nested_repos: bool = False,
log: LogFn | None = None,
timings: PhaseTimings | None = None,
+ read_only: bool = False,
) -> tuple[list, dict[str, bytes], Any, Any, int]:
"""Traverse + parse the repo and build the graph (+ framework-aware edges).
- Shared by the incremental rebuild path (:func:`rebuild_graph_and_git`) and
- the config-triggered re-score path so both build the same graph from the
- same parser and the same synthetic edge step.
+ Shared by the incremental rebuild path (:func:`rebuild_graph_and_git`),
+ the config-triggered re-score path and the commands that analyze the
+ working tree live, so all of them build the same graph from the same
+ parser and the same synthetic edge steps.
+
+ ``read_only`` is for those live commands: the parse cache is read but
+ never written, and no structural episodes or centrality cache are kept.
Files that fail to read/parse are skipped and reported as a count rather than
swallowed silently. ``source_map`` is populated only when ``collect_sources``
@@ -105,12 +110,13 @@ pass reads the sources.
# Structural episodes, minus the formatter check: this path is the hot one
# (every update, plus the config-triggered re-score), so it derives only
# what the walk has already paid for and never spawns a subprocess.
- try:
- from repowise.core.precedent.structural import record_structural_episodes
+ if not read_only:
+ try:
+ from repowise.core.precedent.structural import record_structural_episodes
- record_structural_episodes(repo_path, traverser, allow_formatter_check=False)
- except Exception:
- pass
+ record_structural_episodes(repo_path, traverser, allow_formatter_check=False)
+ except Exception:
+ pass
# Thread-pool source reads + content-hash parse cache split, shared with
# the init parse phase: only changed files need a tree-sitter parse.
@@ -125,6 +131,8 @@ pass reads the sources.
with timed(timings, "rebuild.read"):
fi_and_bytes = _read_sources(file_infos, None)
parse_cache, cached_hits, to_parse = _split_cached(Path(repo_path), fi_and_bytes, None)
+ if read_only:
+ parse_cache = None # hits above still count; misses are not stored
parser: Any = None # constructed lazily — every-file-cached updates skip query compilation
parsed_files: list = []
@@ -132,7 +140,7 @@ pass reads the sources.
graph_builder = GraphBuilder(
repo_path,
exclude_patterns=exclude_patterns,
- centrality_cache_dir=Path(repo_path) / ".repowise",
+ centrality_cache_dir=None if read_only else Path(repo_path) / ".repowise",
head_commit=get_head_commit(Path(repo_path)),
include_submodules=include_submodules,
include_nested_repos=include_nested_repos,
diff --git a/tests/unit/cli/test_dead_code_live_graph.py b/tests/unit/cli/test_dead_code_live_graph.py
new file mode 100644
index 000000000..3c54033f0
--- /dev/null
+++ b/tests/unit/cli/test_dead_code_live_graph.py
@@ -0,0 +1,70 @@
+"""The live ``repowise dead-code`` analysis builds the graph the index builds.
+
+It used to build a bare graph of its own, without the dynamic hints that
+``init`` and ``update`` add, so a module named only by a lazy-registry string
+read as unreachable live while the stored index called it reachable. It also
+must not write into an indexed repo: the command only reads.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+from click.testing import CliRunner
+
+from repowise.cli.commands.dead_code_cmd import dead_code_command
+
+_FILES = {
+ "src/app/__init__.py": "",
+ "src/app/commands/__init__.py": "",
+ "src/app/commands/status_cmd.py": "def status_command():\n return 0\n",
+ "src/app/main.py": (
+ "def register(name, target):\n"
+ " return name, target\n"
+ '_PKG = "app.commands"\n'
+ '_COMMANDS = (("status", "status_cmd:status_command"),)\n'
+ "for name, target in _COMMANDS:\n"
+ ' register(name, f"{_PKG}.{target}")\n'
+ ),
+}
+
+
+def _repo(tmp_path: Path) -> Path:
+ for rel, text in _FILES.items():
+ path = tmp_path / rel
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(text)
+ return tmp_path
+
+
+def _live(repo: Path) -> list[dict]:
+ result = CliRunner().invoke(
+ dead_code_command,
+ [str(repo), "--no-workspace", "--min-confidence", "0.0", "--format", "json"],
+ )
+ assert result.exit_code == 0, result.output
+ return json.loads(result.output[result.output.index("[") :])
+
+
+def test_a_module_named_by_a_lazy_registry_string_is_reachable_live(tmp_path: Path) -> None:
+ findings = _live(_repo(tmp_path))
+
+ unreachable = {f["file_path"] for f in findings if f["kind"] == "unreachable_file"}
+ assert "src/app/commands/status_cmd.py" not in unreachable
+
+
+def test_the_live_analysis_writes_nothing_into_an_indexed_repo(tmp_path: Path) -> None:
+ repo = _repo(tmp_path)
+ for args in (["init", "-q"], ["add", "."], ["commit", "-q", "-m", "init"]):
+ subprocess.run(
+ ["git", "-c", "user.name=t", "-c", "user.email=t@t", *args], cwd=repo, check=True
+ )
+ # An index directory is what turns on the parse, centrality, episode and
+ # git-window caches; an empty one stands in for an indexed repo.
+ (repo / ".repowise").mkdir()
+
+ _live(repo)
+
+ assert list((repo / ".repowise").iterdir()) == []
diff --git a/tests/unit/pipeline/test_update_graph_convergence.py b/tests/unit/pipeline/test_update_graph_convergence.py
index 207be9669..ba8068402 100644
--- a/tests/unit/pipeline/test_update_graph_convergence.py
+++ b/tests/unit/pipeline/test_update_graph_convergence.py
@@ -134,3 +134,23 @@ def test_dynamic_hint_failure_logs_warning_and_does_not_raise(tmp_path: Path) ->
"Dynamic hint extraction failed" in line and "missing from this update" in line
for line in logged_lines
)
+
+
+def test_read_only_build_is_the_update_graph_and_writes_nothing(tmp_path: Path) -> None:
+ """The live commands' read-only build is the update path's graph, minus the writes."""
+ _build_git_repo(tmp_path)
+ index_dir = tmp_path / ".repowise"
+ index_dir.mkdir()
+
+ ro_pf, ro_src, ro_gb, _s, ro_count = build_repo_graph(
+ tmp_path, [], collect_sources=True, read_only=True
+ )
+ assert list(index_dir.iterdir()) == []
+
+ pf, src, gb, _s, count = build_repo_graph(tmp_path, [], collect_sources=True)
+ assert list(index_dir.iterdir()), "the update path keeps its caches"
+
+ assert (ro_count, ro_src) == (count, src)
+ assert [p.file_info.path for p in ro_pf] == [p.file_info.path for p in pf]
+ assert set(ro_gb.graph().nodes()) == set(gb.graph().nodes())
+ assert _edge_set(ro_gb) == _edge_set(gb)