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.

perf(dead-code): read stored findings instead of re-parsing the repo (#2769)

Raghav Chamadiya3618bbfa57de
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md
index fcfaf01f3..4fb28d207 100644
--- a/docs/architecture/ARCHITECTURE.md
+++ b/docs/architecture/ARCHITECTURE.md
@@ -996,6 +996,10 @@ repowise dead-code resolve [FINDING_ID]
--note "reason"
```
+With an index at HEAD, the command reads the findings `init`/`update` stored,
+the same rows `get_dead_code` serves. A floor below the stored one (0.4), an
+index behind HEAD, or no index at all runs the analyzer over the working tree.
+
### 8.4 Integration with Other Components
Dead code findings are stored in the `dead_code_findings` SQL table with a status
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 d6a285011..71bf131dc 100644
--- a/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/dead_code_cmd.py
@@ -3,20 +3,199 @@
from __future__ import annotations
import json
+from pathlib import Path
+from typing import Any
import click
from rich.table import Table
from repowise.cli.helpers import (
console,
+ get_head_commit,
load_state,
+ repo_index_session,
resolve_command_target,
run_async,
silence_logs_for_machine_output,
)
from repowise.cli.output import notice_console
+from repowise.core.analysis.dead_code.models import DeadCodeFindingData, DeadCodeReport
from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE
+#: The floor ``init`` and ``update`` store findings at: they run the analyzer
+#: with its default config, which keeps nothing below this and runs all four
+#: detectors. A request inside that config is answered from the store.
+_STORED_FLOOR = RISK_CAP_CONFIDENCE
+
+#: Finding kind to the config switch that detects it.
+_KIND_SWITCH = {
+ "unreachable_file": "detect_unreachable_files",
+ "unused_export": "detect_unused_exports",
+ "unused_internal": "detect_unused_internals",
+ "zombie_package": "detect_zombie_packages",
+}
+
+
+def _live_reason(repo_path: Path, min_confidence: float) -> str | None:
+ """Why the stored findings cannot answer this request, or ``None`` if they can."""
+ if min_confidence < _STORED_FLOOR:
+ return (
+ f"--min-confidence {min_confidence:g} is below the {_STORED_FLOOR:g} "
+ "floor the index stored"
+ )
+ head = get_head_commit(repo_path)
+ indexed = load_state(repo_path).get("last_sync_commit")
+ if head and indexed and head != indexed:
+ return (
+ f"the index is at {(indexed or 'no commit')[:7]} but HEAD is {head[:7]}; "
+ "run 'repowise update' to make this instant"
+ )
+ return None
+
+
+async def _read_stored(repo_path: Path, config: dict) -> DeadCodeReport | None:
+ """The findings the last ``init``/``update`` stored, or ``None`` with no readable index.
+
+ Deliberate shortcut: an index whose dead-code pass failed stores no rows
+ and reads as a clean repo here, as it already does for ``get_dead_code``.
+ Telling the two apart needs the pass to record that it ran.
+ """
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from repowise.core.persistence.crud import finding_data_from_row, get_dead_code_findings
+
+ async with repo_index_session(repo_path, reconcile=False) as opened:
+ if opened is None:
+ return None
+ session, repo_id = opened
+ try:
+ # Withheld kinds included: this command never applied the registry,
+ # and ``--include-internals`` asks for the hidden kind by name.
+ rows = await get_dead_code_findings(session, repo_id, include_withheld=True)
+ except (SQLAlchemyError, OSError):
+ return None
+ wanted = {kind for kind, switch in _KIND_SWITCH.items() if config[switch]}
+ findings = [finding_data_from_row(r) for r in rows if r.kind in wanted]
+ shown = [f for f in findings if f.confidence >= config["min_confidence"]]
+ return DeadCodeReport.from_findings(
+ shown, hidden_below_threshold=len(findings) - len(shown)
+ )
+
+
+def _notice_stored(repo_path: Path, notices: Any) -> None:
+ from repowise.core.analysis.change_risk import working_tree_is_dirty
+
+ notices.print(
+ f"[dim]Read from the index. Findings below {_STORED_FLOOR:g} are not stored; "
+ "--min-confidence 0.0 computes them live.[/dim]"
+ )
+ if working_tree_is_dirty(str(repo_path)):
+ notices.print(
+ "[yellow]The working tree has changes the index does not include; "
+ "run 'repowise update' after committing to refresh these findings.[/yellow]"
+ )
+
+
+def _finding_order(f: DeadCodeFindingData) -> tuple:
+ """Highest confidence first, then a stable order, whichever path produced it."""
+ return (-f.confidence, f.kind.value, f.file_path, f.start_line or 0, f.symbol_name or "")
+
+
+def _analyze_live(repo_path: Path, config: dict, notices: Any) -> DeadCodeReport:
+ """Parse the working tree and run the analyzer over it."""
+ from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+ from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+ # 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(
+ repo_path,
+ include_submodules=include_submodules,
+ include_nested_repos=include_nested_repos,
+ )
+
+ # 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(""))
+ 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.
+ analyzer = DeadCodeAnalyzer(
+ graph_builder.graph(),
+ git_meta_map,
+ parsed_files=graph_builder._parsed_files,
+ source_map=source_map,
+ repo_root=repo_path,
+ unindexed_source_files=[
+ (skipped.path, skipped.reason)
+ for skipped in (
+ *traverser.stats.skipped_source_files,
+ *traverser.stats.unknown_language_files,
+ )
+ ],
+ )
+ return analyzer.analyze(config)
+
@click.command("dead-code")
@click.argument("path", required=False, type=click.Path(exists=True))
@@ -94,6 +273,10 @@ def dead_code_command(
) -> None:
"""Detect dead and unused code.
+ Reads the findings the last ``init``/``update`` stored when the index is
+ at HEAD and the request is inside what that run computed; otherwise, or
+ with no index, it parses the working tree and analyzes it live.
+
In workspace mode, analyzes the primary repo by default; pass
--repo <alias> to target a different repo. Cross-repo dead-code
detection is not yet supported — run once per repo for now.
@@ -101,11 +284,6 @@ def dead_code_command(
if fmt != "table":
silence_logs_for_machine_output()
- from pathlib import Path as PathlibPath
-
- from repowise.core.analysis.dead_code import DeadCodeAnalyzer
- from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
-
target = resolve_command_target(
path=path,
no_workspace_flag=no_workspace,
@@ -132,78 +310,6 @@ def dead_code_command(
notices.print(f"[bold]repowise dead-code[/bold] — {repo_path}")
- # 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(
- repo_path,
- include_submodules=include_submodules,
- include_nested_repos=include_nested_repos,
- )
-
- # 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 = PathlibPath(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(""))
- git_meta_map = {m["file_path"]: m for m in metadata_list}
- except Exception:
- pass
-
- # Analyze
config: dict = {
"min_confidence": min_confidence,
"detect_unused_internals": include_internals,
@@ -218,26 +324,16 @@ def dead_code_command(
config["detect_unused_internals"] = kind == "unused_internal"
config["detect_zombie_packages"] = kind == "zombie_package"
- # 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.
- analyzer = DeadCodeAnalyzer(
- graph_builder.graph(),
- git_meta_map,
- parsed_files=graph_builder._parsed_files,
- source_map=source_map,
- repo_root=repo_path,
- unindexed_source_files=[
- (skipped.path, skipped.reason)
- for skipped in (
- *traverser.stats.skipped_source_files,
- *traverser.stats.unknown_language_files,
- )
- ],
- )
- report = analyzer.analyze(config)
+ reason = _live_reason(repo_path, min_confidence)
+ report = None if reason else run_async(_read_stored(repo_path, config))
+ if report is None:
+ if reason:
+ notices.print(f"[dim]Computing live: {reason}.[/dim]")
+ report = _analyze_live(repo_path, config, notices)
+ else:
+ _notice_stored(repo_path, notices)
+ findings = sorted(report.findings, key=_finding_order)
- findings = report.findings
if safe_only:
findings = [f for f in findings if f.safe_to_delete]
diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 9d9c64c76..17cbc42a9 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -909,26 +909,8 @@ class DeadCodeAnalyzer:
hidden_below_threshold = sum(1 for f in findings if f.confidence < min_conf)
findings = [f for f in findings if f.confidence >= min_conf]
- now = datetime.now(UTC)
- # Sum of the known counts: a lower bound when any count is unknown.
- deletable = sum(f.lines or 0 for f in findings if f.safe_to_delete)
-
- high = sum(1 for f in findings if f.confidence >= SAFE_CONFIDENCE_THRESHOLD)
- medium = sum(
- 1
- for f in findings
- if RISK_CAP_CONFIDENCE <= f.confidence < SAFE_CONFIDENCE_THRESHOLD
- )
- low = sum(1 for f in findings if f.confidence < RISK_CAP_CONFIDENCE)
-
- return DeadCodeReport(
- repo_id="",
- analyzed_at=now,
- total_findings=len(findings),
- findings=findings,
- deletable_lines=deletable,
- confidence_summary={"high": high, "medium": medium, "low": low},
- hidden_below_threshold=hidden_below_threshold,
+ return DeadCodeReport.from_findings(
+ findings, hidden_below_threshold=hidden_below_threshold
)
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/analysis/dead_code/models.py b/packages/core/src/repowise/core/analysis/dead_code/models.py
index 4b02bd3fd..f01bff6de 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/models.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/models.py
@@ -3,9 +3,11 @@
from __future__ import annotations
from dataclasses import dataclass, field
-from datetime import datetime
+from datetime import UTC, datetime
from enum import StrEnum
+from .risk_factors import RISK_CAP_CONFIDENCE, SAFE_CONFIDENCE_THRESHOLD
+
class DeadCodeKind(StrEnum):
UNREACHABLE_FILE = "unreachable_file"
@@ -63,3 +65,21 @@ class DeadCodeReport:
#: file's stored verdict alone rather than overwriting it with a guess.
#: A full run has metadata for everything and leaves this ``None``.
authoritative_paths: frozenset[str] | None = None
+
+ @classmethod
+ def from_findings(
+ cls, findings: list[DeadCodeFindingData], *, hidden_below_threshold: int = 0
+ ) -> DeadCodeReport:
+ """The report over *findings*, already cut at the confidence floor."""
+ high = sum(1 for f in findings if f.confidence >= SAFE_CONFIDENCE_THRESHOLD)
+ low = sum(1 for f in findings if f.confidence < RISK_CAP_CONFIDENCE)
+ return cls(
+ repo_id="",
+ analyzed_at=datetime.now(UTC),
+ total_findings=len(findings),
+ findings=findings,
+ # Sum of the known counts: a lower bound when any count is unknown.
+ deletable_lines=sum(f.lines or 0 for f in findings if f.safe_to_delete),
+ confidence_summary={"high": high, "medium": len(findings) - high - low, "low": low},
+ hidden_below_threshold=hidden_below_threshold,
+ )
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index bd4536ed3..f7b4a6d55 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -41,6 +41,7 @@ from .coverage_map import (
tests_covering_files,
)
from .dead_code import (
+ finding_data_from_row,
get_dead_code_findings,
get_dead_code_summary,
replace_dead_code_findings,
@@ -143,6 +144,7 @@ __all__ = [
"finalize_performance_opportunities",
"finalize_refactoring_opportunities",
"finalize_refactoring_suggestions",
+ "finding_data_from_row",
"get_average_health",
"get_coverage_summary",
"get_dead_code_findings",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
index e8dc10c88..043e1361a 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/dead_code.py
@@ -8,10 +8,12 @@ from typing import Any
from sqlalchemy import select, text
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.dead_code.models import DeadCodeFindingData, DeadCodeKind
from repowise.core.analysis.dead_code.risk_factors import (
RISK_CAP_CONFIDENCE,
SAFE_CONFIDENCE_THRESHOLD,
effective_safe_to_delete,
+ path_risk_factors,
)
from repowise.core.analysis.finding_registry import excluded_types
@@ -58,6 +60,34 @@ def _dead_code_row_kwargs(finding: Any, repository_id: str) -> dict:
}
+def finding_data_from_row(row: DeadCodeFinding) -> DeadCodeFindingData:
+ """The analyzer's finding for a stored row: the inverse of ``_dead_code_row_kwargs``.
+
+ Risk factors are not stored, so they are re-derived from the path, and
+ deletion-readiness is re-derived the way every read surface does it.
+ """
+ return DeadCodeFindingData(
+ kind=DeadCodeKind(row.kind),
+ file_path=row.file_path,
+ symbol_name=row.symbol_name,
+ symbol_kind=row.symbol_kind,
+ confidence=row.confidence,
+ reason=row.reason,
+ last_commit_at=row.last_commit_at,
+ commit_count_90d=row.commit_count_90d,
+ lines=row.lines,
+ evidence=json.loads(row.evidence_json or "[]"),
+ safe_to_delete=effective_safe_to_delete(
+ row.confidence, row.file_path, row.safe_to_delete, row.kind
+ ),
+ primary_owner=row.primary_owner,
+ age_days=row.age_days,
+ risk_factors=list(path_risk_factors(row.file_path)),
+ start_line=row.start_line,
+ end_line=row.end_line,
+ )
+
+
async def _lines_column_rejects_null(session: AsyncSession) -> bool:
"""True for a SQLite store created before ``lines`` became nullable.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
index 9e41dc1ed..efb8e0533 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
@@ -21,11 +21,9 @@ from repowise.core.analysis.finding_registry import (
verification_label,
withheld_summary,
)
+from repowise.core.persistence.crud import get_dead_code_findings
from repowise.core.persistence.database import get_session
-from repowise.core.persistence.models import (
- DeadCodeFinding,
- GitMetadata,
-)
+from repowise.core.persistence.models import GitMetadata
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server import _state
from repowise.server.mcp_server._basis import call_resolution_bases
@@ -129,13 +127,10 @@ async def _get_dead_code_all_repos(
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
- all_query = select(DeadCodeFinding).where(
- DeadCodeFinding.repository_id == repository.id,
- DeadCodeFinding.status == "open",
- )
- all_result = await session.execute(all_query)
repo_findings = filter_rows_by_attr(
- list(all_result.scalars().all()), "file_path", _get_exclude_spec(ctx.path)
+ await get_dead_code_findings(session, repository.id, include_withheld=True),
+ "file_path",
+ _get_exclude_spec(ctx.path),
)
repo_findings, repo_withheld = filters.split_withheld(repo_findings)
for name, entry in repo_withheld.items():
@@ -399,13 +394,11 @@ async def get_dead_code(
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
- # Fetch all open findings for summary computation
- all_query = select(DeadCodeFinding).where(
- DeadCodeFinding.repository_id == repository.id,
- DeadCodeFinding.status == "open",
+ # Fetch all open findings for summary computation. Withheld kinds are
+ # read too, so the summary can count what it leaves out.
+ all_findings, withheld = filters.split_withheld(
+ await get_dead_code_findings(session, repository.id, include_withheld=True)
)
- all_result = await session.execute(all_query)
- all_findings, withheld = filters.split_withheld(list(all_result.scalars().all()))
# Phase 4: load git metadata for "last meaningful change" enrichment
git_meta_map = await _load_git_meta_map(session, repository.id, all_findings)
diff --git a/tests/unit/cli/test_dead_code_stored.py b/tests/unit/cli/test_dead_code_stored.py
new file mode 100644
index 000000000..aca478410
--- /dev/null
+++ b/tests/unit/cli/test_dead_code_stored.py
@@ -0,0 +1,146 @@
+"""`repowise dead-code` reads the findings the index stored instead of re-parsing.
+
+The stored path answers the default request when the index is at HEAD; a flag
+the stored run did not compute (a floor below the one it stored at) and an
+index behind HEAD fall back to the live analysis. Both paths print one shape.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands import dead_code_cmd
+from repowise.cli.commands.dead_code_cmd import dead_code_command
+from repowise.cli.helpers import run_async
+
+# A finding the live analyzer can never produce for this tree: the file does
+# not exist, so seeing it proves the answer came from the store.
+_STORED_ONLY = {
+ "kind": "unused_export",
+ "file_path": "gone/only_in_store.py",
+ "symbol_name": "stored_symbol",
+ "symbol_kind": "function",
+ "confidence": 0.9,
+ "reason": "Public symbol 'stored_symbol' has no importers",
+ "lines": 4,
+ "start_line": 1,
+ "end_line": 4,
+ "evidence": ["stored"],
+ "safe_to_delete": True,
+ "commit_count_90d": 0,
+}
+
+
+def _git(cwd: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=cwd, check=True, capture_output=True, text=True
+ ).stdout.strip()
+
+
+async def _store(repo_path: Path, findings: list[dict]) -> None:
+ from repowise.core.persistence import (
+ create_engine,
+ create_session_factory,
+ get_session,
+ init_db,
+ upsert_repository,
+ )
+ from repowise.core.persistence.crud import save_dead_code_findings
+
+ db_path = repo_path / ".repowise" / "wiki.db"
+ engine = create_engine(f"sqlite+aiosqlite:///{db_path.as_posix()}")
+ try:
+ await init_db(engine)
+ async with get_session(create_session_factory(engine)) as session:
+ repo = await upsert_repository(session, name="repo", local_path=str(repo_path))
+ await save_dead_code_findings(session, repo.id, findings)
+ finally:
+ await engine.dispose()
+
+
+def indexed_repo(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path:
+ monkeypatch.delenv("REPOWISE_DB_URL", raising=False)
+ monkeypatch.delenv("REPOWISE_DATABASE_URL", raising=False)
+ root = tmp_path.resolve()
+ _git(root, "init", "-q")
+ _git(root, "config", "user.email", "[email protected]")
+ _git(root, "config", "user.name", "A")
+ (root / ".gitignore").write_text(".repowise/\n")
+ (root / "a.py").write_text("def unused():\n return 1\n")
+ _git(root, "add", ".")
+ _git(root, "commit", "-q", "-m", "init")
+ (root / ".repowise").mkdir()
+ state = {"last_sync_commit": _git(root, "rev-parse", "HEAD")}
+ (root / ".repowise" / "state.json").write_text(json.dumps(state))
+ run_async(_store(root, [_STORED_ONLY]))
+ return root
+
+
+def _json(root: Path, *args: str) -> list[dict]:
+ result = CliRunner().invoke(
+ dead_code_command, [str(root), "--format", "json", "--no-workspace", *args]
+ )
+ assert result.exit_code == 0, result.output
+ return json.loads(result.output[result.output.index("[") :])
+
+
+def test_default_flags_read_the_store_without_parsing(indexed_repo, monkeypatch):
+ def _no_parse(*_a, **_k):
+ raise AssertionError("the live analysis ran for a request the store answers")
+
+ monkeypatch.setattr(dead_code_cmd, "_analyze_live", _no_parse)
+
+ findings = _json(indexed_repo)
+
+ assert [f["file_path"] for f in findings] == [_STORED_ONLY["file_path"]]
+ assert findings[0]["safe_to_delete"] is True
+
+
+def test_a_floor_below_the_stored_one_runs_live(indexed_repo):
+ findings = _json(indexed_repo, "--min-confidence", "0.0")
+
+ assert _STORED_ONLY["file_path"] not in {f["file_path"] for f in findings}
+
+
+def test_an_index_behind_head_runs_live(indexed_repo):
+ (indexed_repo / "b.py").write_text("x = 1\n")
+ _git(indexed_repo, "add", "b.py")
+ _git(indexed_repo, "commit", "-q", "-m", "second")
+
+ findings = _json(indexed_repo)
+
+ assert _STORED_ONLY["file_path"] not in {f["file_path"] for f in findings}
+
+
+def test_kind_switches_filter_the_stored_rows(indexed_repo, monkeypatch):
+ monkeypatch.setattr(dead_code_cmd, "_analyze_live", None)
+
+ assert _json(indexed_repo, "--no-unused-exports") == []
+ assert len(_json(indexed_repo, "--kind", "unused_export")) == 1
+
+
+def test_both_paths_print_one_shape(indexed_repo):
+ stored = _json(indexed_repo)
+ live = _json(indexed_repo, "--min-confidence", "0.0")
+
+ assert live, "the live fixture must produce a finding to compare"
+ assert {tuple(f) for f in stored} == {tuple(f) for f in live}
+
+
+def test_uncommitted_changes_are_noted_not_recomputed(indexed_repo, monkeypatch):
+ monkeypatch.setattr(dead_code_cmd, "_analyze_live", None)
+ (indexed_repo / "a.py").write_text("def unused():\n return 2\n")
+
+ result = CliRunner().invoke(
+ dead_code_command, [str(indexed_repo), "--format", "md", "--no-workspace"]
+ )
+
+ assert result.exit_code == 0, result.output
+ assert "working tree has changes the index does not include" in result.output
+ assert "stored_symbol" in result.output