Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(dead-code): persist the repo-wide verdict an update already computed (#1389)
Raghav Chamadiya6a22d8cd1221
diff --git a/docs/architecture/deep-dives.md b/docs/architecture/deep-dives.mdindex 0ac018007..4d5802813 100644--- a/docs/architecture/deep-dives.md+++ b/docs/architecture/deep-dives.md@@ -273,17 +273,11 @@ DeadCodeAnalyzer.analyze()### Incremental dead code analysis-When files change (via `repowise update`), full re-analysis is wasteful. `analyze_partial()` only checks affected files:+`repowise update` runs the same repo-wide `analyze()` a full index runs, and persists the whole result.-```python-def analyze_partial(affected_files, config):- for node in affected_files:- if node not in graph: continue- if in_degree(node) == 0 and not entry_point and not test:- → Check if this file became unreachable due to the change-```+Scoping the detectors to the changed files is not available here, because dead code is a cross-file property: removing the last import of a module makes *that module* dead, and the module is not in the change set. An earlier `analyze_partial()` filtered the repo-wide report down to the changed files before persisting it, and the effect was that any file a change had made dead — or brought back to life — kept its previous verdict until someone re-indexed from scratch.-This is O(affected_files) instead of O(all_files). Only detects newly-unreachable files — it doesn't re-check unused exports or zombie packages (those need the full graph).+What the update path does have to be careful about is confidence, which is scored per file from git metadata. An update re-indexes git metadata for the changed files only, and a file with no metadata is indistinguishable from a file with no commits, so it would score 0.7 with `safe_to_delete=True` however actively it is committed to. The analyzer is therefore also handed the persisted per-file git fields, and the report carries `authoritative_paths`: the set of files it was actually able to score. Persistence replaces findings for those files and leaves every other file's stored verdict alone, so a partial or failed metadata read narrows what gets written rather than overwriting the index with guesses.---diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.pyindex afa05f46e..5c6b07fb6 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py@@ -43,6 +43,7 @@ from repowise.core.reasoning import REASONING_MODESfrom .incremental import (_build_update_vector_store,+ _load_stored_git_meta,_rebuild_graph_and_git,_refresh_knowledge_graph,_run_partial_analysis,@@ -1201,8 +1202,17 @@ def run_update()return UpdateOutcome.DRY_RUN+ # ``git_meta_map`` holds this run's changed files only; the dead-code+ # analyzer scores confidence per file and would read every unchanged file+ # as "no commits" without the stored rows.partial_health_report, dead_code_report = _run_partial_analysis(- repo_path, graph_builder, git_meta_map, parsed_files, file_diffs, source_map+ repo_path,+ graph_builder,+ git_meta_map,+ parsed_files,+ file_diffs,+ source_map,+ stored_git_meta=_load_stored_git_meta(repo_path),)# Partial health has consumed the per-file ``BlameIndex``; drop it beforediff --git a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.pyindex 3d0e7be64..dfceb0886 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py@@ -147,6 +147,17 @@ def _refresh_knowledge_graph()+def _load_stored_git_meta(repo_path: Any) -> dict[str, dict]:+ """Persisted per-file git fields for the dead-code analyzer.++ Delegates to :mod:`repowise.core.pipeline.incremental`. Best-effort: an+ unreadable store yields ``{}``.+ """+ from repowise.core.pipeline.incremental import load_stored_git_meta++ return run_async(load_stored_git_meta(repo_path, log=console.print))++def _run_partial_analysis(repo_path: Any,graph_builder: Any,@@ -154,8 +165,9 @@ def _run_partial_analysis(parsed_files: list,file_diffs: list,source_map: dict[str, bytes] | None = None,+ stored_git_meta: dict[str, dict] | None = None,) -> tuple[Any, Any]:- """Run partial code-health + dead-code analysis for the changed files.+ """Run partial code-health + repo-wide dead-code analysis.Delegates to :mod:`repowise.core.pipeline.incremental` — the logic movedto core so workspace updates can reuse the incremental path.@@ -172,5 +184,6 @@ def _run_partial_analysis(parsed_files,file_diffs,source_map=source_map,+ stored_git_meta=stored_git_meta,log=console.print,)diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex 58d3a65e7..4003c25a8 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -469,6 +469,7 @@ def _persist_index_only_update(degraded=degraded,pages_rendered=pages_rendered,template_wiki=template_wiki,+ changed_paths=changed_paths,)@@ -880,18 +881,22 @@ async def _persist_full_update_async(except Exception as exc:_skip("Health persist", exc)- # Scoped to changed files so unchanged files keep their findings (#295).+ # Repo-wide. The old file-scoped write kept unchanged files' rows+ # (#295) at the price of never correcting them: the analysis is+ # repo-wide and dead code is a cross-file property, so dropping an+ # import could make a module dead and that module, being unchanged,+ # kept its stale verdict until the next full re-index.if dead_code_report is not None:try:import dataclasses as _dc_dead- from repowise.core.persistence.crud import upsert_dead_code_findings+ from repowise.core.persistence.crud import replace_dead_code_findings- await upsert_dead_code_findings(+ await replace_dead_code_findings(session,repo_id,[_dc_dead.asdict(f) for f in dead_code_report.findings],- file_paths=[fd.path for fd in file_diffs],+ scope=dead_code_report.authoritative_paths,)except Exception as exc:_skip("Dead-code persist", exc)diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py b/packages/cli/src/repowise/cli/commands/update_cmd/reporting.pyindex 5a6309638..c1940d95f 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/reporting.py@@ -178,9 +178,21 @@ def render_degraded(degraded: list[str] | None) -> None:console.print(f" [yellow]-[/yellow] {entry}")-def _dead_code_counts(dead_code_report: Any) -> tuple[int, int]:- """Return ``(unreachable_files, unused_exports)`` from a dead-code report."""+def _dead_code_counts(+ dead_code_report: Any, changed_paths: list[str] | None = None+) -> tuple[int, int]:+ """Return ``(unreachable_files, unused_exports)`` from a dead-code report.++ The report is repo-wide, but this panel is a summary of the update that+ just ran, so the counts stay scoped to the files it touched. Reporting the+ repo-wide totals here would turn a one-file update on a large repo into+ "Dead code 759 unreachable" where it previously said 0, which reads as+ the update having caused it.+ """findings = dead_code_report.findings if dead_code_report else []+ if changed_paths is not None:+ scope = set(changed_paths)+ findings = [f for f in findings if f.file_path in scope]unreachable = sum(1 for f in findings if f.kind.value == "unreachable_file")unused = sum(1 for f in findings if f.kind.value == "unused_export")return unreachable, unused@@ -235,6 +247,7 @@ def show_index_only_completion(degraded: list[str] | None = None,pages_rendered: int = 0,template_wiki: bool = False,+ changed_paths: list[str] | None = None,) -> None:"""Render the completion panel for an index-only update (no LLM regen).@@ -244,7 +257,7 @@ def show_index_only_completion("""render_degraded(degraded)graph = graph_builder.graph()- unreachable, unused = _dead_code_counts(dead_code_report)+ unreachable, unused = _dead_code_counts(dead_code_report, changed_paths)metrics: list[tuple[str, str]] = [("Files changed", str(changed_count)),diff --git a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.pyindex 7f70b6f29..b8cab93e8 100644--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py@@ -491,17 +491,78 @@ def _never_flag_regex(patterns: tuple[str, ...]) -> re.Pattern[str]:return re.compile("|".join(fnmatch.translate(os.path.normcase(p)) for p in patterns))+@lru_cache(maxsize=8)+def _never_flag_suffix_index(+ patterns: tuple[str, ...],+) -> tuple[re.Pattern[str] | None, dict[str, re.Pattern[str]], tuple[int, ...]]:+ """Split *patterns* into suffix-keyed buckets that can be skipped wholesale.++ ``_never_flag_regex`` puts all 579 patterns in one alternation, and+ ``.match()`` tries every branch at position 0 — most of them beginning+ ``.*``, so each branch scans the path. Measured cold on a 63k-node repo+ that is 206 microseconds per unique path and 12.8s of an 18.1s dead-code+ analysis, the single largest cost in the pass.++ The filter is sound because ``fnmatch.translate`` ends *each* alternative+ with ``\\Z`` and the join keeps that per-branch (``(?s:A)\\Z|(?s:B)\\Z``),+ so every branch has to match the whole string. A pattern whose text after+ its last ``*`` is the literal ``S`` can therefore only match a path ending+ in ``S``: testing it against a path that does not end in ``S`` is wasted+ work, never a dropped match. Patterns ending in ``*`` constrain nothing at+ the tail and stay in one always-tried group.++ Within a bucket the branches keep their original translated form, so the+ atomic groups ``fnmatch`` emits for interior ``*literal`` runs — which+ commit to the first occurrence and never retry a later one — behave+ exactly as they did in the single alternation. Alternation order does not+ matter to a boolean "did anything match".++ Returns ``(always_tried_regex_or_None, {suffix: regex}, suffix_lengths)``.+ """+ always: list[str] = []+ by_suffix: dict[str, list[str]] = {}+ for pattern in patterns:+ norm = os.path.normcase(pattern)+ # No pattern in the set uses ``?`` or a character class (checked by+ # test_never_flag_suffix_index_covers_pattern_shapes), so the text+ # after the last ``*`` is a plain literal tail.+ suffix = norm.rsplit("*", 1)[-1]+ translated = fnmatch.translate(norm)+ if suffix:+ by_suffix.setdefault(suffix, []).append(translated)+ else:+ always.append(translated)+ compiled = {s: re.compile("|".join(v)) for s, v in by_suffix.items()}+ return (+ re.compile("|".join(always)) if always else None,+ compiled,+ tuple(sorted({len(s) for s in compiled})),+ )++@lru_cache(maxsize=131072)def _never_flag_regex_match(path: str) -> bool:- """Memoized ``_never_flag_regex`` match for the default pattern set.-- The alternation has ~540 branches, so one match costs tens of- microseconds, and the detector passes ask about the same node ids- repeatedly (every graph node is checked by both the unreachable-files- and unused-exports passes). Pure function of *path*: the pattern set is- a module constant, so process-wide memoization is sound.+ """Memoized never-flag match for the default pattern set.++ Equivalent to ``_never_flag_regex(_NEVER_FLAG_PATTERNS).match(...)``, and+ pinned to it path-for-path by ``test_never_flag_regex.py``. Pure function+ of *path*: the pattern set is a module constant, so process-wide+ memoization is sound. The detector passes ask about the same node ids+ repeatedly (every graph node is checked by the unreachable-files and the+ unused-exports passes), which is what the cache is for; this function is+ what the *first* ask of each id costs."""- return _never_flag_regex(_NEVER_FLAG_PATTERNS).match(os.path.normcase(path)) is not None+ norm = os.path.normcase(path)+ always, by_suffix, suffix_lengths = _never_flag_suffix_index(_NEVER_FLAG_PATTERNS)+ if always is not None and always.match(norm):+ return True+ for length in suffix_lengths:+ if length > len(norm):+ break+ bucket = by_suffix.get(norm[-length:])+ if bucket is not None and bucket.match(norm):+ return True+ return Falseclass DeadCodeAnalyzer:@@ -642,33 +703,6 @@ class DeadCodeAnalyzer:confidence_summary={"high": high, "medium": medium, "low": low},)- def analyze_partial(- self, affected_files: list[str], config: dict | None = None- ) -> DeadCodeReport:- """Run the full detector suite, then narrow findings to ``affected_files``.-- Persisted via the file-scoped ``upsert_dead_code_findings`` so unchanged- files keep their findings. Cross-file effects on unchanged files are not- recomputed here; the full ``analyze()`` remains authoritative.- """- affected_set = set(affected_files)- full = self.analyze(config)- findings = [f for f in full.findings if f.file_path in affected_set]-- deletable = sum(f.lines for f in findings if f.safe_to_delete)- high = sum(1 for f in findings if f.confidence >= 0.7)- medium = sum(1 for f in findings if 0.4 <= f.confidence < 0.7)- low = sum(1 for f in findings if f.confidence < 0.4)-- return DeadCodeReport(- repo_id="",- analyzed_at=full.analyzed_at,- total_findings=len(findings),- findings=findings,- deletable_lines=deletable,- confidence_summary={"high": high, "medium": medium, "low": low},- )-# ------------------------------------------------------------------# Detection methods# ------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/analysis/dead_code/models.py b/packages/core/src/repowise/core/analysis/dead_code/models.pyindex 869550426..959d3bb9b 100644--- a/packages/core/src/repowise/core/analysis/dead_code/models.py+++ b/packages/core/src/repowise/core/analysis/dead_code/models.py@@ -48,3 +48,12 @@ class DeadCodeReport:findings: list[DeadCodeFindingData]deletable_lines: intconfidence_summary: dict # {"high": N, "medium": N, "low": N}+ #: The file paths this report is allowed to speak for, or ``None`` for+ #: "all of them". Confidence is scored from per-file git metadata, and a+ #: file with no metadata is indistinguishable from one with no commits —+ #: it scores 0.7 with ``safe_to_delete=True`` however active it is. The+ #: incremental path can only obtain metadata for some files, so it sets+ #: this to the set it actually has, and persistence leaves every other+ #: 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 = Nonediff --git a/packages/core/src/repowise/core/persistence/__init__.py b/packages/core/src/repowise/core/persistence/__init__.pyindex 6616117a9..52e64d5e3 100644--- a/packages/core/src/repowise/core/persistence/__init__.py+++ b/packages/core/src/repowise/core/persistence/__init__.py@@ -38,6 +38,7 @@ from .crud import (get_conversation,get_cross_community_edges,get_dead_code_findings,+ get_dead_code_git_fields,get_dead_code_summary,get_decision,get_decision_health_summary,@@ -226,6 +227,7 @@ __all__ = ["get_db_url",# dead code crud"get_dead_code_findings",+ "get_dead_code_git_fields","get_dead_code_summary","get_decision","get_decision_edges",diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.pyindex 82aa85ae5..0e43d2c1b 100644--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py@@ -24,9 +24,9 @@ from .coverage_map import (from .dead_code import (get_dead_code_findings,get_dead_code_summary,+ replace_dead_code_findings,save_dead_code_findings,update_dead_code_status,- upsert_dead_code_findings,)from .health import (HEALTH_SNAPSHOT_RETENTION,@@ -83,6 +83,7 @@ __all__ = ["get_test_coverage_summary","list_health_snapshots","load_coverage_for_repo",+ "replace_dead_code_findings","replace_governance_findings","save_coverage_files","save_dead_code_findings",@@ -95,7 +96,6 @@ __all__ = ["tests_covering","update_dead_code_status","update_health_finding_status",- "upsert_dead_code_findings","upsert_health_findings","upsert_health_metrics","upsert_refactoring_suggestions",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.pyindex 03dd40230..97e8e916d 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@@ -77,40 +77,78 @@ async def save_dead_code_findings(await session.flush()-async def upsert_dead_code_findings(+def _finding_identity(finding: Any) -> tuple:+ """The (file, kind, symbol) triple that makes two findings the same finding.++ Compared against ``DeadCodeFinding`` rows, whose ``kind`` column holds the+ enum's *value*. Both shapes reach here: the dataclass (workspace path) and+ ``dataclasses.asdict`` output (CLI path), and ``asdict`` leaves the+ ``DeadCodeKind`` member intact rather than converting it. ``DeadCodeKind``+ is a ``StrEnum``, so ``str()`` happens to give the value today; unwrapping+ ``.value`` states the requirement instead of inheriting it from the mixin.+ """+ kind = finding.kind if hasattr(finding, "kind") else finding.get("kind", "")+ symbol = finding.symbol_name if hasattr(finding, "kind") else finding.get("symbol_name")+ return (_finding_file_path(finding), str(getattr(kind, "value", kind)), symbol)+++async def replace_dead_code_findings(session: AsyncSession,repository_id: str,findings: list[Any],*,- file_paths: list[str],+ scope: frozenset[str] | set[str] | None = None,) -> None:- """Replace open dead-code findings **only for the given file paths**.-- Used by the incremental ``repowise update`` path so unchanged files keep- their findings instead of being wiped on every partial re-index. Callers- must pass the full set of *changed* file paths (not just paths that- produced findings) so a changed-but-now-clean file has its stale findings- removed.+ """Replace open dead-code findings, for *scope* or for the whole repository.++ The incremental update path used to replace findings only for the files+ that changed, which meant an unchanged file kept whatever verdict the last+ full index gave it. Dead code is a cross-file property — removing the last+ import of a module makes *that module* dead, and it is not in the change+ set — so a change-scoped write can never express the result of the+ analysis that produced it. The analyzer computes the repo-wide truth+ either way; this persists it rather than discarding the inconvenient part.++ *scope* is the set of file paths the caller can actually speak for, and+ ``None`` means all of them. It is not a performance knob and not a+ threshold: dead-code confidence is scored from per-file git metadata, and+ a file the caller has no metadata for scores 0.7 with+ ``safe_to_delete=True`` however actively it is committed to. Writing that+ would be worse than writing nothing, so a caller holding partial metadata+ passes the part it has and every other file keeps its stored verdict.+ Rows outside *scope* are neither deleted nor inserted.++ Findings the user has acted on are not resurrected. The delete is scoped+ to ``status == "open"``, so a dismissed or resolved row survives it, and+ any incoming finding matching such a row by (file, kind, symbol) is+ dropped rather than re-inserted as a fresh ``open`` duplicate. Without+ that second half a repo-wide write would re-open every dismissal on every+ update, which the old change-scoped write only did for changed files.++ There is no unique constraint on that triple (and ``symbol_name`` is+ nullable, so one would not bite without a functional index), hence+ delete-then-insert with the surviving keys filtered out in Python rather+ than an ``ON CONFLICT`` upsert."""- if not file_paths:- return- allowed = set(file_paths)existing = await session.execute(- select(DeadCodeFinding).where(- DeadCodeFinding.repository_id == repository_id,- DeadCodeFinding.status == "open",- DeadCodeFinding.file_path.in_(file_paths),- )+ select(DeadCodeFinding).where(DeadCodeFinding.repository_id == repository_id))+ acted_on: set[tuple] = set()for row in existing.scalars().all():- await session.delete(row)+ if scope is not None and row.file_path not in scope:+ continue+ if row.status == "open":+ await session.delete(row)+ else:+ acted_on.add((row.file_path, row.kind, row.symbol_name))await session.flush()- # Insert only within the replaced scope (delete is scoped to file_paths).- scoped = [f for f in findings if _finding_file_path(f) in allowed]- for i in range(0, len(scoped), _BATCH_SIZE):- batch = scoped[i : i + _BATCH_SIZE]+ writable = [f for f in findings if scope is None or _finding_file_path(f) in scope]+ for i in range(0, len(writable), _BATCH_SIZE):+ batch = writable[i : i + _BATCH_SIZE]for finding in batch:+ if _finding_identity(finding) in acted_on:+ continuesession.add(DeadCodeFinding(**_dead_code_row_kwargs(finding, repository_id)))await session.flush()diff --git a/packages/core/src/repowise/core/persistence/crud/git.py b/packages/core/src/repowise/core/persistence/crud/git.pyindex 39e5136d9..670a8e623 100644--- a/packages/core/src/repowise/core/persistence/crud/git.py+++ b/packages/core/src/repowise/core/persistence/crud/git.py@@ -105,6 +105,45 @@ async def get_all_git_metadata(session: AsyncSession, repository_id: str) -> dicreturn {gm.file_path: gm for gm in result.scalars().all()}+#: The only git fields dead-code confidence is scored from+#: (``analyzer._make_unreachable_finding`` and its sibling detectors).+_DEAD_CODE_GIT_FIELDS = (+ "commit_count_90d",+ "last_commit_at",+ "age_days",+ "primary_owner_name",+)+++async def get_dead_code_git_fields(session: AsyncSession, repository_id: str) -> dict[str, dict]:+ """Return ``{file_path: {field: value}}`` for the dead-code scoring fields.++ The incremental update path re-indexes git metadata for the *changed* files+ only, so the dead-code analyzer otherwise sees an empty dict for every+ unchanged file — which lands each one on the ``commit_count_90d == 0``+ branch of the confidence ladder (0.7, ``safe_to_delete=True``) however+ actively the file is committed to. This supplies the stored value instead.++ Deliberately four narrow columns rather than ``get_all_git_metadata``'s+ whole ORM rows: this runs on every update over every file in the repo, and+ hydrating 60k full rows to read four fields is the cost that was just taken+ out of ``backfill_related_pages``.++ The values are one update-interval stale for idle files, whose time-decayed+ windows are rewritten later in the same run, after analysis. That is+ strictly closer to the truth than the empty dict it replaces.+ """+ rows = (+ await session.execute(+ select(+ GitMetadata.file_path,+ *(getattr(GitMetadata, f) for f in _DEAD_CODE_GIT_FIELDS),+ ).where(GitMetadata.repository_id == repository_id)+ )+ ).all()+ return {r[0]: dict(zip(_DEAD_CODE_GIT_FIELDS, r[1:], strict=True)) for r in rows}++# Repo-wide-walk signals (co-change pairs, Hassan entropy). A pass that did# not run the walk — ESSENTIAL tier, or an incremental update without the# tracked-file set — reports the empty default for these; overwriting blindlydiff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 776a8b6c1..8bec348e1 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -311,6 +311,62 @@ async def rebuild_graph_and_git(return parsed_files, source_map, graph_builder, repo_structure, file_count, git_meta_map+async def load_stored_git_meta(+ repo_path: Any, *, log: LogFn | None = None+) -> dict[str, dict] | None:+ """Read the persisted per-file git fields the dead-code analyzer scores on.++ Returns ``None`` when the store could not be read, and a mapping (possibly+ an empty one) when it could. The caller has to tell those apart: an empty+ mapping is a repository whose ``git_metadata`` genuinely holds nothing,+ which scores exactly the way a full index would score it, whereas a failed+ read means this run knows less than a full index does and must not+ overwrite what a full index wrote.++ Not every indexed file has a row even on a healthy repository — ``git+ metadata`` covers what ``index_repo`` produced, which excludes skipped+ paths — so a *missing file* is not evidence of a failure and a coverage+ count cannot stand in for one.+ """+ log = log or _noop_log+ # Never create the store as a side effect of reading it. A repo whose+ # wiki.db was deleted to force a rebuild would otherwise be handed an+ # empty one here, and an empty database reads as "indexed" downstream.+ # Same guard, and the same reason, as the head-commit stamper.+ if not (Path(repo_path) / ".repowise" / "wiki.db").is_file():+ log("[yellow]No store to read git metadata from; dead-code scope narrowed[/yellow]")+ return None+ try:+ from repowise.core.persistence import (+ create_engine,+ create_session_factory,+ get_dead_code_git_fields,+ get_session,+ )+ from repowise.core.persistence.crud import get_repository_by_path+ from repowise.core.persistence.database import resolve_db_url++ engine = create_engine(resolve_db_url(repo_path))+ try:+ async with get_session(create_session_factory(engine)) as session:+ repo = await get_repository_by_path(session, str(repo_path))+ if repo is None:+ # The persist path resolves the repository with an upsert,+ # so a miss here means this run would be writing against a+ # row that does not exist yet. Unknown, not empty.+ log(+ f"[yellow]No stored repository for {repo_path}; "+ "dead-code scope narrowed[/yellow]"+ )+ return None+ return await get_dead_code_git_fields(session, repo.id)+ finally:+ await engine.dispose()+ except Exception as exc:+ log(f"[yellow]Stored git metadata unavailable for dead-code scoring: {exc}[/yellow]")+ return None++def run_partial_analysis(repo_path: Any,graph_builder: Any,@@ -319,15 +375,30 @@ def run_partial_analysis(file_diffs: list,*,source_map: dict[str, bytes] | None = None,+ stored_git_meta: dict[str, dict] | None = None,log: LogFn | None = None,) -> tuple[Any, Any]:- """Run partial code-health + dead-code analysis for the changed files.+ """Run partial code-health + repo-wide dead-code analysis.Returns ``(partial_health_report, dead_code_report)`` — either may be``None`` if its analysis failed (both are best-effort).*source_map* is ingestion's ``{path: raw bytes}`` for this rebuild; thedead-code prepasses read it instead of re-reading the repo from disk.++ *stored_git_meta* is the persisted per-file git metadata, supplied to the+ dead-code analyzer *only*. ``git_meta_map`` holds this run's freshly+ indexed rows, which on an incremental update means the changed files and+ nothing else; every other file would otherwise be scored against an empty+ dict and land on the ``commit_count_90d == 0`` rung of the confidence+ ladder at 0.7 / ``safe_to_delete=True``. It is deliberately NOT merged into+ ``git_meta_map`` itself: the partial health analysis reads that map's+ entries as a repo-wide aggregate, so widening it there would silently move+ health scores (the same reason the idle-decay rows are kept out of it).++ ``None`` means the store could not be read, which is different from an+ empty mapping and narrows what the resulting report is allowed to+ overwrite. See ``load_stored_git_meta``."""log = log or _noop_log@@ -365,8 +436,8 @@ def run_partial_analysis(except Exception as exc:log(f"[yellow]Health analysis skipped: {exc}[/yellow]")- # Run partial dead-code analysis up front so both branches can- # persist its results. Previously this sat below the ``if index_only``+ # Run dead-code analysis up front so both branches can persist its+ # results. Previously this sat below the ``if index_only``# short-circuit, which left the closure's reference to# ``dead_code_report`` unbound and crashed every ``--index-only`` run.dead_code_report = None@@ -375,16 +446,54 @@ def run_partial_analysis(# parsed_files enables the source-scan rescues (dynamic markers,# bundler aliases, export aliases) on the update path, matching init.- _analyzer_partial = DeadCodeAnalyzer(+ #+ # This run's freshly indexed rows win over the stored ones for the+ # files they cover; the stored rows carry every other file, which is+ # what init's analyzer had and this path did not.+ _dead_code_git_meta = {**(stored_git_meta or {}), **git_meta_map}+ _dead_code_analyzer = DeadCodeAnalyzer(graph_builder.graph(),- git_meta_map,+ _dead_code_git_meta,parsed_files=graph_builder._parsed_files,source_map=source_map,)- _changed_paths_partial = [fd.path for fd in file_diffs]- dead_code_report = _analyzer_partial.analyze_partial(_changed_paths_partial)+ # Repo-wide, and persisted repo-wide. The detectors were always+ # repo-wide — the update path just discarded everything outside the+ # change set before writing, which is why an unchanged file that the+ # change had made dead (or brought back to life) kept its old verdict+ # until someone re-indexed from scratch.+ dead_code_report = _dead_code_analyzer.analyze()++ # What this report is allowed to overwrite.+ #+ # When the stored read succeeded, this run's git knowledge is the same+ # knowledge a full index had — the stored rows ARE what the last full+ # index wrote, with this run's fresher ones on top — so every file is+ # scored at least as well here as it was there and the report speaks+ # for the whole repository. That includes files with no git row at+ # all: a full index had no row for them either and scored them the+ # same way, so holding them back would protect nothing while leaving+ # exactly the stale verdicts this is meant to fix. Coverage is not the+ # test, and cannot be: ``git_metadata`` legitimately covers only the+ # files ``index_repo`` produced.+ #+ # When the read FAILED, this run knows strictly less than the index it+ # would be overwriting: every file outside the change set would be+ # scored against an empty dict, which reads as "no commits" and stores+ # 0.7 with ``safe_to_delete=True`` however active the file is. So it+ # speaks only for the files it re-indexed this run, which is the+ # behavior this path had before it was widened.+ dead_code_report.authoritative_paths = (+ None if stored_git_meta is not None else frozenset(git_meta_map)+ )+ if dead_code_report.authoritative_paths is not None:+ log(+ "[yellow]Dead-code findings limited to "+ f"{len(dead_code_report.authoritative_paths)} re-indexed files; "+ "the rest keep their previous verdict[/yellow]"+ )if dead_code_report.total_findings:- log(f"Dead code findings (partial): [yellow]{dead_code_report.total_findings}[/yellow]")+ log(f"Dead code findings: [yellow]{dead_code_report.total_findings}[/yellow]")except Exception as exc:log(f"[yellow]Dead code analysis skipped: {exc}[/yellow]")@@ -1091,11 +1200,19 @@ async def persist_incremental_index(if dead_code_report is not None:try:from repowise.core.persistence.crud import (- upsert_dead_code_findings,+ replace_dead_code_findings,)- await upsert_dead_code_findings(- session, repo_id, dead_code_report.findings, file_paths=changed_paths+ # The report is repo-wide, and dead code is a cross-file+ # property, so a change-scoped write would drop every+ # verdict the change flipped outside the change set. The+ # scope is the set of files whose confidence was scored on+ # real git metadata; the rest keep what they had.+ await replace_dead_code_findings(+ session,+ repo_id,+ dead_code_report.findings,+ scope=dead_code_report.authoritative_paths,)except Exception as exc:_skip("Dead-code persist", exc, range_scoped=True)diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.pyindex 3a8430bc4..b7394bd8f 100644--- a/packages/core/src/repowise/core/workspace/update.py+++ b/packages/core/src/repowise/core/workspace/update.py@@ -421,6 +421,14 @@ async def _incremental_repo_update(log=_log.info,)+ # Stored per-file git fields for the dead-code analyzer. ``git_meta_map``+ # covers the changed files only, so every other file would be scored+ # against an empty dict — which reads as "no commits in 90 days" and puts+ # the whole repo on the 0.7 / safe-to-delete rung of the confidence ladder.+ from ..pipeline.incremental import load_stored_git_meta++ stored_git_meta = await load_stored_git_meta(repo_path, log=_log.info)+partial_health_report, dead_code_report = run_partial_analysis(repo_path,graph_builder,@@ -428,6 +436,7 @@ async def _incremental_repo_update(parsed_files,file_diffs,source_map=source_map,+ stored_git_meta=stored_git_meta,log=_log.info,)diff --git a/tests/unit/cli/test_update_reporting.py b/tests/unit/cli/test_update_reporting.pyindex b29c4dd67..d3c10fae4 100644--- a/tests/unit/cli/test_update_reporting.py+++ b/tests/unit/cli/test_update_reporting.py@@ -183,3 +183,37 @@ class TestGenerationReport:assert "overlap exploded" in textassert "RuntimeError" in textassert "checks did not run" in text+++class TestDeadCodeCountsAreScopedToTheUpdate:+ """The dead-code report is repo-wide, but this panel summarises the update+ that just ran. Reporting the repo-wide totals would turn a one-file change+ on a large repository into "Dead code 759 unreachable" where it had said+ 0, which reads as the update having caused it.+ """++ def _report(self):+ from types import SimpleNamespace++ from repowise.core.analysis.dead_code.models import DeadCodeKind++ def _f(path, kind):+ return SimpleNamespace(file_path=path, kind=kind)++ return SimpleNamespace(+ findings=[+ _f("changed.py", DeadCodeKind.UNREACHABLE_FILE),+ _f("changed.py", DeadCodeKind.UNUSED_EXPORT),+ _f("elsewhere.py", DeadCodeKind.UNREACHABLE_FILE),+ _f("elsewhere2.py", DeadCodeKind.UNUSED_EXPORT),+ ]+ )++ def test_only_the_changed_files_are_counted(self):+ assert reporting._dead_code_counts(self._report(), ["changed.py"]) == (1, 1)++ def test_no_scope_still_counts_everything(self):+ assert reporting._dead_code_counts(self._report(), None) == (2, 2)++ def test_a_missing_report_counts_as_nothing(self):+ assert reporting._dead_code_counts(None, ["changed.py"]) == (0, 0)diff --git a/tests/unit/dead_code/test_never_flag_regex.py b/tests/unit/dead_code/test_never_flag_regex.pyindex f302629cb..3bf555eff 100644--- a/tests/unit/dead_code/test_never_flag_regex.py+++ b/tests/unit/dead_code/test_never_flag_regex.py@@ -112,3 +112,70 @@ class TestShouldNeverFlag:def test_init_py_barrel(self):assert self._analyzer()._should_never_flag("pkg/sub/__init__.py", set())+++class TestSuffixIndexEquivalence:+ r"""``_never_flag_regex_match`` buckets the patterns by the literal text+ after their last ``*`` and only tests the buckets a path's tail can reach.+ That is sound only because ``fnmatch.translate`` end-anchors every+ alternative, so these pin both the equivalence and the assumption.+ """++ def test_no_pattern_uses_a_construct_the_split_cannot_see(self):+ """The suffix is taken with ``rsplit("*", 1)``, which yields a literal+ tail only while no pattern uses ``?``, a character class or a brace.+ Adding one would silently make the prefilter drop real matches, so+ fail here rather than there."""+ offenders = [p for p in _NEVER_FLAG_PATTERNS if set("?[]{}") & set(p)]+ assert offenders == [], offenders++ def test_every_alternative_is_end_anchored(self):+ r"""Each branch carries its own ``\Z``, which is what makes "the+ pattern ends in literal S, so it can only match a path ending in S"+ true. One shared trailing anchor would make the buckets wrong rather+ than merely slow."""+ for pat in ("*.sh", "*/apps/**/*.cc", "build.rs"):+ assert fnmatch.translate(os.path.normcase(pat)).endswith(r"\Z")++ @pytest.mark.parametrize(+ "path",+ [+ # Repeated segments: fnmatch emits atomic groups for interior+ # ``*literal`` runs, which commit to the FIRST occurrence and never+ # retry a later one, so a matcher that backtracks would over-match.+ "a/tests/b/tests/c/d.cpp",+ "vendor/x/vendor/y.rs",+ "src/generated/deep/generated/nested/file.ts",+ "apps/x/apps/y.cc",+ "build/a/build/b.rs",+ # Tails that brush the bucket boundaries.+ "a.sh",+ "a.sh::Foo",+ "A.SH",+ "x/y/livereload/livereload.js",+ "livereload/livereload.js",+ "notbuild.rs",+ "build.rs",+ "deeply/nested/build.rs",+ "",+ "a",+ "::",+ ],+ )+ def test_matches_the_single_alternation(self, path):+ from repowise.core.analysis.dead_code.analyzer import _never_flag_regex_match++ expected = bool(_never_flag_regex(_NEVER_FLAG_PATTERNS).match(os.path.normcase(path)))+ assert _never_flag_regex_match(path) == expected, path++ def test_synthesized_probe_per_pattern_agrees(self):+ """One concrete path per glob, plus near-miss variants around it, run+ through the bucketed matcher rather than the raw regex."""+ from repowise.core.analysis.dead_code.analyzer import _never_flag_regex_match++ regex = _never_flag_regex(_NEVER_FLAG_PATTERNS)+ for pat in _NEVER_FLAG_PATTERNS:+ base = pat.replace("**", "x").replace("*", "x")+ for probe in (base, base.upper(), f"prefix/{base}", f"{base}/trailing.py"):+ expected = bool(regex.match(os.path.normcase(probe)))+ assert _never_flag_regex_match(probe) == expected, (pat, probe)diff --git a/tests/unit/dead_code/test_partial.py b/tests/unit/dead_code/test_partial.pyindex 475fcf289..cc667595c 100644--- a/tests/unit/dead_code/test_partial.py+++ b/tests/unit/dead_code/test_partial.py@@ -1,4 +1,12 @@-"""Tests for DeadCodeAnalyzer.analyze_partial (incremental update path)."""+"""Tests for the dead-code analysis the incremental update path runs.++The update path used to call ``analyze_partial``, which ran the full detector+suite and then threw away every finding outside the change set. That method is+gone: the update now keeps the repo-wide report, because dead code is a+cross-file property and the findings the filter discarded were exactly the ones+a change had just moved. See ``test_dead_code_crud.py`` for the persistence+half.+"""from __future__ import annotations@@ -40,23 +48,172 @@ def _graph_with_unused_export():)-def test_analyze_partial_reports_unused_export_for_changed_file():- """analyze_partial must run all detectors (not just unreachable files),- so a changed file's unused export is reported."""+def test_update_path_analysis_reports_unused_exports():+ """All detectors run, not just unreachable files."""analyzer = DeadCodeAnalyzer(_graph_with_unused_export(), git_meta_map={})- partial = analyzer.analyze_partial(["pkg/utils.py"])+ report = analyzer.analyze()- by_symbol = {(f.file_path, f.symbol_name): f.kind for f in partial.findings}+ by_symbol = {(f.file_path, f.symbol_name): f.kind for f in report.findings}assert ("pkg/utils.py", "orphan") in by_symbolassert by_symbol[("pkg/utils.py", "orphan")] == DeadCodeKind.UNUSED_EXPORT-def test_analyze_partial_scopes_findings_to_affected_files():- """Findings for files outside the affected set are not returned."""- analyzer = DeadCodeAnalyzer(_graph_with_unused_export(), git_meta_map={})+def test_analyze_partial_is_gone():+ """The filtering entry point must not come back.++ It is the whole bug: it computed the repo-wide truth and then narrowed the+ result to the changed files before anything could persist it, so a file the+ change had just made dead kept its old verdict until a full re-index.+ """+ assert not hasattr(DeadCodeAnalyzer, "analyze_partial")+++class _Builder:+ def __init__(self, graph):+ self._graph = graph+ self._parsed_files = {}++ def graph(self):+ return self._graph+++def _run_update_analysis(graph, git_meta_map, stored_git_meta):+ from repowise.core.pipeline.incremental import run_partial_analysis++ _health, dead_code = run_partial_analysis(+ "/tmp/repo",+ _Builder(graph),+ git_meta_map,+ [],+ [],+ stored_git_meta=stored_git_meta,+ )+ return dead_code+++_ORPHAN_NODES = {+ "pkg/main.py": {+ "is_entry_point": True,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 4,+ "symbols": [],+ },+ "pkg/orphan.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [],+ },+}+++def _orphan_graph():+ return _build_graph(nodes=_ORPHAN_NODES, edges=[])+++class TestStoredGitMetadataReachesTheAnalyzer:+ """The update path re-indexes git metadata for changed files only, and a+ file with no metadata is indistinguishable from one with no commits: it+ scores 0.7 with ``safe_to_delete=True`` however actively it is committed+ to. So the stored rows have to arrive, and this run's fresh rows have to+ win over them.+ """++ def test_a_stored_row_scores_an_unchanged_file(self):+ stored = {+ "pkg/orphan.py": {+ "commit_count_90d": 12,+ "last_commit_at": None,+ "age_days": 30,+ "primary_owner_name": "a",+ }+ }+ report = _run_update_analysis(+ _orphan_graph(), {"pkg/main.py": {"commit_count_90d": 1}}, stored+ )+ finding = {f.file_path: f for f in report.findings}["pkg/orphan.py"]+ assert not finding.safe_to_delete+ assert finding.confidence < 0.7++ def test_this_runs_fresh_rows_beat_the_stored_ones(self):+ """The stored row is by construction one update-interval stale.+ Flipping the merge order lets it overwrite a freshly indexed value and+ marks an actively-committed file safe to delete."""+ fresh = {"pkg/orphan.py": {"commit_count_90d": 40, "age_days": 2}}+ stale = {"pkg/orphan.py": {"commit_count_90d": 0, "age_days": 900}}+ report = _run_update_analysis(_orphan_graph(), fresh, stale)+ finding = {f.file_path: f for f in report.findings}["pkg/orphan.py"]+ assert not finding.safe_to_delete+ assert finding.confidence < 0.7+++class TestAuthoritativeScope:+ """What the report may overwrite turns on whether the stored read+ SUCCEEDED, not on how many files it covered.++ A successful read gives this run the same git knowledge the last full+ index had, so it may speak for the whole repository. A failed read leaves+ it knowing strictly less, so it speaks only for what it re-indexed.+ """++ def test_a_successful_read_speaks_for_the_whole_repository(self):+ report = _run_update_analysis(+ _orphan_graph(),+ {"pkg/main.py": {}},+ {"pkg/orphan.py": {"commit_count_90d": 1}},+ )+ assert report.authoritative_paths is None++ def test_partial_coverage_still_speaks_for_the_whole_repository(self):+ """A file with no git row is not evidence of a failed read.++ `git_metadata` legitimately covers only what `index_repo` produced, so+ a real repository has indexed files with no row. A full index scored+ those files the same way this run does, so holding them back would+ protect nothing and would leave exactly the stale verdicts this is+ meant to correct.+ """+ report = _run_update_analysis(_orphan_graph(), {"pkg/main.py": {}}, {})+ assert report.authoritative_paths is None++ def test_a_failed_read_narrows_the_scope_to_what_this_run_indexed(self):+ """`None` is the read failing, and is not the same as an empty map."""+ report = _run_update_analysis(_orphan_graph(), {"pkg/main.py": {}}, None)+ assert report.authoritative_paths == frozenset({"pkg/main.py"})++ def test_a_full_report_speaks_for_everything_by_default(self):+ analyzer = DeadCodeAnalyzer(_orphan_graph(), git_meta_map={})+ assert analyzer.analyze().authoritative_paths is None+++def test_findings_outside_the_change_set_are_kept():+ """A file nobody touched still gets a verdict, which is what the update+ now writes."""+ graph = _build_graph(+ nodes={+ "pkg/orphaned.py": {+ "is_entry_point": False,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 1,+ "symbols": [],+ },+ "pkg/main.py": {+ "is_entry_point": True,+ "is_test": False,+ "is_api_contract": False,+ "symbol_count": 4,+ "symbols": [],+ },+ },+ edges=[],+ )+ analyzer = DeadCodeAnalyzer(graph, git_meta_map={})- partial = analyzer.analyze_partial(["pkg/utils.py"])+ paths = {f.file_path for f in analyzer.analyze().findings}- assert partial.findings- assert all(f.file_path == "pkg/utils.py" for f in partial.findings)+ # Nothing imports orphaned.py and it is not an entry point.+ assert "pkg/orphaned.py" in pathsdiff --git a/tests/unit/persistence/test_dead_code_crud.py b/tests/unit/persistence/test_dead_code_crud.pyindex 96bdb8f0b..da3a774e2 100644--- a/tests/unit/persistence/test_dead_code_crud.py+++ b/tests/unit/persistence/test_dead_code_crud.py@@ -1,12 +1,23 @@-"""Unit tests for dead-code findings persistence (file-scoped upsert)."""+"""Unit tests for dead-code findings persistence (repo-wide replace).++The update path used to write findings for the changed files only, which meant+an unchanged file kept the verdict the last full index gave it even when the+change had just made it dead (or brought it back to life). The write is now+repo-wide, so the tests that bite here are the ones pinning (a) that a stale+verdict on an *unchanged* file is corrected, and (b) that a finding the user+dismissed is not resurrected by the wider write. The rest are regression+guards.+"""from __future__ import annotations+from dataclasses import dataclass+from sqlalchemy import selectfrom repowise.core.persistence.crud import (+ replace_dead_code_findings,save_dead_code_findings,- upsert_dead_code_findings,)from repowise.core.persistence.models import DeadCodeFindingfrom tests.unit.persistence.helpers import insert_repo@@ -33,66 +44,312 @@ def _finding(file_path: str, symbol: str, kind: str = "unused_export") -> dict:async def _findings_by_file(session, repo_id: str) -> list[tuple[str, str]]:rows = (- await session.execute(- select(DeadCodeFinding).where(DeadCodeFinding.repository_id == repo_id)+ (+ await session.execute(+ select(DeadCodeFinding).where(DeadCodeFinding.repository_id == repo_id)+ ))- ).scalars().all()+ .scalars()+ .all()+ )return sorted((r.file_path, r.symbol_name) for r in rows)-async def test_upsert_dead_code_findings_scopes_by_file(async_session):- """Re-indexing one file replaces only that file's findings; others survive."""+async def _rows(session, repo_id: str) -> list[DeadCodeFinding]:+ return list(+ (+ await session.execute(+ select(DeadCodeFinding).where(DeadCodeFinding.repository_id == repo_id)+ )+ )+ .scalars()+ .all()+ )+++# --------------------------------------------------------------------------+# The two that bite+# --------------------------------------------------------------------------+++async def test_stale_verdict_on_an_unchanged_file_is_corrected(async_session):+ """The whole point of the change: a file nobody touched loses a verdict+ that is no longer true, and gains one that has become true.++ ``b.py`` is not in any change set here — under the old file-scoped write+ its stale finding survived every update until a full re-index.+ """repo = await insert_repo(async_session)await save_dead_code_findings(- async_session, repo.id, [_finding("a.py", "fa"), _finding("b.py", "fb")]+ async_session, repo.id, [_finding("a.py", "fa"), _finding("b.py", "stale")])await async_session.commit()- await upsert_dead_code_findings(- async_session, repo.id, [_finding("a.py", "fa2")], file_paths=["a.py"]+ # A later analysis says b.py is clean and c.py has gone dead.+ await replace_dead_code_findings(+ async_session, repo.id, [_finding("a.py", "fa"), _finding("c.py", "newly_dead")])await async_session.commit()assert await _findings_by_file(async_session, repo.id) == [- ("a.py", "fa2"),- ("b.py", "fb"),+ ("a.py", "fa"),+ ("c.py", "newly_dead"),]-async def test_upsert_dead_code_findings_clears_changed_file_with_no_findings(async_session):- """A changed file that is now clean must have its old findings removed."""+async def test_dismissed_finding_is_not_resurrected(async_session):+ """A finding the user acted on stays acted on.++ The delete is scoped to ``status == "open"``, so the dismissed row+ survives it; without the second half of the guard the incoming finding+ would be re-inserted next to it as a fresh ``open`` duplicate, and the+ dismissal would be undone on every single update.+ """repo = await insert_repo(async_session)- await save_dead_code_findings(async_session, repo.id, [_finding("a.py", "fa")])+ await save_dead_code_findings(+ async_session, repo.id, [_finding("a.py", "fa"), _finding("b.py", "fb")]+ )await async_session.commit()- await upsert_dead_code_findings(async_session, repo.id, [], file_paths=["a.py"])+ dismissed = next(r for r in await _rows(async_session, repo.id) if r.file_path == "b.py")+ dismissed.status = "ignored"await async_session.commit()- assert await _findings_by_file(async_session, repo.id) == []+ # The analyzer still reports it — it is still statically unreachable.+ await replace_dead_code_findings(+ async_session, repo.id, [_finding("a.py", "fa"), _finding("b.py", "fb")]+ )+ await async_session.commit()++ rows = await _rows(async_session, repo.id)+ assert sorted((r.file_path, r.status) for r in rows) == [+ ("a.py", "open"),+ ("b.py", "ignored"),+ ]++async def test_scope_holds_back_files_the_caller_cannot_speak_for(async_session):+ """A caller with partial git metadata must not overwrite the rest of the+ repo with guesses.-async def test_upsert_dead_code_findings_ignores_out_of_scope_findings(async_session):- """Findings whose file_path is outside file_paths are not inserted."""+ A file the analyzer has no git metadata for scores 0.7 /+ ``safe_to_delete=True`` however actively it is committed to, so writing+ that verdict is worse than writing nothing. Rows outside the scope are+ neither deleted nor inserted, and the file keeps what it had.+ """repo = await insert_repo(async_session)+ await save_dead_code_findings(+ async_session, repo.id, [_finding("in.py", "keep"), _finding("out.py", "untouched")]+ )+ await async_session.commit()- await upsert_dead_code_findings(+ await replace_dead_code_findings(async_session,repo.id,- [_finding("a.py", "fa"), _finding("b.py", "fb")],- file_paths=["a.py"],+ # The analyzer reports on both files, but only in.py was scorable.+ [_finding("in.py", "fresh"), _finding("out.py", "guess")],+ scope=frozenset({"in.py"}),+ )+ await async_session.commit()++ assert await _findings_by_file(async_session, repo.id) == [+ ("in.py", "fresh"),+ ("out.py", "untouched"),+ ]+++async def test_an_empty_scope_writes_nothing_at_all(async_session):+ """The floor: a run that could score no file leaves the index exactly as+ it found it rather than clearing it."""+ repo = await insert_repo(async_session)+ await save_dead_code_findings(async_session, repo.id, [_finding("a.py", "fa")])+ await async_session.commit()++ await replace_dead_code_findings(+ async_session, repo.id, [_finding("a.py", "different")], scope=frozenset())await async_session.commit()assert await _findings_by_file(async_session, repo.id) == [("a.py", "fa")]-async def test_upsert_dead_code_findings_noop_without_file_paths(async_session):- """Empty file_paths is a no-op (nothing deleted, nothing inserted)."""+async def test_scope_none_still_means_the_whole_repository(async_session):+ repo = await insert_repo(async_session)+ await save_dead_code_findings(+ async_session, repo.id, [_finding("a.py", "fa"), _finding("b.py", "stale")]+ )+ await async_session.commit()++ await replace_dead_code_findings(async_session, repo.id, [_finding("a.py", "fa")], scope=None)+ await async_session.commit()++ assert await _findings_by_file(async_session, repo.id) == [("a.py", "fa")]+++async def test_a_dismissal_outside_the_scope_is_left_alone(async_session):+ repo = await insert_repo(async_session)+ await save_dead_code_findings(async_session, repo.id, [_finding("out.py", "fo")])+ await async_session.commit()+ row = (await _rows(async_session, repo.id))[0]+ row.status = "ignored"+ await async_session.commit()++ await replace_dead_code_findings(+ async_session, repo.id, [_finding("out.py", "fo")], scope=frozenset({"in.py"})+ )+ await async_session.commit()++ assert [(r.file_path, r.status) for r in await _rows(async_session, repo.id)] == [+ ("out.py", "ignored")+ ]+++# --------------------------------------------------------------------------+# Regression guards+# --------------------------------------------------------------------------+++async def test_replace_clears_a_file_that_is_now_clean(async_session):repo = await insert_repo(async_session)await save_dead_code_findings(async_session, repo.id, [_finding("a.py", "fa")])await async_session.commit()- await upsert_dead_code_findings(async_session, repo.id, [_finding("a.py", "x")], file_paths=[])+ await replace_dead_code_findings(async_session, repo.id, [])+ await async_session.commit()++ assert await _findings_by_file(async_session, repo.id) == []+++async def test_replace_does_not_touch_another_repository(async_session):+ repo = await insert_repo(async_session)+ other = await insert_repo(async_session, name="other", local_path="/tmp/other")+ await save_dead_code_findings(async_session, other.id, [_finding("x.py", "fx")])+ await async_session.commit()++ await replace_dead_code_findings(async_session, repo.id, [_finding("a.py", "fa")])await async_session.commit()assert await _findings_by_file(async_session, repo.id) == [("a.py", "fa")]+ assert await _findings_by_file(async_session, other.id) == [("x.py", "fx")]+++async def test_dismissal_is_keyed_on_file_kind_and_symbol(async_session):+ """A dismissal covers one finding, not the whole file: a *different*+ symbol in the same file, and the same symbol under a different kind, are+ both still written."""+ repo = await insert_repo(async_session)+ await save_dead_code_findings(async_session, repo.id, [_finding("a.py", "one")])+ await async_session.commit()++ row = (await _rows(async_session, repo.id))[0]+ row.status = "ignored"+ await async_session.commit()++ await replace_dead_code_findings(+ async_session,+ repo.id,+ [+ _finding("a.py", "one"),+ _finding("a.py", "two"),+ _finding("a.py", "one", kind="unused_internal"),+ ],+ )+ await async_session.commit()++ rows = await _rows(async_session, repo.id)+ assert sorted((r.file_path, r.symbol_name, r.kind, r.status) for r in rows) == [+ ("a.py", "one", "unused_export", "ignored"),+ ("a.py", "one", "unused_internal", "open"),+ ("a.py", "two", "unused_export", "open"),+ ]+++async def test_replace_accepts_dataclass_findings(async_session):+ """The workspace path hands over ``DeadCodeFindingData`` objects while the+ CLI path hands over ``dataclasses.asdict`` output, so both shapes have to+ key identically — including the ``DeadCodeKind`` member, which ``asdict``+ leaves as an enum rather than converting to its value."""+ from repowise.core.analysis.dead_code.models import DeadCodeKind++ @dataclass+ class _Data:+ kind: DeadCodeKind+ file_path: str+ symbol_name: str | None+ symbol_kind: str | None = "function"+ confidence: float = 1.0+ reason: str = "test"+ last_commit_at: object = None+ commit_count_90d: int = 0+ lines: int = 1+ start_line: int | None = None+ end_line: int | None = None+ package: str | None = None+ evidence: list = None # type: ignore[assignment]+ safe_to_delete: bool = True+ primary_owner: str | None = None+ age_days: int | None = None++ repo = await insert_repo(async_session)+ await replace_dead_code_findings(+ async_session,+ repo.id,+ [_Data(kind=DeadCodeKind.UNUSED_EXPORT, file_path="a.py", symbol_name="fa", evidence=[])],+ )+ await async_session.commit()++ rows = await _rows(async_session, repo.id)+ assert [(r.file_path, r.symbol_name, r.kind) for r in rows] == [+ ("a.py", "fa", "unused_export")+ ]++ # ...and that row is now dismissible, i.e. the kind it stored is the value+ # the identity check compares against.+ rows[0].status = "ignored"+ await async_session.commit()+ await replace_dead_code_findings(+ async_session,+ repo.id,+ [_Data(kind=DeadCodeKind.UNUSED_EXPORT, file_path="a.py", symbol_name="fa", evidence=[])],+ )+ await async_session.commit()+ assert [r.status for r in await _rows(async_session, repo.id)] == ["ignored"]+++async def test_get_dead_code_git_fields_returns_the_scoring_columns(async_session):+ """The four columns dead-code confidence is scored from, per file.++ If this ever comes back empty the analyzer scores every file as "no+ commits" and marks it safe to delete, so the read itself needs a test and+ not only its callers.+ """+ from repowise.core.persistence.crud import get_dead_code_git_fields+ from repowise.core.persistence.models import GitMetadata++ repo = await insert_repo(async_session)+ other = await insert_repo(async_session, name="other", local_path="/tmp/other")+ async_session.add(+ GitMetadata(+ repository_id=repo.id,+ file_path="a.py",+ commit_count_90d=7,+ age_days=400,+ primary_owner_name="ada",+ )+ )+ async_session.add(GitMetadata(repository_id=other.id, file_path="elsewhere.py"))+ await async_session.commit()++ fields = await get_dead_code_git_fields(async_session, repo.id)++ assert set(fields) == {"a.py"}, "must not leak another repository's rows"+ assert fields["a.py"]["commit_count_90d"] == 7+ assert fields["a.py"]["age_days"] == 400+ assert fields["a.py"]["primary_owner_name"] == "ada"+ assert "last_commit_at" in fields["a.py"]+++async def test_get_dead_code_git_fields_is_empty_for_an_unknown_repo(async_session):+ from repowise.core.persistence.crud import get_dead_code_git_fields++ assert await get_dead_code_git_fields(async_session, "nope") == {}diff --git a/tests/unit/pipeline/test_load_stored_git_meta.py b/tests/unit/pipeline/test_load_stored_git_meta.pynew file mode 100644index 000000000..2bf719d45--- /dev/null+++ b/tests/unit/pipeline/test_load_stored_git_meta.py@@ -0,0 +1,39 @@+"""``load_stored_git_meta`` reads the store without creating one, and says so+when it could not read it at all.++``None`` (could not read) and ``{}`` (read fine, no rows) drive different+behavior in the caller, so conflating them is the failure mode this file+exists to prevent.+"""++from __future__ import annotations++from repowise.core.pipeline.incremental import load_stored_git_meta+++async def test_a_repo_without_a_store_yields_nothing_and_creates_nothing(tmp_path):+ """Reading must never conjure an empty database.++ A repo whose ``wiki.db`` was deleted to force a rebuild would otherwise be+ handed an empty one here, and an empty database reads as "indexed"+ downstream. The same guard, for the same reason, sits on the head-commit+ stamper and the workspace updater.+ """+ assert await load_stored_git_meta(tmp_path) is None+ assert not (tmp_path / ".repowise" / "wiki.db").exists()+ assert not (tmp_path / ".repowise").exists()+++async def test_an_unreadable_store_is_unknown_not_empty(tmp_path):+ """Best-effort, but the failure has to stay distinguishable.++ ``None`` means "could not read", and the caller then narrows what the+ update may overwrite. Returning ``{}`` would instead assert "this+ repository has no git history", which is the one answer that makes the+ caller rewrite the whole index with verdicts scored against nothing.+ """+ store = tmp_path / ".repowise"+ store.mkdir()+ (store / "wiki.db").write_bytes(b"this is not a sqlite database")++ assert await load_stored_git_meta(tmp_path) is None