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(update): five places the incremental path knew less than a full index (#2129)

Raghav Chamadiya0a4399b3cb99
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 8a947913d..e661a40b1 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -48,6 +48,7 @@ from .file_reachability import (
from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport
from .name_occurrences import IDENTIFIER_RE, clamp_unverified_absence
from .risk_factors import (
+ NO_GIT_SIGNAL_CONFIDENCE,
RISK_CAP_CONFIDENCE,
SAFE_CONFIDENCE_THRESHOLD,
path_risk_factors,
@@ -964,14 +965,21 @@ class DeadCodeAnalyzer:
dynamic_patterns: tuple[str, ...],
) -> DeadCodeFindingData | None:
"""Create an unreachable file finding with confidence scoring."""
- git_meta = self.git_meta_map.get(node, {})
+ git_meta = self.git_meta_map.get(node)
+ # No row at all is not "no commits in 90 days": that rung is for a
+ # file git has data on. Scored below the deletion-ready threshold and
+ # said so in the evidence, on every path that builds this map.
+ no_git_signal = not git_meta
+ git_meta = git_meta or {}
commit_90d = git_meta.get("commit_count_90d", 0)
last_commit = git_meta.get("last_commit_at")
age_days = git_meta.get("age_days")
primary_owner = git_meta.get("primary_owner_name")
# _is_old uses strict >, so pass days-1 to get >= semantics.
- if commit_90d == 0 and last_commit and self._is_old(last_commit, days=364):
+ if no_git_signal:
+ confidence = NO_GIT_SIGNAL_CONFIDENCE
+ elif commit_90d == 0 and last_commit and self._is_old(last_commit, days=364):
confidence = 1.0 # Untouched for a year+ — very likely dead
elif commit_90d == 0 and last_commit and self._is_old(last_commit, days=179):
confidence = 0.9
@@ -1008,7 +1016,9 @@ class DeadCodeAnalyzer:
safe = False
evidence = ["in_degree=0 (no files import this)"]
- if commit_90d == 0:
+ if no_git_signal:
+ evidence.append("No git history recorded for this file")
+ elif commit_90d == 0:
evidence.append("No commits in last 90 days")
if self._dynamic_import_files and confidence <= RISK_CAP_CONFIDENCE:
evidence.append("Package uses dynamic imports or runtime-resolved edges")
diff --git a/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py b/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
index 54890613e..cb669c6d7 100644
--- a/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/risk_factors.py
@@ -39,6 +39,12 @@ from pathlib import PurePosixPath
# so the analyzer and every read-time consumer agree.
SAFE_CONFIDENCE_THRESHOLD: float = 0.7
+# Confidence for an unreachable file that has no git row at all. Absence is
+# the weakest evidence the ladder sees, not the strongest: the file may be
+# untracked, newly added, or outside the walk that produced the rows. Held
+# below the deletion-ready threshold so no verdict is issued on it.
+NO_GIT_SIGNAL_CONFIDENCE: float = 0.5
+
# Confidence ceiling applied to a finding that carries a runtime-load risk
# factor. 0.4 is the default ``min_confidence`` floor across CLI, REST router,
# and MCP tools (which import this value as their single source of truth), so the
diff --git a/packages/core/src/repowise/core/analysis/health/trends.py b/packages/core/src/repowise/core/analysis/health/trends.py
index 145bc64c2..912453599 100644
--- a/packages/core/src/repowise/core/analysis/health/trends.py
+++ b/packages/core/src/repowise/core/analysis/health/trends.py
@@ -110,6 +110,24 @@ def diff_snapshots(history: list[Any]) -> TrendSummary:
return summary
+def hotspot_trend(history: list[Any]) -> str | None:
+ """``"improving"``, ``"stable"`` or ``"declining"`` for the hotspot KPI.
+
+ Compared over the same window the declining alert uses, so the two never
+ disagree. ``None`` with fewer than two snapshots: one reading is not a
+ trend, and a surface should say nothing rather than print "stable".
+ """
+ if len(history) < 2:
+ return None
+ baseline = history[max(0, len(history) - 1 - DECLINE_LOOKBACK)]
+ delta = float(history[-1].hotspot_health) - float(baseline.hotspot_health)
+ if delta <= -DECLINE_THRESHOLD:
+ return "declining"
+ if delta >= DECLINE_THRESHOLD:
+ return "improving"
+ return "stable"
+
+
def _declining_alerts(history: list[Any]) -> list[TrendAlert]:
"""``Declining Health`` — current is ≥ threshold below snapshot N-5."""
if len(history) <= DECLINE_LOOKBACK:
diff --git a/packages/core/src/repowise/core/generation/editor_files/data.py b/packages/core/src/repowise/core/generation/editor_files/data.py
index 1a21bc1c4..02176b4bb 100644
--- a/packages/core/src/repowise/core/generation/editor_files/data.py
+++ b/packages/core/src/repowise/core/generation/editor_files/data.py
@@ -66,7 +66,8 @@ class CodeHealthBlock:
average_health: float
worst_score: float
worst_path: str
- hotspot_trend: str = "stable"
+ # ``None`` until two snapshots exist; the section then omits the label.
+ hotspot_trend: str | None = None
# Maintainability pillar headline (NLOC-weighted average over the per-file
# maintainability scores). ``None`` until the split populates the column, so
# the section omits it rather than printing a misleading 10.0.
diff --git a/packages/core/src/repowise/core/generation/editor_files/fetcher.py b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
index cf806158b..32fca0a80 100644
--- a/packages/core/src/repowise/core/generation/editor_files/fetcher.py
+++ b/packages/core/src/repowise/core/generation/editor_files/fetcher.py
@@ -17,6 +17,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.health.perf.coverage import coverage_for_metrics
from repowise.core.analysis.health.scoring import hotspot_health, nloc_weighted_score
+from repowise.core.analysis.health.trends import DECLINE_LOOKBACK, hotspot_trend
from repowise.core.entry_candidacy import conventional_entry_stems
from repowise.core.generation.entry_points import rank_entry_points
from repowise.core.persistence import crud
@@ -212,6 +213,12 @@ class EditorFileDataFetcher:
The fix columns come from the same row the churn columns already did, so
this is the same single query it was.
+
+ Filtered to files that exist in the checkout. A ``git_metadata`` row
+ outlives its file when the deleted-file prune refuses a run that looks
+ like a broken checkout, and a fix-heavy file that was deleted would
+ otherwise rank first in "files that need care" forever. The limit is
+ applied after the filter, so a dropped row cannot leave the list short.
"""
result = await self._session.execute(
select(
@@ -234,11 +241,14 @@ class EditorFileDataFetcher:
GitMetadata.churn_percentile.desc(),
GitMetadata.file_path.asc(), # deterministic tie-break
)
- .limit(_MAX_HOTSPOTS)
)
now = datetime.now(UTC)
hotspots: list[HotspotFile] = []
for row in result.all():
+ if len(hotspots) >= _MAX_HOTSPOTS:
+ break
+ if not (self._repo_path / row[0]).exists():
+ continue
last_fix_at = row[6]
age: str | None = None
if isinstance(last_fix_at, datetime):
@@ -431,12 +441,18 @@ class EditorFileDataFetcher:
}
)
+ # The trend the snapshots record, or nothing: a repository indexed once
+ # has no trend, and the section used to print "stable" for it anyway.
+ history = await crud.list_health_snapshots(
+ self._session, self._repo_id, limit=DECLINE_LOOKBACK + 1
+ )
+
return CodeHealthBlock(
hotspot_health=round(hotspot_for_claude_md, 2),
average_health=round(avg, 2),
worst_score=round(worst.score, 2),
worst_path=worst.file_path,
- hotspot_trend="stable",
+ hotspot_trend=hotspot_trend(history),
maintainability_average=(
round(maintainability_average, 2) if maintainability_average is not None else None
),
diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2
index ddcd95286..65133d9bb 100644
--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2
@@ -43,7 +43,7 @@ Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}
{% if data.code_health %}
### Code health
-Three co-equal signals: defect risk {{ data.code_health.average_health }}/10 avg, hotspot health {{ data.code_health.hotspot_health }}/10 ({{ data.code_health.hotspot_trend }}), worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static I/O-in-loop / N+1 finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
+Three co-equal signals: defect risk {{ data.code_health.average_health }}/10 avg, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static I/O-in-loop / N+1 finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
{% if data.code_health.critical_biomarkers %}
Critical files:
diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2
index 55b7e4120..9677a62b7 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -43,7 +43,7 @@ Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}
{% if data.code_health %}
### Code health
-Three co-equal signals: defect risk {{ data.code_health.average_health }}/10 avg, hotspot health {{ data.code_health.hotspot_health }}/10 ({{ data.code_health.hotspot_trend }}), worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static I/O-in-loop / N+1 finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
+Three co-equal signals: defect risk {{ data.code_health.average_health }}/10 avg, hotspot health {{ data.code_health.hotspot_health }}/10{% if data.code_health.hotspot_trend %} ({{ data.code_health.hotspot_trend }}){% endif %}, worst `{{ data.code_health.worst_path }}` at {{ data.code_health.worst_score }}/10{% if data.code_health.maintainability_average is not none %} · maintainability {{ data.code_health.maintainability_average }}/10{% endif %}{% if data.code_health.performance_average is not none %} · performance risk {{ data.code_health.performance_findings }} open static I/O-in-loop / N+1 finding{{ 's' if data.code_health.performance_findings != 1 else '' }}{% endif %}. Detail: `get_health()`.
{% if data.code_health.critical_biomarkers %}
Critical files:
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 a2f1e643a..b6ed1ae22 100644
--- a/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
+++ b/packages/core/src/repowise/core/ingestion/git_indexer/indexer.py
@@ -414,6 +414,14 @@ class GitIndexer:
persist path upserts them field-by-field so ownership / age / authorship
(correct only from the full init walk) are left intact.
"""
+ # The same allowlist the full index applies to the tracked-file set.
+ # Without it an update wrote rows for a changed workflow file, and the
+ # idle refresh minted rows for every tracked config and markup file,
+ # which the health pass then scored: a store grew rows a fresh index
+ # never has.
+ changed_file_paths = [fp for fp in changed_file_paths if not _should_skip_index(fp)]
+ if all_files:
+ all_files = {fp for fp in all_files if not _should_skip_index(fp)}
repo = self._get_repo()
if repo is None:
return []
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index c752ec201..9d07cdd15 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -800,10 +800,11 @@ def run_partial_analysis(
#
# 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.
+ # scored with no git row, which the analyzer holds below the
+ # deletion-ready threshold, so a verdict a full index scored at 1.0
+ # would be written back as an unscored 0.5. 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)
)
@@ -1046,6 +1047,11 @@ async def persist_partial_health(session: Any, repo_id: str, report: Any) -> Non
from repowise.core.persistence.crud import upsert_git_function_blame_bulk
await upsert_git_function_blame_bulk(session, repo_id, fn_blame_rows)
+ # The store now holds the merged repository, so the snapshot describes the
+ # whole of it, not this run's changed files.
+ from repowise.core.pipeline.persist import snapshot_health_from_store
+
+ await snapshot_health_from_store(session, repo_id)
async def persist_incremental_commits(session: Any, repo_id: str, repo_path: Any) -> None:
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 597b9485c..c021a78fc 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -1546,6 +1546,67 @@ async def _analyzed_commit(session: Any, repo_id: str) -> str | None:
return None
+async def snapshot_health_from_store(session: Any, repo_id: str) -> None:
+ """Append a ``HealthSnapshot`` built from the repository's stored rows.
+
+ One writer for the full index and the incremental update. The full path
+ used to snapshot from the in-memory report and the update path never
+ snapshotted at all, so ``health --trend`` and the CLAUDE.md trend only
+ moved on a full re-index however many updates ran in between. A partial
+ report cannot be snapshotted directly, because it holds the changed files
+ and the snapshot has to describe the whole repository; the store after the
+ write holds exactly that, on both paths.
+
+ Best-effort: a snapshot that fails to write is logged and never fails the
+ run that produced the rows it describes.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.analysis.health.scoring import compute_kpis
+ from repowise.core.analysis.health.trends import snapshot_file_maps
+ from repowise.core.persistence.crud import get_hotspot_file_paths, save_health_snapshot
+ from repowise.core.persistence.models import HealthFileMetric, HealthFinding
+
+ try:
+ metrics = list(
+ (
+ await session.execute(
+ select(HealthFileMetric).where(HealthFileMetric.repository_id == repo_id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ if not metrics:
+ return
+ findings = list(
+ (
+ await session.execute(
+ select(HealthFinding).where(
+ HealthFinding.repository_id == repo_id,
+ HealthFinding.status == "open",
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ kpis = compute_kpis(metrics, await get_hotspot_file_paths(session, repo_id))
+ scores_map, deductions_map = snapshot_file_maps(metrics, findings)
+ await save_health_snapshot(
+ session,
+ repo_id,
+ hotspot_health=float(kpis.get("hotspot_health", 10.0)),
+ average_health=float(kpis.get("average_health", 10.0)),
+ worst_performer_path=kpis.get("worst_performer_path"),
+ worst_performer_score=kpis.get("worst_performer_score"),
+ per_file_scores=scores_map,
+ per_file_deductions=deductions_map,
+ )
+ except Exception as exc:
+ logger.warning("health_snapshot_skipped", error=str(exc))
+
+
async def save_full_health_report(
session: Any,
repo_id: str,
@@ -1632,13 +1693,11 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
decisions/governance are idempotent. Intended to run once the analysis
phase has fully completed.
"""
- from repowise.core.analysis.health.trends import snapshot_file_maps
from repowise.core.persistence.crud import (
bulk_upsert_decisions,
recompute_decision_staleness,
save_coverage_files,
save_dead_code_findings,
- save_health_snapshot,
upsert_git_function_blame_bulk,
)
@@ -1669,24 +1728,9 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
fn_blame_rows = getattr(hr, "function_blame_rows", None)
if fn_blame_rows:
await upsert_git_function_blame_bulk(session, repo_id, fn_blame_rows)
- # Snapshot the run for trend tracking (rolling delete inside).
- kpis = hr.kpis or {}
- try:
- scores_map, deductions_map = snapshot_file_maps(
- hr.metrics or [], hr.findings or []
- )
- await save_health_snapshot(
- session,
- repo_id,
- hotspot_health=float(kpis.get("hotspot_health", 10.0)),
- average_health=float(kpis.get("average_health", 10.0)),
- worst_performer_path=kpis.get("worst_performer_path"),
- worst_performer_score=kpis.get("worst_performer_score"),
- per_file_scores=scores_map,
- per_file_deductions=deductions_map,
- )
- except Exception as _snap_err:
- logger.warning("health_snapshot_skipped", error=str(_snap_err))
+ # Snapshot the run for trend tracking (rolling delete inside). From
+ # the rows just written, by the same writer the update path uses.
+ await snapshot_health_from_store(session, repo_id)
# ---- Decision records ----------------------------------------------------
# One contributor: the multi-source extractor. A second read used to fold
diff --git a/tests/unit/cli/test_update_degraded_persist_marker.py b/tests/unit/cli/test_update_degraded_persist_marker.py
new file mode 100644
index 000000000..ea0580a4a
--- /dev/null
+++ b/tests/unit/cli/test_update_degraded_persist_marker.py
@@ -0,0 +1,59 @@
+"""A degraded range-scoped persist leaves a repair marker, end to end.
+
+The sync pointer advances after a degraded run so every other reader stays
+current, and the marker is what keeps the range from being stranded: the next
+update widens its base back to the commit this run started from. The unit
+tests pin the marker arithmetic; this one drives the real command through a
+forced failure and reads ``state.json`` back.
+"""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+
+
+def _git(repo: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=str(repo), capture_output=True, text=True, check=True
+ ).stdout.strip()
+
+
+def test_degraded_git_persist_records_the_range_it_missed(tmp_path: Path, monkeypatch) -> None:
+ from click.testing import CliRunner
+
+ from repowise.cli.helpers import save_state
+ from repowise.cli.main import cli
+ from repowise.core.persistence import crud
+
+ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(repo, "init", "-q")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "T")
+ (repo / "a.py").write_text("def a():\n return 1\n", encoding="utf-8")
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-q", "-m", "c0")
+ c0 = _git(repo, "rev-parse", "HEAD")
+ (repo / ".repowise").mkdir()
+ save_state(repo, {"last_sync_commit": c0, "last_docs_commit": c0, "docs_mode": "none"})
+
+ (repo / "a.py").write_text("def a():\n return 2\n", encoding="utf-8")
+ _git(repo, "commit", "-q", "-am", "c1")
+ c1 = _git(repo, "rev-parse", "HEAD")
+
+ def _boom(*_args, **_kwargs):
+ raise RuntimeError("disk full")
+
+ monkeypatch.setattr(crud, "upsert_git_metadata_bulk", _boom)
+
+ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])
+ assert result.exit_code == 0, result.output
+ assert "next update will re-cover it" in result.output
+
+ state = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))
+ assert state["last_sync_commit"] == c1
+ assert state["pending_repair"]["from_commit"] == c0
+ assert "Git persist" in state["pending_repair"]["steps"]
diff --git a/tests/unit/cli/test_update_forgets_deleted_files.py b/tests/unit/cli/test_update_forgets_deleted_files.py
new file mode 100644
index 000000000..8c189f7f2
--- /dev/null
+++ b/tests/unit/cli/test_update_forgets_deleted_files.py
@@ -0,0 +1,120 @@
+"""Delete a file, run ``repowise update``, and every table forgets it.
+
+The deleted-file prune (#1377) and the tombstone step each cover a set of
+tables, and a table missed by both keeps serving a file that is gone: that is
+how a deleted file's ``git_metadata`` row came to rank first in "files that
+need care" (#1929). This drives the real command and checks every file-keyed
+table, so a table added later without a prune shows up here first.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import subprocess
+from pathlib import Path
+
+from sqlalchemy import or_, select
+
+from repowise.core.persistence.models import (
+ DeadCodeFinding,
+ GitMetadata,
+ GraphEdge,
+ GraphMetric,
+ GraphNode,
+ HealthFileMetric,
+ HealthFinding,
+ Page,
+ WikiSymbol,
+)
+
+GONE = "pkg/gone.py"
+
+# Every table that keys rows by file, and how a row names its file.
+_KEYED = [
+ (GraphNode, lambda m: or_(m.node_id == GONE, m.node_id.like(f"{GONE}::%"))),
+ (GraphEdge, lambda m: or_(m.source_node_id.like(f"{GONE}%"), m.target_node_id.like(f"{GONE}%"))),
+ (GraphMetric, lambda m: m.node_id == GONE),
+ (WikiSymbol, lambda m: m.file_path == GONE),
+ (GitMetadata, lambda m: m.file_path == GONE),
+ (HealthFileMetric, lambda m: m.file_path == GONE),
+ (HealthFinding, lambda m: m.file_path == GONE),
+ (DeadCodeFinding, lambda m: m.file_path == GONE),
+]
+
+
+def _git(repo: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", *args], cwd=str(repo), capture_output=True, text=True, check=True
+ ).stdout.strip()
+
+
+def _repo(tmp_path: Path) -> tuple[Path, str]:
+ repo = tmp_path / "repo"
+ (repo / "pkg").mkdir(parents=True)
+ _git(repo, "init", "-q")
+ _git(repo, "config", "user.email", "[email protected]")
+ _git(repo, "config", "user.name", "T")
+ (repo / "pkg" / "__init__.py").write_text("", encoding="utf-8")
+ (repo / "pkg" / "keep.py").write_text(
+ "from pkg.gone import helper\n\n\ndef keep():\n return helper()\n", encoding="utf-8"
+ )
+ (repo / "pkg" / "gone.py").write_text(
+ "def helper():\n return 1\n\n\ndef unused():\n return 2\n", encoding="utf-8"
+ )
+ (repo / "pkg" / "other.py").write_text("def other():\n return 3\n", encoding="utf-8")
+ _git(repo, "add", ".")
+ _git(repo, "commit", "-q", "-m", "c0")
+ return repo, _git(repo, "rev-parse", "HEAD")
+
+
+async def _rows(repo: Path) -> dict[str, int]:
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+
+ engine = create_engine(get_db_url_for_repo(repo))
+ try:
+ async with get_session(create_session_factory(engine)) as session:
+ out: dict[str, int] = {}
+ for model, where in _KEYED:
+ rows = await session.execute(select(model).where(where(model)))
+ out[model.__tablename__] = len(rows.scalars().all())
+ page = await session.execute(select(Page).where(Page.id == f"file_page:{GONE}"))
+ row = page.scalar_one_or_none()
+ out["page"] = row.freshness_status if row is not None else None
+ return out
+ finally:
+ await engine.dispose()
+
+
+def test_every_table_forgets_a_deleted_file(tmp_path: Path, monkeypatch) -> None:
+ from click.testing import CliRunner
+
+ from repowise.cli.helpers import save_state
+ from repowise.cli.main import cli
+ from repowise.core.pipeline.full_index import index_repo_full
+
+ monkeypatch.setenv("REPOWISE_SKIP_EDITOR_SETUP", "1")
+ repo, c0 = _repo(tmp_path)
+ asyncio.run(index_repo_full(repo))
+ save_state(repo, {"last_sync_commit": c0, "last_docs_commit": c0, "docs_mode": "none"})
+
+ before = asyncio.run(_rows(repo))
+ # The index knew the file: a table with nothing to forget proves nothing.
+ assert before["graph_nodes"] > 0
+ assert before["wiki_symbols"] > 0
+ assert before["git_metadata"] > 0
+
+ _git(repo, "rm", "-q", GONE)
+ (repo / "pkg" / "keep.py").write_text("def keep():\n return 1\n", encoding="utf-8")
+ _git(repo, "commit", "-q", "-am", "c1: drop gone.py")
+
+ result = CliRunner().invoke(cli, ["update", str(repo), "--no-workspace"])
+ assert result.exit_code == 0, result.output
+
+ after = asyncio.run(_rows(repo))
+ leftovers = {t: n for t, n in after.items() if t != "page" and n}
+ assert leftovers == {}, f"rows still name {GONE}: {leftovers}"
+ assert after["page"] in (None, "tombstone")
+ state = json.loads((repo / ".repowise" / "state.json").read_text(encoding="utf-8"))
+ assert state["last_sync_commit"] == _git(repo, "rev-parse", "HEAD")
diff --git a/tests/unit/dead_code/test_no_git_signal.py b/tests/unit/dead_code/test_no_git_signal.py
new file mode 100644
index 000000000..1e34d8422
--- /dev/null
+++ b/tests/unit/dead_code/test_no_git_signal.py
@@ -0,0 +1,69 @@
+"""A file with no git row is scored as unknown, not as untouched.
+
+The confidence ladder's ``commit_count_90d == 0`` rung is for a file git has
+data on. A file absent from the map used to fall through to that rung at 0.7,
+which is the deletion-ready threshold, so the weakest evidence the analyzer
+sees produced a verdict as strong as three quiet months.
+"""
+
+from __future__ import annotations
+
+from datetime import timedelta
+
+import pytest
+
+from repowise.core.analysis.dead_code import DeadCodeAnalyzer
+from repowise.core.analysis.dead_code.risk_factors import (
+ NO_GIT_SIGNAL_CONFIDENCE,
+ SAFE_CONFIDENCE_THRESHOLD,
+)
+from tests.unit.dead_code._helpers import _build_graph, _now
+
+_NODE = {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+}
+_CONFIG = {
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+}
+
+
+def _finding(git_meta_map: dict) -> object:
+ g = _build_graph(nodes={"pkg/orphan.py": dict(_NODE)})
+ report = DeadCodeAnalyzer(g, git_meta_map=git_meta_map).analyze(_CONFIG)
+ return next(f for f in report.findings if f.file_path == "pkg/orphan.py")
+
+
+def test_missing_row_is_not_deletion_ready() -> None:
+ finding = _finding({})
+ assert finding.confidence == pytest.approx(NO_GIT_SIGNAL_CONFIDENCE)
+ assert finding.confidence < SAFE_CONFIDENCE_THRESHOLD
+ assert not finding.safe_to_delete
+ assert "No git history recorded for this file" in finding.evidence
+ assert "No commits in last 90 days" not in finding.evidence
+
+
+def test_empty_row_reads_the_same_as_a_missing_one() -> None:
+ finding = _finding({"pkg/orphan.py": {}})
+ assert finding.confidence == pytest.approx(NO_GIT_SIGNAL_CONFIDENCE)
+ assert not finding.safe_to_delete
+
+
+def test_a_row_with_no_recent_commits_keeps_its_rung() -> None:
+ """The fix narrows one rung; a file git confirms quiet still scores it."""
+ finding = _finding(
+ {
+ "pkg/orphan.py": {
+ "commit_count_90d": 0,
+ "last_commit_at": _now() - timedelta(days=400),
+ "age_days": 900,
+ }
+ }
+ )
+ assert finding.confidence == pytest.approx(1.0)
+ assert finding.safe_to_delete
diff --git a/tests/unit/generation/test_editor_file_fetcher.py b/tests/unit/generation/test_editor_file_fetcher.py
index a97a39d91..994a2862b 100644
--- a/tests/unit/generation/test_editor_file_fetcher.py
+++ b/tests/unit/generation/test_editor_file_fetcher.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from datetime import UTC, datetime, timedelta
+from pathlib import Path
import pytest
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
@@ -99,6 +100,13 @@ async def _add_page(session, repo_id, page_id, page_type, target_path, content):
return page
+def _touch(root: Path, *paths: str) -> None:
+ """The hotspot list only names files that exist in the checkout."""
+ for path in paths:
+ (root / path).parent.mkdir(parents=True, exist_ok=True)
+ (root / path).write_text("", encoding="utf-8")
+
+
async def _add_git_meta(
session,
repo_id,
@@ -270,6 +278,7 @@ async def test_fetch_entry_points_prefers_curated_list(session, repo, tmp_path):
async def test_fetch_hotspots(session, repo, tmp_path):
+ _touch(tmp_path, "src/billing.py", "src/utils.py")
await _add_git_meta(
session, repo.id, "src/billing.py", is_hotspot=True, churn_pct=0.95, owner="@alice"
)
@@ -288,6 +297,7 @@ async def test_fetch_hotspots(session, repo, tmp_path):
async def test_fetch_hotspots_admits_bug_magnets_that_are_not_churn_hotspots(
session, repo, tmp_path
):
+ _touch(tmp_path, "src/busy.py", "src/broken.py")
# The filter used to be is_hotspot-only, so a file fixed four times last
# month that simply is not busy could never appear no matter how it ranked.
await _add_git_meta(session, repo.id, "src/busy.py", is_hotspot=True, churn_pct=0.99)
@@ -314,6 +324,7 @@ async def test_fetch_hotspots_admits_bug_magnets_that_are_not_churn_hotspots(
async def test_fetch_hotspots_falls_back_to_churn_order_without_fix_data(session, repo, tmp_path):
+ _touch(tmp_path, "src/low.py", "src/high.py")
# A repo with no fix convention has zero fix mass everywhere; the ordering
# must degrade to exactly the churn ranking it had before, not to nothing.
await _add_git_meta(session, repo.id, "src/low.py", is_hotspot=True, churn_pct=0.20)
@@ -329,6 +340,7 @@ async def test_fetch_hotspots_falls_back_to_churn_order_without_fix_data(session
async def test_fetch_hotspots_drops_the_magnet_flag_when_recency_is_unknown(
session, repo, tmp_path
):
+ _touch(tmp_path, "src/a.py")
# bug_magnet with a NULL last_fix_at would render an unanchored accusation.
await _add_git_meta(
session,
@@ -442,3 +454,62 @@ async def test_fetch_indexed_commit_falls_back_to_live_head_when_stored_is_empty
# tmp_path is not a git checkout, so the fallback resolves to "".
assert data.indexed_commit == ""
+
+
+async def test_fetch_hotspots_skips_files_no_longer_in_the_checkout(session, repo, tmp_path):
+ """A git_metadata row outlives its file when the prune refuses a run; the
+ deleted file used to rank first in "files that need care" forever (#1929)."""
+ _touch(tmp_path, "src/alive.py")
+ await _add_git_meta(
+ session,
+ repo.id,
+ "src/deleted.py",
+ is_hotspot=True,
+ churn_pct=0.99,
+ fix_mass=9.0,
+ bug_magnet=True,
+ last_fix_at=_now() - timedelta(days=3),
+ )
+ await _add_git_meta(session, repo.id, "src/alive.py", is_hotspot=True, churn_pct=0.50)
+
+ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
+
+ assert [h.path for h in data.hotspots] == ["src/alive.py"]
+
+
+async def _add_metric(session, repo_id, path, score):
+ from repowise.core.persistence.models import HealthFileMetric
+
+ session.add(HealthFileMetric(repository_id=repo_id, file_path=path, score=score, nloc=10))
+ await session.flush()
+
+
+async def test_code_health_trend_is_absent_without_history(session, repo, tmp_path):
+ await _add_metric(session, repo.id, "src/a.py", 7.0)
+
+ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
+
+ assert data.code_health is not None
+ assert data.code_health.hotspot_trend is None
+
+
+async def test_code_health_trend_is_read_from_the_snapshots(session, repo, tmp_path):
+ from repowise.core.persistence.crud import save_health_snapshot
+
+ await _add_metric(session, repo.id, "src/a.py", 7.0)
+ for day, value in enumerate((8.0, 6.5)):
+ await save_health_snapshot(
+ session,
+ repo.id,
+ hotspot_health=value,
+ average_health=value,
+ worst_performer_path="src/a.py",
+ worst_performer_score=value,
+ per_file_scores={"src/a.py": value},
+ per_file_deductions={},
+ taken_at=_now() + timedelta(days=day),
+ )
+
+ data = await EditorFileDataFetcher(session, repo.id, tmp_path).fetch()
+
+ assert data.code_health.hotspot_trend == "declining"
diff --git a/tests/unit/health/test_hotspot_trend.py b/tests/unit/health/test_hotspot_trend.py
new file mode 100644
index 000000000..f30b3f450
--- /dev/null
+++ b/tests/unit/health/test_hotspot_trend.py
@@ -0,0 +1,40 @@
+"""The hotspot trend is read from the snapshots or left out.
+
+The generated CLAUDE.md printed "(stable)" beside the hotspot KPI as a
+literal, whatever the history said (#1490). Now it is the sign of the same
+delta the declining alert reads, and nothing at all when there is no history
+to read it from.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.core.analysis.health.trends import (
+ DECLINE_LOOKBACK,
+ DECLINE_THRESHOLD,
+ hotspot_trend,
+)
+
+
+def _history(*values: float) -> list[SimpleNamespace]:
+ return [SimpleNamespace(hotspot_health=v, average_health=v) for v in values]
+
+
+def test_fewer_than_two_snapshots_is_no_trend() -> None:
+ assert hotspot_trend([]) is None
+ assert hotspot_trend(_history(7.0)) is None
+
+
+def test_direction_follows_the_delta_against_the_lookback() -> None:
+ assert hotspot_trend(_history(7.0, 7.0 - DECLINE_THRESHOLD)) == "declining"
+ assert hotspot_trend(_history(7.0, 7.0 + DECLINE_THRESHOLD)) == "improving"
+ assert hotspot_trend(_history(7.0, 7.1)) == "stable"
+
+
+def test_baseline_is_the_lookback_snapshot_not_the_previous_one() -> None:
+ """Five small drops read as declining; the last step alone would not."""
+ step = DECLINE_THRESHOLD / DECLINE_LOOKBACK
+ values = [8.0 - i * step for i in range(DECLINE_LOOKBACK + 1)]
+ assert hotspot_trend(_history(*values)) == "declining"
+ assert hotspot_trend(_history(*values[-2:])) == "stable"
diff --git a/tests/unit/ingestion/test_git_index_changed_files_allowlist.py b/tests/unit/ingestion/test_git_index_changed_files_allowlist.py
new file mode 100644
index 000000000..c8fa94323
--- /dev/null
+++ b/tests/unit/ingestion/test_git_index_changed_files_allowlist.py
@@ -0,0 +1,57 @@
+"""An update's git index covers the same files a full index does.
+
+``index_repo`` skips every path outside the source-extension allowlist.
+``index_changed_files`` did not, so a changed workflow file got a row, and the
+idle-decay refresh minted a row for every tracked config and markup file; the
+health pass then scored them. A store that had taken updates held rows a fresh
+index never writes.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.git_indexer import GitIndexer
+from repowise.core.ingestion.git_indexer.tiers import GitIndexTier
+
+
+def _repo(tmp_path: Path) -> None:
+ import git as gitpython
+
+ repo = gitpython.Repo.init(tmp_path)
+ with repo.config_writer() as cw:
+ cw.set_value("user", "name", "Alice")
+ cw.set_value("user", "email", "[email protected]")
+ (tmp_path / ".github" / "workflows").mkdir(parents=True)
+ (tmp_path / "a.py").write_text("x = 1\n")
+ (tmp_path / "b.py").write_text("y = 1\n")
+ (tmp_path / ".github" / "workflows" / "ci.yaml").write_text("on: push\n")
+ (tmp_path / "README.md").write_text("# r\n")
+ repo.index.add(["a.py", "b.py", ".github/workflows/ci.yaml", "README.md"])
+ repo.index.commit("feat: add files")
+ for i in range(2, 4):
+ (tmp_path / "a.py").write_text(f"x = {i}\n")
+ (tmp_path / ".github" / "workflows" / "ci.yaml").write_text(f"on: push # {i}\n")
+ repo.index.add(["a.py", ".github/workflows/ci.yaml"])
+ repo.index.commit(f"chore: round {i}")
+ repo.close()
+
+
+async def test_changed_files_and_idle_refresh_follow_the_full_index_allowlist(tmp_path):
+ _repo(tmp_path)
+ all_files = {"a.py", "b.py", ".github/workflows/ci.yaml", "README.md"}
+ sink: dict[str, dict] = {}
+
+ rows = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_changed_files(
+ ["a.py", ".github/workflows/ci.yaml"],
+ all_files=all_files,
+ co_change_sink={},
+ idle_decay_sink=sink,
+ )
+
+ assert {r["file_path"] for r in rows} == {"a.py"}
+ assert not {p for p in sink if p.endswith((".yaml", ".md"))}
+
+ _summary, full_rows = await GitIndexer(tmp_path, tier=GitIndexTier.FULL).index_repo("r")
+ full_paths = {r["file_path"] for r in full_rows}
+ assert {r["file_path"] for r in rows} | set(sink) <= full_paths
diff --git a/tests/unit/persistence/test_health_snapshot_on_update.py b/tests/unit/persistence/test_health_snapshot_on_update.py
new file mode 100644
index 000000000..08cdab3b3
--- /dev/null
+++ b/tests/unit/persistence/test_health_snapshot_on_update.py
@@ -0,0 +1,85 @@
+"""Every health write appends a snapshot built from the stored rows.
+
+The full index used to snapshot from its in-memory report and the incremental
+update never snapshotted, so ``health --trend`` only moved on a full re-index.
+Both paths now call one writer that reads the repository's rows back, which is
+the only view that describes the whole repository after a partial write.
+"""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+from sqlalchemy import select
+
+from repowise.core.persistence.crud import upsert_repository
+from repowise.core.persistence.models import HealthFileMetric, HealthFinding, HealthSnapshot
+from repowise.core.pipeline.incremental import persist_partial_health
+from repowise.core.pipeline.persist import snapshot_health_from_store
+
+
+async def _seed(session) -> str:
+ repo = await upsert_repository(session, name="r", local_path="/tmp/r")
+ session.add_all(
+ [
+ HealthFileMetric(repository_id=repo.id, file_path="a.py", score=6.0, nloc=100),
+ HealthFileMetric(repository_id=repo.id, file_path="b.py", score=9.0, nloc=50),
+ HealthFinding(
+ repository_id=repo.id,
+ file_path="a.py",
+ biomarker_type="long_method",
+ severity="medium",
+ health_impact=1.5,
+ status="open",
+ ),
+ ]
+ )
+ await session.flush()
+ return repo.id
+
+
+async def _snapshots(session, repo_id: str) -> list[HealthSnapshot]:
+ rows = await session.execute(
+ select(HealthSnapshot)
+ .where(HealthSnapshot.repository_id == repo_id)
+ .order_by(HealthSnapshot.taken_at.asc())
+ )
+ return list(rows.scalars().all())
+
+
+async def test_snapshot_describes_every_stored_file(async_session) -> None:
+ repo_id = await _seed(async_session)
+
+ await snapshot_health_from_store(async_session, repo_id)
+
+ (snap,) = await _snapshots(async_session, repo_id)
+ assert json.loads(snap.per_file_scores_json) == {"a.py": 6.0, "b.py": 9.0}
+ assert snap.worst_performer_path == "a.py"
+ assert snap.worst_performer_score == 6.0
+
+
+async def test_no_stored_metrics_writes_no_snapshot(async_session) -> None:
+ repo = await upsert_repository(async_session, name="empty", local_path="/tmp/empty")
+ await snapshot_health_from_store(async_session, repo.id)
+ assert await _snapshots(async_session, repo.id) == []
+
+
+async def test_partial_health_persist_appends_a_snapshot(async_session) -> None:
+ """A changed-files write still snapshots the whole repository."""
+ repo_id = await _seed(async_session)
+ report = SimpleNamespace(
+ metrics=[],
+ findings=[],
+ refactoring_suggestions=[],
+ function_blame_rows=[],
+ authoritative_paths={"b.py"},
+ performance_authoritative_paths=set(),
+ performance_plan_policy=None,
+ )
+
+ await persist_partial_health(async_session, repo_id, report)
+
+ (snap,) = await _snapshots(async_session, repo_id)
+ # Both files, not only the one this run re-scored.
+ assert set(json.loads(snap.per_file_scores_json)) == {"a.py", "b.py"}