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.

feat(doc-drift): surface documentation drift in the CLI and get_health (#2313)

Raghav Chamadiya0bbb02fc15d8
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 4a3d69492..037ada5b6 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -878,7 +878,7 @@ get_health(opportunity_id="refop2_...")
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `targets` | list[string] | No | File paths, or `module:foo` to expand a module's file set. Empty means dashboard mode. |
-| `include` | list[string] | No | Opt-in blocks (default response stays lean): `"biomarkers"` (findings in dashboard mode), `"refactoring"` (structured, graph-aware refactoring plans; see below), `"trend"` (snapshot diff + declining / predicted-decline alerts), `"coverage"`, `"accuracy"` (the "does the score find the bugs?" stat, dashboard mode), `"signals"` (per-file process / people / topology signals, targeted mode), `"churn_complexity"` (churn x complexity quadrant points, dashboard mode), and a dimension name (`"performance"` / `"defect"` / `"maintainability"`) to filter findings to that pillar. |
+| `include` | list[string] | No | Opt-in blocks (default response stays lean): `"biomarkers"` (findings in dashboard mode), `"refactoring"` (structured, graph-aware refactoring plans; see below), `"trend"` (snapshot diff + declining / predicted-decline alerts), `"coverage"`, `"accuracy"` (the "does the score find the bugs?" stat, dashboard mode), `"signals"` (per-file process / people / topology signals, targeted mode), `"churn_complexity"` (churn x complexity quadrant points, dashboard mode), `"doc_drift"` (documentation whose claims about the tree no longer hold), and a dimension name (`"performance"` / `"defect"` / `"maintainability"`) to filter findings to that pillar. |
| `only` | list[string] | No | Keep just these top-level keys. `include` adds blocks, `only` subtracts them. `mode`, `_meta`, `unresolved`, `known_modules` and each kept list's `*_total` sibling always survive. The three `include` **block** names work as aliases: `biomarkers`→`findings`, `accuracy`→`defect_accuracy`, `refactoring`→`refactoring_plans`. Note that `refactoring_plans` is the raw
per-detector list and is now **opt-in**: `include=["refactoring"]` leads with
`refactoring_opportunities`, the composed unit, and emitting both would ship two
@@ -1039,6 +1039,19 @@ The opt-in enrichments:
change scatter, 90-day churn, primary / recent owner, and graph in / out
degree. Honest `null` per field when the underlying row is absent (never an
imputed zero).
+- **`doc_drift`** returns a `doc_drift` block: `findings` (each naming the
+ **document** to edit, its line, the `target` it wrongly claims exists, a
+ `reason` sentence, `kind`, `origin` and `confidence`), plus `findings_total`,
+ `documents` and the high/medium/low `confidence` split. Its `basis` field is
+ load-bearing: the detector checks only references it can resolve, most
+ references in a typical repository are uncheckable by design, and a finding is
+ evidence to check rather than a proven defect. Every document is re-checked
+ against the live tree on every `init` and every `update`, so a finding does
+ not outlive the sentence that caused it; the exception is a document that
+ could not be read on a given run, whose existing rows are left alone rather
+ than deleted. An index written before findings were stored reports
+ `{"unavailable": "index_predates_doc_drift"}` rather than an empty list. `repowise doc-drift` serves the same rows in a
+ terminal, with the evidence lines this block leaves out.
- **`churn_complexity`** returns `churn_complexity` points (one per recently-changed
file: 90-day commit count, max CCN, NLOC, score, churn percentile): the
refactor zone where volatility and tangle collide.
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 562f57967..c8cc81731 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -2,9 +2,9 @@
Complete reference for all `repowise` commands. For a guided introduction, see the [Quickstart](../start/QUICKSTART.md).
-Command list (in registration order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `generate`, `dead-code`, `health`, `risk`, `overlap`, `decision`, `coverage`, `impacted-tests`, `search`, `ask`, `context`, `symbol`, `why`, `distill`, `expand`, `saved`, `security`, `corrections`, `export`, `hook`, `agents`, `uninstall`, `status`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).
+Command list (in registration order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `generate`, `dead-code`, `doc-drift`, `health`, `risk`, `overlap`, `decision`, `coverage`, `impacted-tests`, `search`, `ask`, `context`, `symbol`, `why`, `distill`, `expand`, `saved`, `security`, `corrections`, `export`, `hook`, `agents`, `uninstall`, `status`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).
-**Do you need an LLM key?** Most commands are pure index/analysis and never call an LLM. `init` never requires a key: without one it renders the wiki from structure. It calls an LLM only when a provider is resolvable or `--prose` is passed. The exceptions: `update` (unless `--index-only` or `--no-docs`), `generate`, `restyle`, `watch` (when it regenerates a page), `health --generate-code`, and `workspace add --docs`. Everything else, `search`, `dead-code`, `health`, `risk`, `impacted-tests`, `decision`, `coverage`, `security`, `export`, `mcp`, `reindex`, `doctor`, and so on, works index-only, with no provider configured.
+**Do you need an LLM key?** Most commands are pure index/analysis and never call an LLM. `init` never requires a key: without one it renders the wiki from structure. It calls an LLM only when a provider is resolvable or `--prose` is passed. The exceptions: `update` (unless `--index-only` or `--no-docs`), `generate`, `restyle`, `watch` (when it regenerates a page), `health --generate-code`, and `workspace add --docs`. Everything else, `search`, `dead-code`, `doc-drift`, `health`, `risk`, `impacted-tests`, `decision`, `coverage`, `security`, `export`, `mcp`, `reindex`, `doctor`, and so on, works index-only, with no provider configured.
## Contents
@@ -33,6 +33,7 @@ Grouped by what you're trying to do, not alphabetically. `PATH` and flag details
[`risk`](#repowise-risk-revspec) ·
[`overlap`](#repowise-overlap) ·
[`dead-code`](#repowise-dead-code-path) ·
+[`doc-drift`](#repowise-doc-drift-path) ·
[`security`](#repowise-security) ·
[`impacted-tests`](#repowise-impacted-tests-revspec) ·
[`coverage`](#repowise-coverage)
@@ -97,7 +98,7 @@ Most commands auto-detect whether you're in a workspace root and route according
| `--repo <alias>` | Scope a workspace command to one repo. Available on commands where it makes sense. |
| `--all` | Fan out across every workspace repo (on `costs`, `search`). |
-The commands that grew these flags: `update`, `status`, `watch`, `doctor`, `costs`, `search`, `dead-code`, `decision`, `coverage`, `generate-claude-md`, `hook install/status/uninstall`.
+The commands that grew these flags: `update`, `status`, `watch`, `doctor`, `costs`, `search`, `dead-code`, `doc-drift`, `decision`, `coverage`, `generate-claude-md`, `hook install/status/uninstall`.
---
@@ -732,6 +733,42 @@ repowise dead-code --repo backend # workspace, single repo
---
+### `repowise doc-drift [PATH]`
+
+Show documentation this repository's own tree no longer satisfies: a path a
+document names that no longer exists, a link pointing at a heading that was
+renamed, a `make` target the manifest no longer declares.
+
+Reads what the last `init` or `update` stored rather than re-scanning, so it
+agrees with `get_health(include=["doc_drift"])` on the same tree.
+
+It checks only references it can resolve. Most references in a typical
+repository are uncheckable by design and are neither counted nor reported, so a
+clean run is not a claim that every sentence is true.
+
+**Options:**
+
+| Flag | Description |
+|------|-------------|
+| `--min-confidence` | Hide findings below this confidence (default: 0.4) |
+| `--kind` | Only this reference class: `path`, `link`, `anchor`, `command`. Repeatable |
+| `--format` | Output: `table` (default), `json` |
+| `--repo` | In workspace mode, target a specific repo (defaults to primary) |
+| `--no-workspace` | Force single-repo mode |
+
+```bash
+repowise doc-drift
+repowise doc-drift --kind anchor # just the renamed-heading links
+repowise doc-drift --min-confidence 0.9 # the near-certain ones
+repowise doc-drift --format json
+```
+
+Exits non-zero when there is no readable index, or when the index predates
+drift storage; in both cases `--format json` still emits a document naming the
+reason, rather than an empty finding list that would read as a clean tree.
+
+---
+
### `repowise risk [REVSPEC]`
Just-in-time change-risk scoring for a commit or diff range. Scores the defect
diff --git a/docs/start/USER_GUIDE.md b/docs/start/USER_GUIDE.md
index 78fb3005d..1dbadcf02 100644
--- a/docs/start/USER_GUIDE.md
+++ b/docs/start/USER_GUIDE.md
@@ -166,6 +166,7 @@ Grouped by what you are trying to do. Every flag for every command lives in the
| `repowise health` | Lowest-scoring files and why. `--trend` for direction, `--refactoring-targets` for concrete plans. |
| `repowise risk main..HEAD` | Repo-relative review percentile/classification plus a supporting 0-10 diff-shape score. |
| `repowise dead-code` | What nothing references any more, by confidence tier. |
+| `repowise doc-drift` | Documentation whose claims about the tree no longer hold, by confidence. |
| `repowise decision list` | Architectural decisions, their evidence and status. |
| `repowise impacted-tests` | Only the tests a diff actually exercises. |
diff --git a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
new file mode 100644
index 000000000..733de45d1
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
@@ -0,0 +1,182 @@
+"""``repowise doc-drift`` - assertions this repository's documents no longer satisfy.
+
+Reads the findings the drift pass persisted on the last ``init`` or ``update``
+rather than re-running the analyzer, and serializes them through the same
+function ``get_health(include=["doc_drift"])`` uses, so the two surfaces read
+the same rows the same way. They still differ where the caller asks them to:
+``--kind`` and ``--min-confidence`` narrow this one and not the other.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import click
+
+from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_async
+from repowise.cli.output import emit_json, emit_refusal, format_option, notice_console
+from repowise.core.analysis.doc_drift.constants import (
+ DETECTION_BASIS,
+ bucket_confidences,
+ confidence_tier,
+)
+from repowise.core.analysis.doc_drift.models import DriftKind
+
+#: Sentinels. Both are distinct from "no findings": an index that cannot be
+#: read, and one written before the drift table existed. Reporting either as
+#: zero drift would be the detector claiming a clean bill it never checked.
+_NO_INDEX = object()
+_STALE_INDEX = object()
+
+
+def _repo_path(path: str | None, repo_alias: str | None, no_workspace: bool, fmt: str) -> Path:
+ """The repository to read. One repo: a drift finding belongs to one tree."""
+ target = resolve_command_target(
+ path=path, no_workspace_flag=no_workspace, repo_alias=repo_alias
+ )
+ target.notice(notice_console(fmt), command="doc-drift")
+ return target.single_repo_path().resolve()
+
+
+async def _read(root: Path, *, min_confidence: float | None, kinds: tuple[str, ...]) -> Any:
+ """Persisted findings for *root*, or :data:`_NO_INDEX` when there is none."""
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from repowise.core.persistence.crud import get_doc_drift_findings, serialize_doc_drift_row
+
+ async with repo_index_session(root) as opened:
+ if opened is None:
+ return _NO_INDEX
+ session, repo_id = opened
+ try:
+ rows = await get_doc_drift_findings(session, repo_id, min_confidence=min_confidence)
+ except (SQLAlchemyError, OSError, LookupError):
+ # An index written before migration 0065 has no ``doc_drift_findings``
+ # table, and the query raises rather than returning nothing. Measured
+ # on a real checkout; ``repo_index_session`` shields the open, not the
+ # read, so this is the caller's to catch, as ``overlap`` does.
+ return _STALE_INDEX
+ # Filtered here rather than in the query: the store has no index on
+ # ``kind`` and the table is one row per drifted reference, so the scan
+ # the filter would ride on is the one already being done.
+ if kinds:
+ rows = [r for r in rows if r.kind in kinds]
+ return [serialize_doc_drift_row(r) for r in rows]
+
+
+def _payload(
+ root: Path, findings: list[dict[str, Any]], min_confidence: float | None
+) -> dict[str, Any]:
+ return {
+ "repo": str(root),
+ "min_confidence": min_confidence,
+ "total": len(findings),
+ "documents": len({f["file_path"] for f in findings}),
+ "confidence": bucket_confidences(f["confidence"] for f in findings),
+ "findings_basis": DETECTION_BASIS,
+ "findings": findings,
+ }
+
+
+#: Tier name to terminal colour. Keyed off :func:`confidence_tier` rather than
+#: re-comparing the thresholds, so this cannot disagree with the high/medium/low
+#: summary printed directly above it.
+_TIER_COLOUR = {"high": "red", "medium": "yellow", "low": "dim"}
+
+
+def _render(payload: dict[str, Any]) -> None:
+ """Grouped by document, because the document is the file a reader edits."""
+ from rich.markup import escape
+
+ # Sorted here, not relied upon from the query: the store orders by
+ # confidence first, so one document's findings are contiguous only when
+ # they happen to share a confidence, and a document with both a 0.95 anchor
+ # and a 0.90 path would print two headers for itself.
+ findings = sorted(payload["findings"], key=lambda f: (f["file_path"], f["line_number"]))
+ if not findings:
+ console.print("No documentation drift found.")
+ console.print(f"[dim]{escape(DETECTION_BASIS)}[/dim]")
+ return
+
+ buckets = payload["confidence"]
+ console.print(
+ f"[bold]{payload['total']} finding(s) across {payload['documents']} document(s)[/bold] "
+ f"[dim]({buckets['high']} high, {buckets['medium']} medium, {buckets['low']} low "
+ f"confidence)[/dim]"
+ )
+
+ current = None
+ for f in findings:
+ if f["file_path"] != current:
+ current = f["file_path"]
+ console.print(f"\n[cyan]{escape(current)}[/cyan]")
+ console.print(
+ f" [dim]:{f['line_number']}[/dim] "
+ f"[{_TIER_COLOUR[confidence_tier(f['confidence'])]}]{f['confidence']:.2f}[/] "
+ f"{escape(f['kind'])} {escape(f['reason'])}"
+ )
+ for line in f["evidence"]:
+ console.print(f" [dim]{escape(line)}[/dim]")
+
+ console.print(f"\n[dim]{escape(DETECTION_BASIS)}[/dim]")
+
+
[email protected]("doc-drift")
[email protected]("path", required=False, default=None)
+ "--min-confidence",
+ type=click.FloatRange(0.0, 1.0),
+ default=None,
+ help=(
+ "Hide findings below this confidence. Defaults to showing everything "
+ "the index stored; the pass already applied the repository's own cutoff "
+ "when it wrote them."
+ ),
+)
+ "--kind",
+ "kinds",
+ multiple=True,
+ type=click.Choice([k.value for k in DriftKind]),
+ help="Only this reference class. Repeatable.",
+)
[email protected]("--repo", "repo_alias", default=None, help="In workspace mode, target one repo.")
[email protected]("--no-workspace", is_flag=True, default=False, help="Force single-repo mode.")
+@format_option()
+def doc_drift_command(
+ path: str | None,
+ min_confidence: float | None,
+ kinds: tuple[str, ...],
+ repo_alias: str | None,
+ no_workspace: bool,
+ fmt: str,
+) -> None:
+ """Show documentation that the repository no longer matches."""
+ root = _repo_path(path, repo_alias, no_workspace, fmt)
+ result = run_async(_read(root, min_confidence=min_confidence, kinds=kinds))
+
+ if result is _NO_INDEX:
+ emit_refusal(
+ "no_index",
+ f"No readable Repowise index at {root}.",
+ fmt,
+ remedy="Run 'repowise init' there first.",
+ repo=str(root),
+ )
+ return
+ if result is _STALE_INDEX:
+ emit_refusal(
+ "index_predates_doc_drift",
+ f"The index at {root} was written before drift findings were stored.",
+ fmt,
+ remedy="Run 'repowise update' there to populate them.",
+ repo=str(root),
+ )
+ return
+
+ payload = _payload(root, result, min_confidence)
+ if fmt == "json":
+ emit_json(payload)
+ return
+ _render(payload)
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 5aade5f38..26f669d29 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -1344,6 +1344,31 @@ class CommandTarget:
return None
return (self.ws_root / entry.path).resolve()
+ def single_repo_path(self) -> Path:
+ """The one repository to read, narrowing workspace mode to a repo.
+
+ ``--repo <alias>`` resolves to ``mode="workspace"`` with ``repo_path``
+ left ``None``, so a command that reads ``repo_path`` directly refuses
+ every ``--repo`` call it advertises. Three commands already hand-roll
+ this narrowing (``dead-code``, ``health``, ``costs``); this is where it
+ belongs, beside :meth:`primary_path` and :meth:`resolve_repo_alias`.
+
+ Raises ``click.ClickException`` when the alias is unknown or the
+ workspace declares no primary.
+ """
+ if not self.is_workspace:
+ assert self.repo_path is not None
+ return self.repo_path
+ if self.repo_filter is not None:
+ picked = self.resolve_repo_alias(self.repo_filter)
+ if picked is None:
+ raise click.ClickException(f"Unknown repo alias: {self.repo_filter}")
+ return picked
+ primary = self.primary_path()
+ if primary is None:
+ raise click.ClickException("Workspace has no primary repo configured.")
+ return primary
+
# ------------------------------------------------------------------
# Notice rendering — every command should call this so users always
# know which mode they ended up in.
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index d5ad5f178..533c0b777 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -65,6 +65,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (
("update", "update_cmd:update_command"),
("generate", "generate_cmd:generate_command"),
("dead-code", "dead_code_cmd:dead_code_command"),
+ ("doc-drift", "doc_drift_cmd:doc_drift_command"),
("health", "health_cmd:health_command"),
("risk", "risk_cmd:risk_command"),
("overlap", "overlap_cmd:overlap_command"),
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/constants.py b/packages/core/src/repowise/core/analysis/doc_drift/constants.py
index 9ac1e6bbf..deb4dd146 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/constants.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/constants.py
@@ -29,6 +29,21 @@ HIGH_CONFIDENCE_THRESHOLD: float = 0.7
REVIEW_CONFIDENCE_THRESHOLD: float = 0.4
+def confidence_tier(value: float) -> str:
+ """The house tier one confidence falls in: ``high``, ``medium`` or ``low``.
+
+ The only place the two thresholds are compared. A surface that wants to
+ colour or group a single finding asks for its tier rather than re-deriving
+ the boundaries, so a surface and the summary beside it cannot disagree
+ about where "high" starts.
+ """
+ if value >= HIGH_CONFIDENCE_THRESHOLD:
+ return "high"
+ if value >= REVIEW_CONFIDENCE_THRESHOLD:
+ return "medium"
+ return "low"
+
+
def bucket_confidences(values) -> dict:
"""Bucket an iterable of confidences into the house high/medium/low tiers.
@@ -37,15 +52,23 @@ def bucket_confidences(values) -> dict:
copies of the same three comprehensions; a shared function is cheaper than
the test that would have had to pin them together.
"""
- high = medium = low = 0
+ counts = {"high": 0, "medium": 0, "low": 0}
for value in values:
- if value >= HIGH_CONFIDENCE_THRESHOLD:
- high += 1
- elif value >= REVIEW_CONFIDENCE_THRESHOLD:
- medium += 1
- else:
- low += 1
- return {"high": high, "medium": medium, "low": low}
+ counts[confidence_tier(value)] += 1
+ return counts
+
+
+#: What every surface must say alongside a finding count, so no consumer can
+#: imply coverage or precision this detector does not have. Two facts, both
+#: measured: 702 of this repository's 1,783 references are UNCHECKABLE by
+#: design, and two of the 19 findings are known, deliberate false positives.
+#: One string rather than one sentence per surface, for the reason
+#: ``tests/unit/dead_code/test_confidence_parity.py`` exists.
+DETECTION_BASIS: str = (
+ "Covers only references this detector can resolve; uncheckable ones are "
+ "neither counted nor reported. A finding names the document to edit, not "
+ "the target it names, and is evidence to check rather than a proven defect."
+)
#: Default ``--min-confidence`` cutoff. Matches the lowest shipping origin's
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
index bd6adbf2b..58c3090cf 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -41,6 +41,7 @@ from .doc_drift import (
get_doc_drift_findings,
replace_doc_drift_findings,
replace_doc_drift_findings_guarded,
+ serialize_doc_drift_row,
summarize_confidence_rows,
)
from .health import (
@@ -160,6 +161,7 @@ __all__ = [
"save_health_snapshot",
"save_refactoring_suggestions",
"save_test_coverage",
+ "serialize_doc_drift_row",
"sort_metrics_worst_first",
"summarize_confidence_rows",
"tests_covering",
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/doc_drift.py b/packages/core/src/repowise/core/persistence/crud/analysis/doc_drift.py
index 1ca70923a..913eba777 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/doc_drift.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/doc_drift.py
@@ -162,6 +162,54 @@ async def get_doc_drift_findings(
return list((await session.execute(stmt)).scalars().all())
+def _decode_evidence(raw: str) -> list[str]:
+ """The stored evidence lines, degrading to none rather than raising.
+
+ Pairs with the ``json.dumps`` in :func:`_row_kwargs`. An index written by an
+ older version is still readable, and a finding whose evidence blob will not
+ parse is worth more to a reader than a traceback.
+ """
+ try:
+ loaded = json.loads(raw or "[]")
+ except (TypeError, ValueError):
+ return []
+ return [str(item) for item in loaded] if isinstance(loaded, list) else []
+
+
+def serialize_doc_drift_row(row: DocDriftFinding, *, evidence: bool = True) -> dict:
+ """One stored finding as a dict, for any surface that serves it.
+
+ One function rather than one per surface. The CLI and ``get_health`` serve
+ the same rows, and two hand-maintained dicts are how they would come to
+ disagree about them --- the failure
+ ``tests/unit/dead_code/test_confidence_parity.py`` exists to remember.
+ Placed beside :func:`summarize_confidence_rows` because both are read-side
+ derivations over a row; the no-serializer rule in
+ ``analysis/doc_drift/models.py`` is about the analyzer's dataclass, which
+ neither of these touches.
+
+ ``evidence=False`` drops the evidence lines for a caller under a response
+ budget: their first line restates ``file_path``, ``line_number`` and
+ ``raw``, and the rest is the resolver's own trace.
+ """
+ out = {
+ "file_path": row.file_path,
+ "line_number": row.line_number,
+ "kind": row.kind,
+ "target": row.target,
+ # Rounded in one place, so a future three-decimal tier cannot make one
+ # surface report 0.925 where the other reports 0.93.
+ "confidence": round(row.confidence, 2),
+ "origin": row.origin,
+ "reason": row.reason,
+ "raw": row.raw,
+ "context": row.context,
+ }
+ if evidence:
+ out["evidence"] = _decode_evidence(row.evidence_json)
+ return out
+
+
def summarize_confidence_rows(rows: list[DocDriftFinding]) -> dict:
"""Re-derive the high/medium/low buckets on read.
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
index aa5b30e07..6cff9f4f6 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
@@ -290,6 +290,7 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {
"trend.recent[]",
"trend.alerts[]",
"churn_complexity[]",
+ "doc_drift.findings[]",
"test_findings[]",
"top_findings[]",
"findings[]",
@@ -322,6 +323,19 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {
"distribution",
"gap_analysis",
),
+ # The drift block exists only when it was asked for, so its place in the
+ # shed order above would otherwise guarantee that the one caller who
+ # wants it is the one who loses it first. Declared for this key alone;
+ # every other block keeps the behaviour it has. Only the inner list is
+ # named, as ``coverage.files[]`` is: the block itself is not a shed-order
+ # key, and naming one the order lacks is an entry that does nothing.
+ #
+ # Declaring anything here makes ``_requested_shed_keys`` run on every
+ # call, which folds ``targets`` into the asked-for set through
+ # ``_IMPLICIT_REQUEST_ARGUMENTS``. Inert while no token below is named
+ # ``targets`` --- but adding one would silently entitle every targeted
+ # call, which is not what a projection declaration looks like it does.
+ requested_projections=(("doc_drift", ("doc_drift.findings[]",)),),
),
# The tool caps source at 600 *lines*, and 600 lines of dense code measured
# 79k chars — far past the ceiling that line cap was sized against. Callee
diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.py
index b64e3b2c9..d9759728f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -10,7 +10,9 @@ from time import perf_counter
from typing import Any
from sqlalchemy import func, select
+from sqlalchemy.exc import SQLAlchemyError
+from repowise.core.analysis.doc_drift.constants import DETECTION_BASIS
from repowise.core.analysis.health.aggregation import module_rollups as _module_rollups
from repowise.core.analysis.health.churn_complexity import churn_complexity_points
from repowise.core.analysis.health.counts import (
@@ -50,6 +52,7 @@ from repowise.core.ingestion.models import FILE_DEPENDENCY_EDGE_TYPES
from repowise.core.persistence.crud import (
get_all_git_metadata,
get_coverage_summary,
+ get_doc_drift_findings,
get_file_language_map,
get_git_metadata_bulk,
get_health_finding_by_public_id,
@@ -59,6 +62,8 @@ from repowise.core.persistence.crud import (
get_test_file_paths,
list_health_snapshots,
load_coverage_for_repo,
+ serialize_doc_drift_row,
+ summarize_confidence_rows,
)
from repowise.core.persistence.database import get_session
from repowise.core.persistence.models import (
@@ -1546,7 +1551,7 @@ async def get_health(
) -> dict:
"""Code-health scores and findings from stored analysis.
- No ``targets`` returns a dashboard; targets return ranked files and findings.
+ No ``targets`` returns a dashboard; targets rank files and findings.
Never recomputes health: commit, then run ``repowise update``.
Every block and accepted value: docs/agent/MCP_TOOLS.md.
@@ -1554,9 +1559,9 @@ async def get_health(
targets: file paths or ``module:<name>``; empty means dashboard,
unmatched ones land in ``unresolved``.
include: ``biomarkers``|``refactoring``|``trend``|``coverage``|
- ``accuracy``|``signals``|``churn_complexity``, or a dimension;
- ``performance`` and ``refactoring`` add their queues.
- only: keys to keep; identity, totals and recovery survive.
+ ``accuracy``|``signals``|``churn_complexity``|``doc_drift``,
+ or a dimension; ``performance``/``refactoring`` add queues.
+ only: keys to keep; identity, totals, recovery survive.
``biomarkers``/``accuracy``/``refactoring`` alias their block key;
``performance``/``defect``/``maintainability`` do not: they filter
rows and land in ``unknown_only_keys``.
@@ -1597,6 +1602,7 @@ async def get_health(
"accuracy",
"signals",
"churn_complexity",
+ "doc_drift",
"performance",
"defect",
"maintainability",
@@ -1686,6 +1692,7 @@ async def get_health(
"modules",
"churn_complexity",
"coverage.files",
+ "doc_drift.findings",
"refactoring_plans",
"refactoring_opportunities",
"refactoring_evidence",
@@ -2240,6 +2247,38 @@ async def get_health(
file_signals(git_meta_by_path.get(path), degrees_by_path.get(path))
)
+ # Documentation this repository's own tree no longer satisfies. A
+ # finding is filed against the DOCUMENT, so ``targets`` narrows by the
+ # document path: naming ``docs/a.md`` asks about drift in that file.
+ # Targets are matched exactly, as everywhere else in this tool, so a
+ # bare directory resolves to nothing and lands in ``unresolved``.
+ drift_rows: list[Any] = []
+ drift_unavailable: str | None = None
+ if "doc_drift" in include_set:
+ try:
+ # The savepoint is not decoration. This read raises on an index
+ # written before the drift table existed, and on Postgres a
+ # failed statement poisons the transaction, so without it one
+ # missing table would take every later read in this call down
+ # with it. ``replace_doc_drift_findings_guarded`` guards the
+ # write side against the same hazard.
+ async with session.begin_nested():
+ rows = await get_doc_drift_findings(session, repository.id)
+ # Only the exclude config, NOT ``in_scope_rows``. That helper
+ # also applies the ``production`` scope, whose path set is the
+ # files carrying a health metric --- and no markdown file
+ # carries one. Routing drift through it made
+ # ``scope="production"`` report every document as clean, which
+ # is the one answer this detector must never give by accident.
+ drift_rows = filter_rows_by_attr(rows, "file_path", exclude_spec)
+ except (SQLAlchemyError, OSError, LookupError):
+ # Say the block could not be read rather than serve an empty
+ # list, which would read as a clean bill of health that was
+ # never taken.
+ drift_unavailable = "index_predates_doc_drift"
+ if scoped:
+ drift_rows = [r for r in drift_rows if r.file_path in effective_targets]
+
# Churn x complexity quadrant for the whole repo (dashboard mode). One
# git-metadata query joined against the already-loaded metrics.
churn_points: list[dict[str, Any]] = []
@@ -2850,6 +2889,33 @@ async def get_health(
if len(coverage_payload) < len(coverage_rows):
result["coverage"]["files_reduced_reason"] = "limit"
+ if "doc_drift" in include_set:
+ if drift_unavailable is not None:
+ result["doc_drift"] = {"unavailable": drift_unavailable}
+ else:
+ drift_payload = bounded(
+ # ``evidence=False``: its first line restates ``file_path``,
+ # ``line_number`` and ``raw``, and the rest is the resolver's
+ # own trace, which is a poor trade against this budget. The
+ # CLI, which has no budget, keeps it.
+ [serialize_doc_drift_row(r, evidence=False) for r in drift_rows],
+ "doc_drift.findings",
+ )
+ result["doc_drift"] = {
+ "findings": drift_payload,
+ "findings_total": len(drift_rows),
+ "findings_emitted": len(drift_payload),
+ "documents": len({r.file_path for r in drift_rows}),
+ "confidence": summarize_confidence_rows(drift_rows),
+ # The same sentence the CLI prints, under the house ``*_basis``
+ # name for "what this count does and does not cover". A surface
+ # that shows findings without it claims coverage and precision
+ # this detector does not have: most references are uncheckable.
+ "findings_basis": DETECTION_BASIS,
+ }
+ if len(drift_payload) < len(drift_rows):
+ result["doc_drift"]["findings_reduced_reason"] = "limit"
+
# (The dimension filter — ``include=["performance"]`` and friends, so an
# agent can ask "show me only the performance risk in this change" — is
# applied where the rows are selected, not here. Filtering the finished
diff --git a/tests/unit/cli/test_command_target.py b/tests/unit/cli/test_command_target.py
index d9f1a5e9c..58933d561 100644
--- a/tests/unit/cli/test_command_target.py
+++ b/tests/unit/cli/test_command_target.py
@@ -218,3 +218,40 @@ def test_is_workspace_property(fake_workspace, chdir):
assert resolve_command_target().is_workspace is True
chdir(fake_workspace / "backend")
assert resolve_command_target().is_workspace is False
+
+
+# ---------------------------------------------------------------------------
+# single_repo_path — the narrowing every read-only command needs
+# ---------------------------------------------------------------------------
+
+
+def test_single_repo_path_honours_repo_alias(fake_workspace, chdir):
+ """``--repo`` resolves to workspace mode with ``repo_path`` left None, so a
+ command reading ``repo_path`` directly refuses every ``--repo`` call it
+ advertises. That is the bug this method exists to stop repeating."""
+ chdir(fake_workspace)
+ target = resolve_command_target(repo_alias="frontend")
+
+ assert target.repo_path is None
+ assert target.single_repo_path() == fake_workspace / "frontend"
+
+
+def test_single_repo_path_falls_back_to_the_primary(fake_workspace, chdir):
+ chdir(fake_workspace)
+ assert resolve_command_target().single_repo_path() == fake_workspace / "backend"
+
+
+def test_single_repo_path_passes_a_single_repo_through(fake_workspace, chdir):
+ chdir(fake_workspace / "backend")
+ target = resolve_command_target()
+
+ assert target.single_repo_path() == target.repo_path
+
+
+def test_single_repo_path_refuses_an_unknown_alias(fake_workspace, chdir):
+ chdir(fake_workspace)
+ target = resolve_command_target()
+ object.__setattr__(target, "repo_filter", "nope")
+
+ with pytest.raises(click.ClickException):
+ target.single_repo_path()
diff --git a/tests/unit/cli/test_doc_drift_cmd.py b/tests/unit/cli/test_doc_drift_cmd.py
new file mode 100644
index 000000000..8fdb7bbab
--- /dev/null
+++ b/tests/unit/cli/test_doc_drift_cmd.py
@@ -0,0 +1,205 @@
+"""``repowise doc-drift`` reads persisted findings and never invents a clean tree.
+
+The refusal cases carry most of the weight here. An empty finding list is the
+detector's *good* answer, so every way of failing to read one has to be
+distinguishable from it — otherwise a broken index reports as tidy documentation.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from click.testing import CliRunner
+from sqlalchemy.exc import OperationalError
+
+from repowise.cli.commands import doc_drift_cmd
+from repowise.core.analysis.doc_drift.constants import DETECTION_BASIS
+from repowise.core.persistence.crud import serialize_doc_drift_row
+
+
+class _Row:
+ """A ``DocDriftFinding`` row, only the attributes the command reads."""
+
+ def __init__(self, **kw):
+ self.file_path = kw.get("file_path", "docs/a.md")
+ self.line_number = kw.get("line_number", 7)
+ self.kind = kw.get("kind", "path")
+ self.target = kw.get("target", "src/gone.py")
+ self.confidence = kw.get("confidence", 0.9)
+ self.origin = kw.get("origin", "path_no_candidate")
+ self.reason = kw.get("reason", "Document names src/gone.py, which no longer exists.")
+ self.evidence_json = kw.get("evidence_json", '["docs/a.md:7 states `src/gone.py`"]')
+ self.raw = kw.get("raw", "src/gone.py")
+ self.context = kw.get("context", "see src/gone.py")
+
+
+def _invoke(monkeypatch, tmp_path, result, args=()):
+ monkeypatch.setattr(doc_drift_cmd, "_repo_path", lambda *a, **k: tmp_path)
+ def _run(coro):
+ # Close it rather than leaking an un-awaited coroutine warning, the way
+ # ``test_tool_adapter_commands._spy_run`` does.
+ coro.close()
+ return result
+
+ monkeypatch.setattr(doc_drift_cmd, "run_async", _run)
+ return CliRunner().invoke(doc_drift_cmd.doc_drift_command, list(args))
+
+
+def test_findings_render_with_document_line_and_evidence(monkeypatch, tmp_path):
+ rows = [serialize_doc_drift_row(_Row())]
+ result = _invoke(monkeypatch, tmp_path, rows)
+
+ assert result.exit_code == 0
+ assert "docs/a.md" in result.output
+ assert ":7" in result.output
+ # The evidence line is the thing a reader checks for themselves.
+ assert "states" in result.output
+
+
+def test_json_carries_the_whole_row_and_the_basis(monkeypatch, tmp_path):
+ rows = [serialize_doc_drift_row(_Row())]
+ result = _invoke(monkeypatch, tmp_path, rows, ["--format", "json"])
+
+ payload = json.loads(result.output)
+ assert payload["total"] == 1
+ assert payload["documents"] == 1
+ assert payload["confidence"] == {"high": 1, "medium": 0, "low": 0}
+ assert payload["findings_basis"] == DETECTION_BASIS
+ finding = payload["findings"][0]
+ assert finding["file_path"] == "docs/a.md"
+ assert finding["target"] == "src/gone.py"
+ assert finding["evidence"] == ["docs/a.md:7 states `src/gone.py`"]
+
+
[email protected]("fmt", ["table", "json"])
+def test_a_clean_tree_still_states_what_was_not_checked(monkeypatch, tmp_path, fmt):
+ """Zero findings is a real answer, and it must not read as full coverage."""
+ result = _invoke(monkeypatch, tmp_path, [], ["--format", fmt])
+
+ assert result.exit_code == 0
+ if fmt == "json":
+ assert json.loads(result.output)["findings_basis"] == DETECTION_BASIS
+ else:
+ # Rich wraps the sentence, so match a fragment that survives wrapping.
+ assert "uncheckable" in result.output
+
+
+ ("sentinel", "code"),
+ [
+ (doc_drift_cmd._NO_INDEX, "no_index"),
+ (doc_drift_cmd._STALE_INDEX, "index_predates_doc_drift"),
+ ],
+)
+def test_an_unreadable_index_refuses_rather_than_reporting_zero(
+ monkeypatch, tmp_path, sentinel, code
+):
+ """The failure this guards: "no rows" and "no table" rendering identically."""
+ result = _invoke(monkeypatch, tmp_path, sentinel, ["--format", "json"])
+
+ assert result.exit_code == 1
+ payload = json.loads(result.output)
+ assert payload["error"] == code
+ assert "findings" not in payload
+
+
+def test_a_missing_drift_table_becomes_the_stale_sentinel(monkeypatch, tmp_path):
+ """An index older than the drift table makes the read raise, not return [].
+
+ Measured on a real checkout: ``repo_index_session`` shields opening the
+ store, not querying it, so this is the command's to catch.
+ """
+
+ async def _raise(*_a, **_k):
+ raise OperationalError("select", {}, Exception("no such table: doc_drift_findings"))
+
+ import repowise.core.persistence.crud as crud
+
+ monkeypatch.setattr(crud, "get_doc_drift_findings", _raise)
+
+ class _Session:
+ pass
+
+ def _fake_session(_root):
+ import contextlib
+
+ @contextlib.asynccontextmanager
+ async def _cm():
+ yield (_Session(), "repo-id")
+
+ return _cm()
+
+ monkeypatch.setattr(doc_drift_cmd, "repo_index_session", _fake_session)
+
+ import asyncio
+
+ got = asyncio.run(doc_drift_cmd._read(tmp_path, min_confidence=0.4, kinds=()))
+ assert got is doc_drift_cmd._STALE_INDEX
+
+
+def test_findings_group_under_one_header_per_document(monkeypatch, tmp_path):
+ """The store orders by confidence first, so rows for one document are not
+ contiguous unless they happen to share one. Without a sort the same
+ document prints a header for each run."""
+ rows = [
+ serialize_doc_drift_row(_Row(file_path="docs/a.md", line_number=1, confidence=0.95)),
+ serialize_doc_drift_row(_Row(file_path="docs/b.md", line_number=3, confidence=0.9)),
+ serialize_doc_drift_row(_Row(file_path="docs/a.md", line_number=9, confidence=0.85)),
+ ]
+
+ result = _invoke(monkeypatch, tmp_path, rows)
+
+ # Headers are the only lines that are a bare document path; the evidence
+ # lines name it too, so count headers rather than occurrences.
+ headers = [line for line in result.output.splitlines() if line.strip() == "docs/a.md"]
+ assert len(headers) == 1
+
+
+def test_kind_and_confidence_filters_reach_the_query_and_the_rows(monkeypatch, tmp_path):
+ """``--min-confidence`` is pushed into SQL; ``--kind`` filters the rows."""
+ import asyncio
+ import contextlib
+
+ seen: dict = {}
+ rows = [_Row(kind="path"), _Row(kind="anchor", confidence=0.95)]
+
+ async def _fake(_session, _repo_id, **kw):
+ seen.update(kw)
+ return rows
+
+ import repowise.core.persistence.crud as crud
+
+ monkeypatch.setattr(crud, "get_doc_drift_findings", _fake)
+
+ @contextlib.asynccontextmanager
+ async def _cm(_root):
+ yield (object(), "repo-id")
+
+ monkeypatch.setattr(doc_drift_cmd, "repo_index_session", _cm)
+
+ got = asyncio.run(doc_drift_cmd._read(tmp_path, min_confidence=0.9, kinds=("anchor",)))
+
+ assert seen["min_confidence"] == 0.9
+ assert [f["kind"] for f in got] == ["anchor"]
+
+
+def test_min_confidence_defaults_to_showing_what_the_index_stored(monkeypatch, tmp_path):
+ """The pass already applied the repository's cutoff at write time. A second
+ hardcoded cutoff here would hide rows ``get_health`` still shows."""
+ captured: dict = {}
+
+ def _run(coro):
+ coro.close()
+ return []
+
+ monkeypatch.setattr(doc_drift_cmd, "_repo_path", lambda *a, **k: tmp_path)
+ monkeypatch.setattr(doc_drift_cmd, "run_async", _run)
+ monkeypatch.setattr(
+ doc_drift_cmd, "_payload", lambda root, findings, mc: captured.setdefault("mc", mc) or {}
+ )
+ monkeypatch.setattr(doc_drift_cmd, "_render", lambda _p: None)
+
+ CliRunner().invoke(doc_drift_cmd.doc_drift_command, [])
+
+ assert captured["mc"] is None
diff --git a/tests/unit/cli/test_format_json_rollout.py b/tests/unit/cli/test_format_json_rollout.py
index ce5a796fa..9add7b33b 100644
--- a/tests/unit/cli/test_format_json_rollout.py
+++ b/tests/unit/cli/test_format_json_rollout.py
@@ -51,6 +51,7 @@ _FORMAT_COMMANDS = [
("repowise.cli.commands.workspace_cmd", "workspace_diagnostics"),
("repowise.cli.commands.workspace_cmd", "workspace_metrics"),
("repowise.cli.commands.dead_code_cmd", "dead_code_command"),
+ ("repowise.cli.commands.doc_drift_cmd", "doc_drift_command"),
]
# Commands that shipped a machine mode under a different name. The old flag
diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.py
index 633ed477c..d2e36c363 100644
--- a/tests/unit/cli/test_lazy_commands.py
+++ b/tests/unit/cli/test_lazy_commands.py
@@ -34,7 +34,8 @@ from repowise.core.registry import CLIRegistry, LazyCommand
_EXPECTED_NAMES = frozenset(
{
"agents", "ask", "augment", "context", "corrections", "costs", "coverage",
- "dead-code", "decision", "delete", "distill", "doctor", "expand",
+ "dead-code", "decision", "delete", "distill", "doc-drift", "doctor",
+ "expand",
"export", "generate", "generate-claude-md", "health", "hook",
"impacted-tests", "init", "login", "logout", "mcp", "overlap", "reindex",
"restyle",
diff --git a/tests/unit/persistence/test_doc_drift_crud.py b/tests/unit/persistence/test_doc_drift_crud.py
index 81b43748c..f9b2983c3 100644
--- a/tests/unit/persistence/test_doc_drift_crud.py
+++ b/tests/unit/persistence/test_doc_drift_crud.py
@@ -215,3 +215,42 @@ async def test_read_side_buckets_match_the_analyzer(async_session):
rows = await get_doc_drift_findings(async_session, repo.id)
assert summarize_confidence_rows(rows) == summarize_confidence(findings)
+
+
+async def test_one_serializer_serves_both_surfaces(async_session):
+ """The CLI and ``get_health`` read the same rows, so they serialize them
+ through one function. Two hand-maintained dicts is how they would come to
+ disagree, which is what ``test_confidence_parity`` exists to remember."""
+ from repowise.core.persistence.crud import serialize_doc_drift_row
+
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_findings(async_session, repo.id, [_finding(line=1)])
+ await async_session.commit()
+
+ (row,) = await get_doc_drift_findings(async_session, repo.id)
+ full = serialize_doc_drift_row(row)
+ budgeted = serialize_doc_drift_row(row, evidence=False)
+
+ # The document is what a reader edits, so it is what the finding names.
+ assert full["file_path"] == row.file_path
+ # ``evidence`` is the only difference; everything else must match, or the
+ # terminal and the agent are describing the same row differently.
+ assert set(full) - set(budgeted) == {"evidence"}
+ assert all(budgeted[k] == full[k] for k in budgeted)
+
+
+async def test_unreadable_evidence_degrades_to_none_rather_than_raising():
+ """An index written by an older version is still worth reading."""
+ import types
+
+ from repowise.core.persistence.crud import serialize_doc_drift_row
+
+ def _row(blob):
+ return types.SimpleNamespace(
+ file_path="docs/a.md", line_number=1, kind="path", target="src/gone.py",
+ confidence=0.9, origin="path_no_candidate", reason="r", raw="x", context="c",
+ evidence_json=blob,
+ )
+
+ for blob in ("{not json", '{"a": 1}', "", None):
+ assert serialize_doc_drift_row(_row(blob))["evidence"] == []
diff --git a/tests/unit/server/mcp/test_health_doc_drift.py b/tests/unit/server/mcp/test_health_doc_drift.py
new file mode 100644
index 000000000..a89954add
--- /dev/null
+++ b/tests/unit/server/mcp/test_health_doc_drift.py
@@ -0,0 +1,200 @@
+"""``get_health(include=["doc_drift"])`` — the agent-facing drift surface.
+
+Two things are load-bearing and neither is caught by the generic budget tests.
+``test_every_shed_path_names_a_real_block`` skips a top-level block the recorded
+shape does not contain, and this block is absent unless it is asked for, so the
+shed path is unverified there. And the block's ``basis`` is the only thing
+stopping a finding count from reading as a coverage claim.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.exc import OperationalError
+
+from repowise.core.analysis.doc_drift.constants import DETECTION_BASIS
+from repowise.core.persistence.models import DocDriftFinding
+
+
+def _finding(repo_id: str, path: str, line: int, **kw) -> DocDriftFinding:
+ return DocDriftFinding(
+ repository_id=repo_id,
+ file_path=path,
+ line_number=line,
+ kind=kw.get("kind", "path"),
+ target=kw.get("target", "src/gone.py"),
+ confidence=kw.get("confidence", 0.9),
+ reason=kw.get("reason", "Document names src/gone.py, which no longer exists."),
+ origin=kw.get("origin", "path_no_candidate"),
+ evidence_json='["docs/a.md:1 states `src/gone.py`"]',
+ raw="src/gone.py",
+ context="see src/gone.py",
+ )
+
+
+async def drift_rows(session, repo_id):
+ session.add_all(
+ [
+ _finding(repo_id, "docs/a.md", 7),
+ _finding(repo_id, "docs/a.md", 19, kind="anchor", confidence=0.95),
+ _finding(repo_id, "docs/b.md", 3, confidence=0.5, origin="path_no_candidate_in_guide"),
+ ]
+ )
+ await session.commit()
+ return repo_id
+
+
+async def test_the_block_is_absent_until_it_is_asked_for(setup_mcp, drift_rows):
+ from repowise.server.mcp_server import get_health
+
+ assert "doc_drift" not in await get_health()
+
+
+async def test_doc_drift_is_a_known_include_key(setup_mcp, drift_rows):
+ """An unknown key is reported rather than ignored, so this would be visible."""
+ from repowise.server.mcp_server import get_health
+
+ result = await get_health(include=["doc_drift"])
+ assert "doc_drift" not in (result.get("unknown_include_keys") or [])
+
+
+async def test_the_block_carries_findings_totals_and_its_basis(setup_mcp, drift_rows):
+ from repowise.server.mcp_server import get_health
+
+ block = (await get_health(include=["doc_drift"]))["doc_drift"]
+
+ assert block["findings_total"] == 3
+ assert block["documents"] == 2
+ assert block["confidence"] == {"high": 2, "medium": 1, "low": 0}
+ # Without this a reader takes three findings as the whole truth about the
+ # documentation, when most references were never checkable.
+ assert block["findings_basis"] == DETECTION_BASIS
+
+ lead = block["findings"][0]
+ # Filed against the DOCUMENT, not the target it names.
+ assert lead["file_path"].endswith(".md")
+ assert lead["target"] == "src/gone.py"
+ assert {"line_number", "kind", "origin", "reason", "raw", "context"} <= set(lead)
+ # Budgeted: the evidence lines are the CLI's job.
+ assert "evidence" not in lead
+
+
+async def test_targets_narrow_drift_to_those_documents(setup_mcp, drift_rows):
+ """A finding is filed against the document, so the file scope is the doc scope."""
+ from repowise.server.mcp_server import get_health
+
+ block = (await get_health(targets=["docs/a.md"], include=["doc_drift"]))["doc_drift"]
+
+ assert block["findings_total"] == 2
+ assert {f["file_path"] for f in block["findings"]} == {"docs/a.md"}
+
+
+async def test_limit_caps_the_list_and_says_so(setup_mcp, drift_rows):
+ from repowise.server.mcp_server import get_health
+
+ block = (await get_health(include=["doc_drift"], limit=1))["doc_drift"]
+
+ assert block["findings_emitted"] == 1
+ assert block["findings_total"] == 3
+ assert block["findings_reduced_reason"] == "limit"
+
+
+async def test_production_scope_does_not_report_every_document_as_clean(
+ setup_mcp, health_data, drift_rows
+):
+ """The regression this exists for: a scope wipe rendering as a clean tree.
+
+ ``scope="production"`` narrows every block to the files carrying a health
+ metric. No markdown file carries one, so routing drift rows through that
+ filter reported all 19 real findings on this repository as zero, on a
+ supported argument, with nothing in the response saying why.
+ """
+ from repowise.server.mcp_server import get_health
+
+ block = (await get_health(include=["doc_drift"], scope="production"))["doc_drift"]
+
+ assert block["findings_total"] == 3
+
+
+async def test_an_index_without_the_drift_table_says_so(
+ setup_mcp, health_data, drift_rows, monkeypatch
+):
+ """"Could not read" must never render as "nothing to report"."""
+ import repowise.server.mcp_server.tool_health as th
+ from repowise.server.mcp_server import get_health
+
+ async def _raise(*_a, **_k):
+ raise OperationalError("select", {}, Exception("no such table: doc_drift_findings"))
+
+ monkeypatch.setattr(th, "get_doc_drift_findings", _raise)
+
+ result = await get_health(include=["doc_drift"])
+
+ assert result["doc_drift"] == {"unavailable": "index_predates_doc_drift"}
+ # And the failed read did not take the rest of the response with it.
+ assert result["kpis"]["file_count"] > 0
+
+
+async def test_the_include_token_really_reaches_the_budget_as_a_request(setup_mcp, drift_rows):
+ """Assert the wiring, not a hand-built set: the token has to survive
+ ``_requested_shed_keys`` for the deferral to mean anything in production."""
+ import inspect
+
+ from repowise.server.mcp_server._budget.contracts import _CONTRACTS, _requested_shed_keys
+ from repowise.server.mcp_server.tool_health import get_health as raw_get_health
+
+ keys = _requested_shed_keys(
+ _CONTRACTS["get_health"],
+ inspect.signature(raw_get_health),
+ (),
+ {"include": ["doc_drift"]},
+ )
+ assert "doc_drift.findings" in keys
+
+ # And a call that did not ask for it is entitled to nothing.
+ assert not _requested_shed_keys(
+ _CONTRACTS["get_health"],
+ inspect.signature(raw_get_health),
+ (),
+ {"targets": ["src/a.py"]},
+ )
+
+
+def test_the_shed_path_names_the_block_the_tool_actually_emits():
+ """A shed path that does not resolve sheds nothing, silently.
+
+ The recorded-shape sweep cannot catch this one: it skips a top-level block
+ the recording does not contain, and this block only exists under ``include``.
+ """
+ from repowise.server.mcp_server._budget.contracts import _CONTRACTS
+
+ contract = _CONTRACTS["get_health"]
+ assert "doc_drift.findings[]" in contract.shed_order
+ assert ("doc_drift", ("doc_drift.findings[]",)) in contract.requested_projections
+
+
+def test_asking_for_drift_defers_it_to_the_back_of_the_shed_order():
+ """Otherwise the only caller who wants the block is the one who loses it."""
+ from repowise.server.mcp_server._budget.contracts import (
+ _CONTRACTS,
+ _prioritised_shed_order,
+ )
+
+ order = _CONTRACTS["get_health"].shed_order
+ assert order.index("doc_drift.findings[]") < order.index("findings[]")
+
+ deferred = _prioritised_shed_order(order, frozenset({"doc_drift.findings"}))
+ assert deferred[-1] == "doc_drift.findings[]"
+ # Nothing else moved.
+ assert [k for k in deferred if k != "doc_drift.findings[]"] == [
+ k for k in order if k != "doc_drift.findings[]"
+ ]
diff --git a/website/mcp-server.md b/website/mcp-server.md
index ae99bb019..5ad302d70 100644
--- a/website/mcp-server.md
+++ b/website/mcp-server.md
@@ -403,7 +403,8 @@ same deterministic markers as `repowise health`. Zero LLM calls.
**Parameters:**
- `targets` (optional) — file paths, or `module:foo`; empty = dashboard mode
- `include` (optional) — opt-in blocks such as `"biomarkers"`, `"refactoring"`,
- `"trend"`, `"coverage"`, `"accuracy"`, `"signals"`, `"churn_complexity"`
+ `"trend"`, `"coverage"`, `"accuracy"`, `"signals"`, `"churn_complexity"`,
+ `"doc_drift"`
- `limit` (optional, int) — max lowest-scoring files (default 20)
**When to use:** Self-check a change before opening a PR, or find the worst