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): answer which documents name a file (#2356)

Raghav Chamadiya7766e17a4d12
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 27a4e3a1c..7db77a082 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -326,7 +326,7 @@ The workhorse tool. Returns docs, symbols, ownership, freshness, and community m
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `targets` | list[string] | Yes | File paths, module names, or symbol IDs. Batch multiple targets in one call. Symbol ids take the same `"path/to/file.py::Name"` form `get_symbol` accepts, with the same `::` / `.` / `/` separator normalisation, so an id from either tool works in the other. |
-| `include` | list[string] | No | Additional data to include: `"full_doc"` (full wiki markdown), `"callers"` (who calls this, symbol targets), `"callees"` (what this calls, symbol targets), `"ownership"` (primary owner, bus factor, contributor count), `"last_change"` (last commit date + author), `"metrics"` (PageRank, betweenness, percentiles), `"community"` (cluster membership + neighbors), `"decisions"` (full decision records; default returns titles only), `"skeleton"` (file targets only; the file with bodies elided: every signature, imports, and the bodies of the most central symbols, token-budgeted; typically ~15% of the full file's tokens). An empty `callers`, `callees` or `used_by` list sits beside a `*_basis` object: the language, how many call edges the index resolved for it, the share of those that are guesses, and a note that unbound call sites are not counted, so an empty list means no resolved edge, not proof of none |
+| `include` | list[string] | No | Additional data to include: `"full_doc"` (full wiki markdown), `"callers"` (who calls this, symbol targets), `"callees"` (what this calls, symbol targets), `"ownership"` (primary owner, bus factor, contributor count), `"last_change"` (last commit date + author), `"metrics"` (PageRank, betweenness, percentiles), `"community"` (cluster membership + neighbors), `"decisions"` (full decision records; default returns titles only), `"skeleton"` (file targets only; the file with bodies elided: every signature, imports, and the bodies of the most central symbols, token-budgeted; typically ~15% of the full file's tokens), `"health"` (code-health score and biomarkers), `"doc_drift"` (the documents that name this file, and whether those documents carry drift of their own). An empty `callers`, `callees` or `used_by` list sits beside a `*_basis` object: the language, how many call edges the index resolved for it, the share of those that are guesses, and a note that unbound call sites are not counted, so an empty list means no resolved edge, not proof of none |
| `compact` | boolean | No | Default `true`. Set `false` for full structure block and importer list. |
| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` |
@@ -351,6 +351,7 @@ get_context(targets=["src/auth/middleware.ts"])
get_context(targets=["middleware", "api/routes", "payments"], include=["callers", "metrics"])
get_context(targets=["src/auth"], compact=false, include=["community"])
get_context(targets=["src/big_module.py"], include=["skeleton"])
+get_context(targets=["src/auth/service.py"], include=["doc_drift"])
```
**Skeletons:** with `include=["skeleton"]`, file targets gain a structure-level
@@ -361,6 +362,26 @@ ranked by graph centrality / hotspot / query match. Elision markers carry
structure-level questions ("what's in this file", "which function handles X")
this replaces a full file read at a fraction of the cost.
+**Documentation drift, in reverse:** with `include=["doc_drift"]`, a file target
+gains the documents that name it. The drift detector files a finding against the
+*document*, so this is the only direction that answers "what documentation would
+my change invalidate". Two separate claims ride in the block and must not be
+merged: `references` lists documents that name this file and still resolve to
+it, while `documents_with_drift` says a listed document carries some assertion
+that no longer holds --- anywhere in it, not necessarily about this file.
+`references_basis` states both limits, and is emitted on an empty answer too,
+since a reference the detector cannot resolve is not listed. Documents dropped
+by the repo's exclude rules are counted in `references_excluded` rather than
+silently missing.
+
+An answer the store cannot support is a refusal, not an empty list, because "no
+document mentions this file" is a far stronger claim than "no drift findings".
+`{"unavailable": "not_computed"}` means the table exists but the pass has never
+run, which happens between an upgrade and the first update that does any work;
+`"index_predates_doc_drift"` means the index is older than the table; and
+`"drift_read_failed"` means the read failed for some other reason, where
+reindexing is not the fix.
+
---
## `get_symbol`
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 365b9fbee..bde152f1f 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -578,7 +578,7 @@ call.
| Flag | Description |
|------|-------------|
-| `--include` | Opt-in block, repeatable: `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `skeleton` |
+| `--include` | Opt-in block, repeatable: `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `health`, `skeleton`, `doc_drift` |
| `--no-compact` | Add structure, imports and docstrings to each card |
```bash
diff --git a/packages/cli/src/repowise/cli/commands/context_cmd.py b/packages/cli/src/repowise/cli/commands/context_cmd.py
index e5ca151b6..58d458a68 100644
--- a/packages/cli/src/repowise/cli/commands/context_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/context_cmd.py
@@ -19,12 +19,13 @@ _INCLUDE_BLOCKS = (
"decisions",
"health",
"skeleton",
+ "doc_drift",
)
#: Card keys the projection replaces or drops. Everything else passes through.
#:
-#: A denylist, not an allowlist. Most of what a card carries is opt-in: nine
-#: ``--include`` blocks, each landing under its own key, and an allowlist that
+#: A denylist, not an allowlist. Most of what a card carries is opt-in: every
+#: ``--include`` block lands under its own key, and an allowlist that
#: misses one turns ``--include ownership`` into a flag that changes nothing
#: the caller can see. The failure mode of a denylist is a payload slightly
#: larger than intended; the failure mode of an allowlist is a silently
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index 14bb13a61..5d9d50c62 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -1129,15 +1129,15 @@ async def _persist_full_update_async(
_skip("Dead-code persist", exc)
# Scoped to the documents the pass actually read, so one this run
- # could not open keeps its findings.
+ # could not open keeps its rows in both drift tables.
if doc_drift_report is not None:
try:
from repowise.core.persistence.crud import (
- replace_doc_drift_findings_guarded,
+ replace_doc_drift_guarded,
)
with timed(timings, "persist.doc_drift"):
- await replace_doc_drift_findings_guarded(
+ await replace_doc_drift_guarded(
session, repo_id, doc_drift_report
)
except Exception as exc:
diff --git a/packages/core/alembic/versions/0066_doc_drift_references.py b/packages/core/alembic/versions/0066_doc_drift_references.py
new file mode 100644
index 000000000..1156d74f0
--- /dev/null
+++ b/packages/core/alembic/versions/0066_doc_drift_references.py
@@ -0,0 +1,81 @@
+"""Add doc_drift_references table.
+
+Stores the complement of ``doc_drift_findings``: the references that resolved.
+A row says ``document_path`` names ``target_path`` and the repository still has
+it, which is what answers "which documents mention this file" without
+re-running the pass in a process that holds no ``source_map``.
+
+Two indexes, one per direction, on the ``test_coverage`` pattern. The target
+index is the hot one, because the question is asked about a code file --- the
+direction ``ix_doc_drift_repo_path`` does not have. The document index serves
+the scoped rewrite and the deletion prune.
+
+The unique constraint over
+``(repository_id, document_path, kind, line_number, target_path)`` is what
+makes re-running the pass converge instead of accumulating duplicates, and
+carries ``target_path`` for the same reason the findings key carries
+``target``: one line can hold two references.
+
+Local SQLite stores never run Alembic --- ``init_db``'s reconciler calls
+``Base.metadata.create_all`` --- so this migration exists for managed
+Postgres.
+
+Revision ID: 0066
+Revises: 0065
+Create Date: 2026-09-17
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0066"
+down_revision: str | None = "0065"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ op.create_table(
+ "doc_drift_references",
+ sa.Column("id", sa.Integer, primary_key=True, autoincrement=True),
+ sa.Column(
+ "repository_id",
+ sa.String(32),
+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("document_path", sa.String(1024), nullable=False),
+ sa.Column("target_path", sa.String(1024), nullable=False),
+ sa.Column("kind", sa.String(32), nullable=False),
+ sa.Column("line_number", sa.Integer, nullable=False),
+ sa.Column("section", sa.Text, nullable=False, server_default=""),
+ sa.UniqueConstraint(
+ "repository_id",
+ "document_path",
+ "kind",
+ "line_number",
+ "target_path",
+ name="uq_doc_drift_reference_site",
+ ),
+ )
+ op.create_index(
+ "ix_doc_drift_ref_repo_target",
+ "doc_drift_references",
+ ["repository_id", "target_path"],
+ )
+ op.create_index(
+ "ix_doc_drift_ref_repo_doc",
+ "doc_drift_references",
+ ["repository_id", "document_path"],
+ )
+
+
+def downgrade() -> None:
+ op.drop_index("ix_doc_drift_ref_repo_doc", table_name="doc_drift_references")
+ op.drop_index("ix_doc_drift_ref_repo_target", table_name="doc_drift_references")
+ op.drop_table("doc_drift_references")
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/__init__.py b/packages/core/src/repowise/core/analysis/doc_drift/__init__.py
index db1ff4cb4..316296150 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/__init__.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/__init__.py
@@ -15,6 +15,7 @@ from .models import (
DocReference,
DriftKind,
DriftVerdict,
+ ResolvedDocReference,
)
__all__ = [
@@ -24,5 +25,6 @@ __all__ = [
"DocReference",
"DriftKind",
"DriftVerdict",
+ "ResolvedDocReference",
"summarize_confidence",
]
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/analyzer.py b/packages/core/src/repowise/core/analysis/doc_drift/analyzer.py
index f6e843f45..81597ea63 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/analyzer.py
@@ -27,6 +27,7 @@ from .models import (
DocDriftReport,
DriftKind,
DriftVerdict,
+ ResolvedDocReference,
)
from .resolver import RepoIndex, resolve
@@ -140,6 +141,7 @@ class DocDriftAnalyzer:
on_step("index")
findings: list[DocDriftFindingData] = []
+ resolved: list[ResolvedDocReference] = []
verdict_counts: dict[str, int] = {v.value: 0 for v in DriftVerdict}
references_checked = 0
@@ -153,6 +155,14 @@ class DocDriftAnalyzer:
verdict_counts[res.verdict.value] += 1
if res.verdict is DriftVerdict.MISSING:
findings.append(_to_finding(res))
+ elif res.resolved_target and res.resolved_target != rel:
+ # Retention, not recomputation. Only a resolution naming
+ # a real file sets ``resolved_target``, so an ambiguous or
+ # uncheckable reference cannot land here as a fact. A
+ # document naming itself is dropped: a table of contents
+ # answers the reverse question with the file the reader is
+ # already in.
+ resolved.append(_to_resolved(res))
if on_step:
on_step("resolve")
@@ -181,9 +191,21 @@ class DocDriftAnalyzer:
anchor_renderer=index.renderers.summary(),
hidden_below_threshold=hidden,
documents=frozenset(documents),
+ resolved_references=resolved,
)
+def _to_resolved(res: Any) -> ResolvedDocReference:
+ ref = res.ref
+ return ResolvedDocReference(
+ doc_path=ref.doc_path,
+ target_path=res.resolved_target,
+ kind=ref.kind,
+ line=ref.line,
+ section=ref.section,
+ )
+
+
def _to_finding(res: Any) -> DocDriftFindingData:
ref = res.ref
target, _, fragment = ref.target.partition("#")
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 deb4dd146..87929c328 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/constants.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/constants.py
@@ -71,6 +71,30 @@ DETECTION_BASIS: str = (
)
+#: :data:`DETECTION_BASIS`'s job for the reverse view, which makes a weaker
+#: claim: a row says a document names a file that exists, not that it explains
+#: it. Separate sentences, because the finding one applied to a reference count
+#: describes a number nobody took.
+REFERENCE_BASIS: str = (
+ "Lists documents that name this file and still resolve to it. It does not "
+ "claim they describe it, or that their prose is current. References this "
+ "detector cannot resolve are not listed, so absence is not proof that no "
+ "document mentions the file. A document reported as carrying drift has "
+ "some assertion that no longer holds, which need not be about this file."
+)
+
+
+#: Why a drift surface could not answer. Shared because a client keys on these
+#: strings, and a literal in two packages is how one gets renamed alone.
+#: ``NO_TABLE`` is an index older than the table; ``NOT_COMPUTED`` is a table
+#: that exists and was never filled, which must not render as a clean tree;
+#: ``READ_FAILED`` is anything else, since "your index is old" is wrong advice
+#: for a transient failure.
+UNAVAILABLE_NO_TABLE: str = "index_predates_doc_drift"
+UNAVAILABLE_NOT_COMPUTED: str = "not_computed"
+UNAVAILABLE_READ_FAILED: str = "drift_read_failed"
+
+
#: Default ``--min-confidence`` cutoff. Matches the lowest shipping origin's
#: tier so nothing is hidden by default; a caller that wants only the
#: near-certain findings raises it to ``HIGH_CONFIDENCE_THRESHOLD``.
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/models.py b/packages/core/src/repowise/core/analysis/doc_drift/models.py
index 845261e94..709ca4ecc 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/models.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/models.py
@@ -104,6 +104,32 @@ class DocDriftFindingData:
context: str = ""
+@dataclass(frozen=True)
+class ResolvedDocReference:
+ """One reference that resolved: a document names this file, correctly.
+
+ The complement of :class:`DocDriftFindingData`, and a deliberately weaker
+ claim than that one. A finding says a document is wrong; this says only
+ that a document names a file the repository still has. Whether the prose
+ around the name still *describes* the file is not something this detector
+ can see, so no surface built on these rows may say "describes".
+
+ Only ``RESOLVED`` references that name a concrete repository file become
+ one of these. ``AMBIGUOUS`` is excluded because a basename match is not a
+ resolution, and ``COMMAND`` because a make target is not a file.
+ """
+
+ doc_path: str
+ """Repo-relative POSIX path of the document making the reference."""
+ target_path: str
+ """Repo-relative POSIX path of the file it resolved to."""
+ kind: DriftKind
+ line: int
+ """1-indexed line within the document."""
+ section: str = ""
+ """The enclosing heading trail, so a reader can find the passage."""
+
+
@dataclass
class DocDriftReport:
"""The drift pass's output for one repository."""
@@ -130,6 +156,11 @@ class DocDriftReport:
the count. A document that missed ``source_map`` (transient read failure, or
markdown over :data:`~.constants.MAX_DOC_BYTES`) is absent, which is what
stops a scoped write from deleting findings it never recomputed."""
+ resolved_references: list[ResolvedDocReference] = field(default_factory=list)
+ """Every reference that resolved to a real file, for the reverse view
+ ("which documents mention this file"). Retained rather than recomputed,
+ because the resolver already had each one. Scoped by
+ ``authoritative_paths`` exactly as findings are."""
authoritative_paths: frozenset[str] | None = field(default=None)
"""Document paths this report may speak for; ``None`` means all of them.
Mirrors dead code's field of the same name so an incremental re-check can
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/resolver.py b/packages/core/src/repowise/core/analysis/doc_drift/resolver.py
index e2f28a543..339752fa5 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/resolver.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/resolver.py
@@ -50,6 +50,12 @@ class Resolution:
origin: str = ""
"""Set only on ``MISSING``; names the strategy that concluded it, which is
what carries the confidence."""
+ resolved_target: str = ""
+ """Set only on ``RESOLVED``, and only when the reference names a concrete
+ repository file: the path it resolved to. Not the same as ``ref.target``,
+ which is what the document wrote --- a link joined relative to its own
+ document resolves elsewhere. The reverse view needs the resolved path, and
+ this is where it was already computed."""
@property
def confidence(self) -> float:
@@ -226,11 +232,11 @@ def _exists(idx: RepoIndex, target: str) -> bool:
def _resolve_path(idx: RepoIndex, ref: DocReference, is_guide: bool) -> Resolution:
target = ref.target
if _exists(idx, target):
- return Resolution(ref, DriftVerdict.RESOLVED, "exact")
+ return Resolution(ref, DriftVerdict.RESOLVED, "exact", resolved_target=target)
relative = _join_relative(ref.doc_path, target)
if relative != target and _exists(idx, relative):
- return Resolution(ref, DriftVerdict.RESOLVED, "relative-to-doc")
+ return Resolution(ref, DriftVerdict.RESOLVED, "relative-to-doc", resolved_target=relative)
# Anchoring. A reference is evidence about THIS repository only when it
# carries a separator and its first segment names a directory the
@@ -294,7 +300,7 @@ def _resolve_anchor(idx: RepoIndex, ref: DocReference) -> Resolution:
if target not in idx._doc_text:
return Resolution(ref, DriftVerdict.UNCHECKABLE, "host-doc-unread")
if github_slug(frag) in idx.doc_anchors(target):
- return Resolution(ref, DriftVerdict.RESOLVED, "heading")
+ return Resolution(ref, DriftVerdict.RESOLVED, "heading", resolved_target=target)
return Resolution(ref, DriftVerdict.MISSING, "no-heading", "anchor_no_heading")
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 58c3090cf..a22e0b1d8 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -38,9 +38,13 @@ from .dead_code import (
update_dead_code_status,
)
from .doc_drift import (
+ doc_drift_references_stored,
get_doc_drift_findings,
+ get_doc_drift_references,
replace_doc_drift_findings,
- replace_doc_drift_findings_guarded,
+ replace_doc_drift_guarded,
+ replace_doc_drift_references,
+ serialize_doc_drift_reference_row,
serialize_doc_drift_row,
summarize_confidence_rows,
)
@@ -112,6 +116,7 @@ __all__ = [
"backfill_module_attribution",
"count_refactoring_suggestions",
"covered_source_files",
+ "doc_drift_references_stored",
"files_covered_by",
"finalize_performance_opportunities",
"finalize_refactoring_opportunities",
@@ -122,6 +127,7 @@ __all__ = [
"get_dead_code_summary",
"get_deduction_by_path",
"get_doc_drift_findings",
+ "get_doc_drift_references",
"get_file_language_map",
"get_health_finding_by_public_id",
"get_health_findings",
@@ -152,7 +158,8 @@ __all__ = [
"refactoring_facet_counts",
"replace_dead_code_findings",
"replace_doc_drift_findings",
- "replace_doc_drift_findings_guarded",
+ "replace_doc_drift_guarded",
+ "replace_doc_drift_references",
"replace_governance_findings",
"save_coverage_files",
"save_dead_code_findings",
@@ -161,6 +168,7 @@ __all__ = [
"save_health_snapshot",
"save_refactoring_suggestions",
"save_test_coverage",
+ "serialize_doc_drift_reference_row",
"serialize_doc_drift_row",
"sort_metrics_worst_first",
"summarize_confidence_rows",
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 913eba777..0a33710b8 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
@@ -1,8 +1,10 @@
-"""CRUD operations for documentation drift findings."""
+"""CRUD operations for documentation drift: findings and references."""
from __future__ import annotations
import json
+from collections.abc import Callable, Sequence
+from dataclasses import dataclass
from typing import Any
from sqlalchemy import delete, select
@@ -10,7 +12,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.doc_drift.constants import bucket_confidences
-from ...models import DocDriftFinding
+from ...models import DocDriftFinding, DocDriftReference
from .._shared import _BATCH_SIZE
#: Width of the two ``String(1024)`` columns. ``target`` is lifted verbatim
@@ -28,6 +30,101 @@ _PATH_COLUMN_WIDTH = 1024
_IN_CLAUSE_CHUNK = 400
+@dataclass(frozen=True)
+class _DriftTable:
+ """Everything that differs between the two drift tables, in one place.
+
+ Declared side by side below so the two stay legible as variants of one
+ write rather than as two functions that happen to look alike.
+ """
+
+ model: Any
+ """The ORM model rows are written to."""
+ path_column: Any
+ """Its document-path column, which the scoped delete narrows on."""
+ path_of: Callable[[Any], str]
+ """The document path of an analyzer item, for the scope check."""
+ row_kwargs: Callable[[Any, str], dict]
+ """One analyzer item as ORM row kwargs."""
+ key_fields: tuple[str, ...]
+ """The table's unique-constraint columns, for the in-batch dedup."""
+
+
+_FINDINGS_TABLE = _DriftTable(
+ model=DocDriftFinding,
+ path_column=DocDriftFinding.file_path,
+ path_of=lambda f: f.file_path,
+ row_kwargs=lambda f, repo_id: _row_kwargs(f, repo_id),
+ key_fields=("file_path", "kind", "line_number", "target"),
+)
+
+_REFERENCES_TABLE = _DriftTable(
+ model=DocDriftReference,
+ path_column=DocDriftReference.document_path,
+ path_of=lambda r: r.doc_path,
+ row_kwargs=lambda r, repo_id: _reference_row_kwargs(r, repo_id),
+ key_fields=("document_path", "kind", "line_number", "target_path"),
+)
+
+
+async def _replace_scoped(
+ session: AsyncSession,
+ table: _DriftTable,
+ repository_id: str,
+ items: list[Any],
+ *,
+ scoped: frozenset[str] | None,
+) -> int:
+ """Delete-then-insert one drift table, converging on re-run.
+
+ Shared by both so their scoping cannot drift apart: the two writes must
+ speak for the same set of documents, or one describes a run the other
+ never made.
+
+ ``scoped`` names the document paths this write may speak for; ``None``
+ means repo-wide. Idempotency rests on the unique constraint, and on the
+ DELETE and INSERT scopes being identical so no surviving row can collide.
+ The dedup closes the last gap: two items in one batch sharing a site,
+ which would otherwise raise after the DELETE had run.
+ """
+ model = table.model
+ if scoped is None:
+ await session.execute(delete(model).where(model.repository_id == repository_id))
+ else:
+ # Chunked so a large scope stays under SQLite's parameter limit.
+ paths = sorted(scoped)
+ for i in range(0, len(paths), _IN_CLAUSE_CHUNK):
+ chunk = paths[i : i + _IN_CLAUSE_CHUNK]
+ await session.execute(
+ delete(model).where(
+ model.repository_id == repository_id,
+ table.path_column.in_(chunk),
+ )
+ )
+
+ rows: list[dict] = []
+ seen: set[tuple] = set()
+ for item in items or []:
+ if scoped is not None and table.path_of(item) not in scoped:
+ # Outside the scope it would be inserted and never deleted by the
+ # next scoped run, so it would outlive its own evidence.
+ continue
+ kwargs = table.row_kwargs(item, repository_id)
+ # Keyed on the truncated values, so two targets differing only past the
+ # column width collapse here rather than colliding in the database.
+ key = tuple(kwargs[field] for field in table.key_fields)
+ if key in seen:
+ continue
+ seen.add(key)
+ rows.append(kwargs)
+
+ for i in range(0, len(rows), _BATCH_SIZE):
+ session.add_all(model(**r) for r in rows[i : i + _BATCH_SIZE])
+ await session.flush()
+
+ return len(rows)
+
+
def _row_kwargs(finding: Any, repository_id: str) -> dict:
"""Normalize a ``DocDriftFindingData`` into ORM row kwargs."""
kind = finding.kind
@@ -62,83 +159,83 @@ async def replace_doc_drift_findings(
repo-wide and every row is replaceable.
Returns the number of rows inserted.
-
- Idempotency rests on two things. The unique constraint
- ``uq_doc_drift_finding_site`` is the durable one. The other is that the
- DELETE scope and the INSERT scope are identical --- every row inserted
- belongs to a path just deleted --- so no surviving row can collide. The
- Python-side dedup below closes the remaining gap, which is two findings in
- the *same batch* sharing a site; without it that batch would raise after
- the DELETE had already run. ``security_scan.replace_findings`` guards the
- same hazard the same way, and additionally uses a conflict-tolerant
- INSERT because it has a second writer (the history scan) that this table
- does not.
"""
- scoped = frozenset(scope) if scope is not None else None
+ return await _replace_scoped(
+ session,
+ _FINDINGS_TABLE,
+ repository_id,
+ findings,
+ scoped=frozenset(scope) if scope is not None else None,
+ )
- if scoped is None:
- await session.execute(
- delete(DocDriftFinding).where(DocDriftFinding.repository_id == repository_id)
- )
- else:
- # Chunked so a large scope stays under SQLite's parameter limit.
- paths = sorted(scoped)
- for i in range(0, len(paths), _IN_CLAUSE_CHUNK):
- chunk = paths[i : i + _IN_CLAUSE_CHUNK]
- await session.execute(
- delete(DocDriftFinding).where(
- DocDriftFinding.repository_id == repository_id,
- DocDriftFinding.file_path.in_(chunk),
- )
- )
- rows: list[dict] = []
- seen: set[tuple] = set()
- for finding in findings or []:
- if scoped is not None and finding.file_path not in scoped:
- # A finding outside the scope would be inserted and never deleted
- # by the next scoped run, so it would outlive its own evidence.
- continue
- kwargs = _row_kwargs(finding, repository_id)
- key = (
- kwargs["file_path"],
- kwargs["kind"],
- kwargs["line_number"],
- kwargs["target"],
- )
- if key in seen:
- continue
- seen.add(key)
- rows.append(kwargs)
+def _reference_row_kwargs(reference: Any, repository_id: str) -> dict:
+ """Normalize a ``ResolvedDocReference`` into ORM row kwargs."""
+ kind = reference.kind
+ return {
+ "repository_id": repository_id,
+ "document_path": reference.doc_path[:_PATH_COLUMN_WIDTH],
+ "target_path": reference.target_path[:_PATH_COLUMN_WIDTH],
+ "kind": str(kind.value) if hasattr(kind, "value") else str(kind),
+ "line_number": int(reference.line),
+ "section": reference.section or "",
+ }
- for i in range(0, len(rows), _BATCH_SIZE):
- session.add_all(DocDriftFinding(**r) for r in rows[i : i + _BATCH_SIZE])
- await session.flush()
- return len(rows)
+async def replace_doc_drift_references(
+ session: AsyncSession,
+ repository_id: str,
+ references: list[Any],
+ *,
+ scope: frozenset[str] | set[str] | None = None,
+) -> int:
+ """Replace this repository's resolved references, converging on re-run.
+
+ The same contract as :func:`replace_doc_drift_findings`, over the same
+ ``scope`` of document paths. Returns the number of rows inserted.
+ """
+ return await _replace_scoped(
+ session,
+ _REFERENCES_TABLE,
+ repository_id,
+ references,
+ scoped=frozenset(scope) if scope is not None else None,
+ )
-async def replace_doc_drift_findings_guarded(
+async def replace_doc_drift_guarded(
session: AsyncSession,
repository_id: str,
report: Any,
) -> int:
- """:func:`replace_doc_drift_findings` inside a savepoint, from a *report*.
-
- Every caller reports failure as a warning rather than raising, and this is a
- DELETE followed by an INSERT. Without the savepoint a failing insert leaves
- the DELETE buffered in the caller's live transaction, which then commits it:
- every drift row for the repository wiped, reported only as a warning. On
- Postgres the same failure poisons the transaction and takes the other
- analyses down with it.
+ """Write both drift tables from a *report*, inside one savepoint.
+
+ One writer, because the two are complements of a single pass: written
+ separately they could describe different runs, and a reverse view built on
+ references from one and findings from another is the false "your
+ documentation is wrong" this detector exists to avoid.
+
+ Callers report failure as a warning rather than raising, so without the
+ savepoint a failing insert leaves the DELETE buffered in their live
+ transaction, which then commits it: every drift row wiped, reported as one
+ warning. On Postgres it also poisons the transaction.
+
+ Returns the number of findings inserted.
"""
async with session.begin_nested():
- return await replace_doc_drift_findings(
+ written = await replace_doc_drift_findings(
session,
repository_id,
report.findings,
scope=report.authoritative_paths,
)
+ await replace_doc_drift_references(
+ session,
+ repository_id,
+ report.resolved_references,
+ scope=report.authoritative_paths,
+ )
+ return written
async def get_doc_drift_findings(
@@ -162,6 +259,88 @@ async def get_doc_drift_findings(
return list((await session.execute(stmt)).scalars().all())
+async def get_doc_drift_references(
+ session: AsyncSession,
+ repository_id: str,
+ *,
+ target_paths: Sequence[str] | None = None,
+) -> list[DocDriftReference]:
+ """Read resolved references back, document order then line order.
+
+ *target_paths* is the reverse question this table exists for, and it rides
+ the target index. Plural because one query over the caller's whole batch
+ beats one per target on a session they share. ``kind`` breaks the tie a
+ markdown link with a fragment creates, which would otherwise be ordered by
+ whatever the backend picks.
+ """
+ stmt = select(DocDriftReference).where(
+ DocDriftReference.repository_id == repository_id
+ )
+ if target_paths is not None:
+ paths = sorted(set(target_paths))
+ if not paths:
+ return []
+ if len(paths) <= _IN_CLAUSE_CHUNK:
+ stmt = stmt.where(DocDriftReference.target_path.in_(paths))
+ else:
+ # Chunked so a large batch stays under SQLite's parameter limit.
+ rows: list[DocDriftReference] = []
+ for i in range(0, len(paths), _IN_CLAUSE_CHUNK):
+ rows.extend(
+ await get_doc_drift_references(
+ session,
+ repository_id,
+ target_paths=paths[i : i + _IN_CLAUSE_CHUNK],
+ )
+ )
+ return rows
+ stmt = stmt.order_by(
+ DocDriftReference.document_path,
+ DocDriftReference.line_number,
+ DocDriftReference.kind,
+ )
+ return list((await session.execute(stmt)).scalars().all())
+
+
+async def doc_drift_references_stored(session: AsyncSession, repository_id: str) -> bool:
+ """Whether this repository has any stored reference at all.
+
+ What stops an empty answer being read as a clean one. The reconciler
+ creates the table, but the pass only runs when an update has work to do,
+ so "upgraded, never analysed" is a real state that looks exactly like "no
+ document mentions this file".
+
+ A repository with resolvable documentation has thousands of these rows, so
+ their absence means the pass has not run. One whose documents resolve to
+ nothing reads as unavailable rather than empty: an understatement, never a
+ false clean, which is the direction this must fail in.
+ """
+ stmt = select(DocDriftReference.id).where(
+ DocDriftReference.repository_id == repository_id
+ )
+ return (await session.execute(stmt.limit(1))).scalar_one_or_none() is not None
+
+
+def serialize_doc_drift_reference_row(row: DocDriftReference) -> dict:
+ """One stored reference as a dict, for any surface that serves it.
+
+ One function rather than one per surface, for the reason
+ :func:`serialize_doc_drift_row` gives. ``target_path`` is absent because
+ every row in a reverse answer shares it. The keys are ``document``/``line``
+ rather than the findings serializer's ``file_path``/``line_number``: here a
+ bare ``file_path`` would read as the file that was asked about, which is
+ the one thing it is not.
+ """
+ out = {
+ "document": row.document_path,
+ "line": row.line_number,
+ "kind": row.kind,
+ }
+ if row.section:
+ out["section"] = row.section
+ return out
+
+
def _decode_evidence(raw: str) -> list[str]:
"""The stored evidence lines, degrading to none rather than raising.
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index b289c5e5e..757b59646 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -1383,6 +1383,59 @@ class DeadCodeFinding(Base):
__table_args__ = (Index("ix_dead_code_repo_path", "repository_id", "file_path"),)
+class DocDriftReference(Base):
+ """One resolved ``(document, file)`` reference - the reverse index.
+
+ Where :class:`DocDriftFinding` stores what a document got *wrong*, this
+ stores what it got right: ``document_path`` names ``target_path`` and the
+ repository still has it. Complements, not two views of one thing: a
+ drifted reference resolves to nothing, so it can never appear here, and no
+ surface may read one as evidence against the other.
+
+ A table, not a graph edge, for :class:`TestCoverageEntry`'s reason - the
+ consumer is a straight lookup keyed by file path. It is stored at all
+ because the process answering "which documents mention this file" holds no
+ ``source_map``: 0.7 ms to serve, 243 ms to re-run the pass, 1,562 ms on a
+ document-heavy tree.
+
+ ``ix_doc_drift_ref_repo_target`` is the hot index, the direction the
+ findings table lacks; the document index serves the scoped rewrite and the
+ prune. Rows are replaced per run under the same ``authoritative_paths`` as
+ findings, so a document a run could not read keeps its rows.
+ """
+
+ __tablename__ = "doc_drift_references"
+ __table_args__ = (
+ UniqueConstraint(
+ "repository_id",
+ "document_path",
+ "kind",
+ "line_number",
+ "target_path",
+ name="uq_doc_drift_reference_site",
+ ),
+ # Reverse index (file -> documents naming it) is the hot path.
+ Index("ix_doc_drift_ref_repo_target", "repository_id", "target_path"),
+ # Forward index (document -> what it names), for the scoped rewrite.
+ Index("ix_doc_drift_ref_repo_doc", "repository_id", "document_path"),
+ )
+
+ id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
+ repository_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
+ )
+ #: The document making the reference, which is the file a reader edits.
+ document_path: Mapped[str] = mapped_column(String(1024), nullable=False)
+ #: The file it resolved to. Not what the document wrote: a relative link
+ #: resolves against its own directory.
+ target_path: Mapped[str] = mapped_column(String(1024), nullable=False)
+ kind: Mapped[str] = mapped_column(String(32), nullable=False)
+ line_number: Mapped[int] = mapped_column(Integer, nullable=False)
+ #: The enclosing heading trail, carried because the reverse view shows it:
+ #: it is how a reader finds the passage rather than just the file.
+ section: Mapped[str] = mapped_column(Text, nullable=False, default="")
+
+
class DocDriftFinding(Base):
"""An assertion a document makes that the repository no longer satisfies.
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index c41dd1e71..e9effdc95 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -1938,11 +1938,11 @@ async def persist_incremental_index(
if doc_drift_report is not None:
try:
from repowise.core.persistence.crud import (
- replace_doc_drift_findings_guarded,
+ replace_doc_drift_guarded,
)
with timed(timings, "persist.doc_drift"):
- await replace_doc_drift_findings_guarded(
+ await replace_doc_drift_guarded(
session, repo_id, doc_drift_report
)
except Exception as exc:
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index d6f545f04..fa2704935 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -1069,6 +1069,7 @@ async def prune_deleted_file_rows(
from repowise.core.persistence.models import (
DeadCodeFinding,
DocDriftFinding,
+ DocDriftReference,
GitMetadata,
GraphEdge,
GraphMetric,
@@ -1170,6 +1171,12 @@ async def prune_deleted_file_rows(
# function, so drift rows for a document deleted there wait for a reindex,
# as dead-code and health rows already do.
await _prune_table(DocDriftFinding, DocDriftFinding.file_path, "doc_drift_findings")
+ # On the document only. A reference to a deleted *target* is drift, not a
+ # dead row: the next pass re-resolves it into a finding, and pruning by
+ # target here would delete the evidence before anything reported it.
+ await _prune_table(
+ DocDriftReference, DocDriftReference.document_path, "doc_drift_references"
+ )
await _prune_table(HealthFileMetric, HealthFileMetric.file_path, "health_file_metrics")
await _prune_table(HealthFinding, HealthFinding.file_path, "health_findings")
# git_metadata is keyed off the git indexer on a full run, but an
@@ -1916,7 +1923,7 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
from repowise.core.persistence.crud import (
bulk_upsert_decisions,
recompute_decision_staleness,
- replace_doc_drift_findings_guarded,
+ replace_doc_drift_guarded,
save_coverage_files,
save_dead_code_findings,
upsert_git_function_blame_bulk,
@@ -1926,16 +1933,17 @@ async def persist_analysis(result: Any, session: Any, repo_id: str) -> None:
if result.dead_code_report and result.dead_code_report.findings:
await save_dead_code_findings(session, repo_id, result.dead_code_report.findings)
- # ---- Documentation drift findings ---------------------------------------
- # Written even when the finding list is empty, unlike dead code above: a
- # run that fixed the last drifted reference must clear the rows, and a
- # guard on ``.findings`` would leave the old ones standing as though the
- # documents were still wrong. ``authoritative_paths`` is None on a full
- # run, so the replace is repo-wide.
+ # ---- Documentation drift: findings and resolved references --------------
+ # Both tables, one savepoint, one run. Written even when the finding list
+ # is empty, unlike dead code above: a run that fixed the last drifted
+ # reference must clear the rows, and a guard on ``.findings`` would leave
+ # the old ones standing as though the documents were still wrong.
+ # ``authoritative_paths`` is None on a full run, so the replace is
+ # repo-wide.
drift = getattr(result, "doc_drift_report", None)
if drift is not None:
try:
- await replace_doc_drift_findings_guarded(session, repo_id, drift)
+ await replace_doc_drift_guarded(session, repo_id, drift)
except Exception as exc:
logger.warning("doc_drift_persist_skipped", error=str(exc))
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 1ee8c5044..c2b7b7155 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -682,6 +682,25 @@ def is_excluded(path: str | None, spec: Any) -> bool:
return _core_is_excluded(path, spec)
+def is_missing_table(exc: Exception) -> bool:
+ """Whether *exc* is "that table is not there" rather than a real failure.
+
+ Backend-specific wording, so this is a substring check and not a code. It
+ fails toward ``unavailable``: mistaking a missing table for a failure costs
+ a visible block that should have been silent, while the reverse would let a
+ genuine failure render as a clean bill.
+
+ Every clause is table-scoped for that reason. Postgres says "does not
+ exist" for a missing column, database, function or role too, and each of
+ those is real schema drift or misconfiguration -- swallowing them here
+ would rebuild the exact silence this block exists to break.
+ """
+ text = str(getattr(exc, "orig", "") or exc).lower()
+ if "no such table" in text or "undefined table" in text:
+ return True
+ return "does not exist" in text and ("relation" in text or "table" in text)
+
+
def filter_rows_by_attr(rows: list, attr: str, spec: Any) -> list:
"""Shape A: drop ORM rows whose ``attr`` path is excluded."""
if not spec:
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 2a2138ec4..5f1a2d647 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -53,6 +53,7 @@ from repowise.server.mcp_server._helpers import (
_resolve_repo_context,
_unsupported_repo_all,
attach_ignored_arguments,
+ is_missing_table,
resolve_enum_argument,
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
@@ -875,7 +876,7 @@ async def _read_prior_fixes(ctx: Any, changed: dict[str, set[int]]) -> PriorFixI
# An index built before fix events existed has no table to read. That is
# silence, not an error the caller should have to handle -- but a locked
# or unreadable database is a real failure and falls through below.
- if _is_missing_table(exc):
+ if is_missing_table(exc):
return unsupported_prior_fixes("this index predates the bug-fix record")
return unavailable_prior_fixes(_read_failure(exc))
except SQLAlchemyError as exc:
@@ -906,25 +907,6 @@ def _read_failure(exc: SQLAlchemyError) -> str:
return f"the fix record could not be read ({type(exc).__name__})"
-def _is_missing_table(exc: OperationalError) -> bool:
- """Whether *exc* is "that table is not there" rather than a real failure.
-
- Backend-specific wording, so this is a substring check and not a code. It
- fails toward ``unavailable``: mistaking a missing table for a failure costs
- a visible block that should have been silent, while the reverse would let a
- genuine failure render as a clean bill.
-
- Every clause is table-scoped for that reason. Postgres says "does not
- exist" for a missing column, database, function or role too, and each of
- those is real schema drift or misconfiguration -- swallowing them here
- would rebuild the exact silence this block exists to break.
- """
- text = str(getattr(exc, "orig", "") or exc).lower()
- if "no such table" in text or "undefined table" in text:
- return True
- return "does not exist" in text and ("relation" in text or "table" in text)
-
-
async def _independent_changes_block(
ctx: Any,
changed: dict[str, set[int]],
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
index 196b20401..d00c5c6f7 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py
@@ -20,6 +20,7 @@ Optional ``include`` parameter widens the response:
- include=["decisions"] → full decision records (default returns titles only)
- include=["skeleton"] → body-elided file rendering (signatures + top-PageRank bodies)
- include=["health"] → code-health scores and biomarkers for the target
+ - include=["doc_drift"] → documents that name this file, and their drift
An unrecognised key is dropped and named in ``ignored_arguments`` rather than
silently ignored: an unknown key otherwise produces exactly the response the
@@ -52,6 +53,7 @@ from repowise.server.mcp_server._helpers import (
from repowise.server.mcp_server._meta import build_meta as _build_meta
from repowise.server.mcp_server._meta import completeness_line as _completeness_line
from repowise.server.mcp_server._meta import context_hint as _context_hint
+from repowise.server.mcp_server.tool_context.enrichment import attach_doc_references
from repowise.server.mcp_server.tool_context.targets import _resolve_one_target
_log = logging.getLogger("repowise.mcp.context")
@@ -75,6 +77,7 @@ _INCLUDE_BLOCKS = frozenset(
"decisions",
"skeleton",
"health",
+ "doc_drift",
}
)
@@ -139,7 +142,8 @@ async def get_context(
Args:
targets: file paths, module paths, or "path::Symbol" ids.
include: opt-in blocks: full_doc | ownership | last_change | callers
- | callees | metrics | community | decisions | skeleton | health.
+ | callees | metrics | community | decisions | skeleton | health
+ | doc_drift (documents naming this file).
An unrecognised key is named in ignored_arguments.
compact: default True; False adds structure+imports+docstrings.
repo: usually omitted.
@@ -198,6 +202,19 @@ async def get_context(
return_exceptions=True,
)
+ # One batched read for every target that asked for it, on the session
+ # they share, and a no-op for every call that did not. Deliberately
+ # not per-target inside the gather above: savepoints opened
+ # concurrently on one session close each other, and
+ # ``attach_doc_references`` carries the account of that.
+ await attach_doc_references(
+ session,
+ repository,
+ {r["target"]: r for r in raw_results if isinstance(r, dict)},
+ exclude_spec=exclude_spec,
+ collector=collector,
+ )
+
# repo="all" already returned above, so ctx here is always one repo.
# Computed on the open session: never open a second one for this.
scope_hint = await _scope_hint(session, repository, raw_results)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index ea0848733..5825535c8 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
@@ -9,26 +9,38 @@ dispatch rather than one long body.
from __future__ import annotations
import json
+from collections import Counter
from dataclasses import asdict
from typing import Any
from sqlalchemy import func, select
+from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession
+from repowise.core.analysis.doc_drift.constants import (
+ REFERENCE_BASIS,
+ UNAVAILABLE_NO_TABLE,
+ UNAVAILABLE_NOT_COMPUTED,
+ UNAVAILABLE_READ_FAILED,
+)
from repowise.core.analysis.health.signals import file_signals
from repowise.core.ingestion.models import (
FILE_DEPENDENCY_EDGE_TYPES,
SYMBOL_USE_EDGE_TYPES,
)
from repowise.core.persistence.crud import (
+ doc_drift_references_stored,
get_all_file_metrics,
get_community_members,
get_cross_community_edges,
+ get_doc_drift_findings,
+ get_doc_drift_references,
get_git_metadata,
get_graph_edges_for_node,
get_graph_node,
get_graph_nodes_by_ids,
get_node_degree_counts,
+ serialize_doc_drift_reference_row,
)
from repowise.core.persistence.models import (
CoverageFile,
@@ -41,9 +53,22 @@ from repowise.core.persistence.models import (
from repowise.server.mcp_server._basis import basis_cache_key, call_resolution_basis
from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
from repowise.server.mcp_server._graph_files import keep_projected_edge, node_to_file
-from repowise.server.mcp_server._helpers import filter_dicts_by_key, filter_path_list
+from repowise.server.mcp_server._helpers import (
+ filter_dicts_by_key,
+ filter_path_list,
+ filter_rows_by_attr,
+ is_missing_table,
+)
from repowise.server.schemas.intelligence import SYMBOL_RELATION_GROUP_OF
+#: Where a resolved target path waits between its card being built and the
+#: batched doc-drift read. Popped by that pass, so it never reaches a response.
+_DOC_DRIFT_PATH = "_doc_drift_path"
+
+#: Reference rows per target before the cap takes over. The same figure as
+#: ``targets._MAX_USED_BY``, for the same "who points at this" question.
+_MAX_DOC_REFERENCES = 20
+
# Minimum confidence for call edges to filter false positives.
#
# Symbol-level only. The file-level rollup below defers to the shared
@@ -734,6 +759,149 @@ async def _resolve_health(
result_data["health"] = health
+async def attach_doc_references(
+ session: AsyncSession,
+ repository: Repository,
+ cards: dict[str, dict[str, Any]],
+ *,
+ exclude_spec: Any = None,
+ collector: OmissionCollector | None = None,
+) -> None:
+ """Attach, to every card, the documents that name its file.
+
+ The drift pass files a finding against the document, so these stored rows
+ are the only thing that can answer a question asked about a code file.
+ Served rather than recomputed: see :class:`DocDriftReference`.
+
+ Runs once for the whole call, after the targets resolve. Savepoints opened
+ per target nest on the session they share, and the first to exit closes
+ the others.
+
+ Two claims, kept apart: ``references`` says a document names this file,
+ ``documents_with_drift`` says a listed document has some assertion that no
+ longer holds -- anywhere in it, not necessarily about this file.
+ """
+ wanted = {
+ name: card.pop(_DOC_DRIFT_PATH, None)
+ for name, card in cards.items()
+ if _DOC_DRIFT_PATH in card
+ }
+ if not wanted:
+ return
+
+ paths = {path for path in wanted.values() if path}
+ rows: list[Any] = []
+ finding_rows: list[Any] = []
+ stored = True
+ if paths:
+ try:
+ # Not decoration: this read raises on an index older than the
+ # table, and on Postgres a failed statement poisons the whole
+ # transaction.
+ async with session.begin_nested():
+ rows = await get_doc_drift_references(
+ session, repository.id, target_paths=sorted(paths)
+ )
+ # An empty answer is the strong claim "no document
+ # mentions this file", and an empty store cannot support it.
+ # Asked only when the answer would otherwise be empty.
+ stored = bool(rows) or await doc_drift_references_stored(
+ session, repository.id
+ )
+ # Read whole: the findings table is the defect list and is
+ # bounded by design. Ceiling for a repo with thousands of
+ # them: a plural filter on ``get_doc_drift_findings``.
+ if rows:
+ finding_rows = await get_doc_drift_findings(session, repository.id)
+ except (SQLAlchemyError, OSError, LookupError) as exc:
+ # Refuse rather than serve an empty list, which reads as a
+ # clean bill that was never taken -- and name which failure, since
+ # "your index is old" is wrong advice for a transient one.
+ reason = (
+ UNAVAILABLE_NO_TABLE
+ if is_missing_table(exc)
+ else UNAVAILABLE_READ_FAILED
+ )
+ for name in wanted:
+ cards[name]["doc_drift"] = {"unavailable": reason}
+ return
+
+ kept = filter_rows_by_attr(rows, "document_path", exclude_spec)
+ excluded_by_target = Counter(r.target_path for r in rows) - Counter(
+ r.target_path for r in kept
+ )
+ by_target: dict[str, list[Any]] = {}
+ for row in kept:
+ by_target.setdefault(row.target_path, []).append(row)
+
+ drift_by_document = Counter(f.file_path for f in finding_rows)
+
+ for name, path in wanted.items():
+ if not path:
+ # A module target resolves to a directory, and a reference does
+ # not resolve to one.
+ cards[name]["doc_drift"] = None
+ elif not stored:
+ cards[name]["doc_drift"] = {"unavailable": UNAVAILABLE_NOT_COMPUTED}
+ else:
+ cards[name]["doc_drift"] = _doc_reference_block(
+ by_target.get(path, []),
+ drift_by_document,
+ excluded=excluded_by_target.get(path, 0),
+ target=path,
+ collector=collector,
+ )
+
+
+def _doc_reference_block(
+ rows: list[Any],
+ drift_by_document: Counter[str],
+ *,
+ excluded: int,
+ target: str,
+ collector: OmissionCollector | None,
+) -> dict[str, Any]:
+ """One target's reverse-view block, built from its own rows."""
+ block: dict[str, Any] = {}
+ seen: set[tuple[str, int]] = set()
+ emitted = []
+ for row in rows:
+ # One markdown link with a fragment yields both a link row and an
+ # anchor row at the same site. The store keeps them apart because they
+ # drift apart; a reader counting mentions should see one.
+ site = (row.document_path, row.line_number)
+ if site in seen:
+ continue
+ seen.add(site)
+ emitted.append(serialize_doc_drift_reference_row(row))
+ cap_collection(
+ block,
+ "references",
+ emitted,
+ _MAX_DOC_REFERENCES,
+ collector,
+ label=f"documents naming {target}",
+ )
+ block["documents"] = len({r.document_path for r in rows})
+ if excluded:
+ # Otherwise a tree whose naming documents are all excluded reads as a
+ # file nothing mentions.
+ block["references_excluded"] = excluded
+
+ # Only the documents this answer matched; the repo-wide total is what
+ # ``get_health(include=["doc_drift"])`` is for.
+ matched = sorted({r.document_path for r in rows} & set(drift_by_document))
+ if matched:
+ block["documents_with_drift"] = [
+ {"document": path, "findings": drift_by_document[path]} for path in matched
+ ]
+
+ # Emitted on an empty answer too: that is the one most likely to be
+ # read as proof that nothing documents this file.
+ block["references_basis"] = REFERENCE_BASIS
+ return block
+
+
async def _resolve_skeleton(
session: AsyncSession,
repository: Repository,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index fcdd18040..2920859af 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -47,6 +47,7 @@ from repowise.server.mcp_server._helpers import (
from repowise.server.mcp_server._references import path_identity, symbol_identity
from repowise.server.mcp_server._symbol_lookup import resolve_symbol_rows
from repowise.server.mcp_server.tool_context.enrichment import (
+ _DOC_DRIFT_PATH,
_resolve_call_graph,
_resolve_community,
_resolve_health,
@@ -1205,6 +1206,13 @@ async def _resolve_one_target(
if include and "health" in include:
await _resolve_health(session, repository, target, target_type, result_data)
+ # --- Documents naming this file (doc-drift reverse view) ---
+ # Only the path is recorded here. The read itself is one batched pass over
+ # every target, after the gather: see ``attach_doc_references``, which
+ # explains why a savepoint per target cannot work on a shared session.
+ if include and "doc_drift" in include:
+ result_data[_DOC_DRIFT_PATH] = file_path_for_git
+
# --- Skeleton (distill) — opt-in only, see the module note ---
if want_skeleton:
await _resolve_skeleton(
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 7978adb30..ff1c89623 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_health.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py
@@ -12,7 +12,10 @@ 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.doc_drift.constants import (
+ DETECTION_BASIS,
+ UNAVAILABLE_NO_TABLE,
+)
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 (
@@ -2265,7 +2268,7 @@ async def get_health(
# 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
+ # with it. ``replace_doc_drift_guarded`` guards the
# write side against the same hazard.
async with session.begin_nested():
rows = await get_doc_drift_findings(session, repository.id)
@@ -2280,7 +2283,7 @@ async def get_health(
# 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"
+ drift_unavailable = UNAVAILABLE_NO_TABLE
if scoped:
drift_rows = [r for r in drift_rows if r.file_path in effective_targets]
diff --git a/tests/unit/cli/test_tool_adapter_commands.py b/tests/unit/cli/test_tool_adapter_commands.py
index 334b0176e..71b0a4664 100644
--- a/tests/unit/cli/test_tool_adapter_commands.py
+++ b/tests/unit/cli/test_tool_adapter_commands.py
@@ -368,6 +368,26 @@ def test_context_projection_keeps_every_include_block():
assert card["metrics"] == {"pagerank": 0.4}
+def test_cli_include_choices_match_the_tools_own_blocks():
+ """The CLI keeps its own copy of the block names, so pin the two together.
+
+ ``click.Choice`` is built at import time and the tool lives in the server
+ package, which the command imports lazily to keep CLI startup cheap --- so
+ the names are duplicated on purpose. Without this, a block added to the
+ tool is simply unreachable from the terminal, rejected by the parser with
+ a usage error naming every block but the new one. ``docs`` and
+ ``freshness`` are excluded because they are always returned, so offering
+ them as choices would advertise a flag that does nothing.
+ """
+ from repowise.cli.commands import context_cmd
+ from repowise.server.mcp_server.tool_context import context as tool_context
+
+ assert set(context_cmd._INCLUDE_BLOCKS) == set(tool_context._INCLUDE_BLOCKS) - {
+ "docs",
+ "freshness",
+ }
+
+
def test_context_projection_keeps_a_tombstones_redirect():
"""The successor path is the whole point of a tombstone card."""
payload = {
diff --git a/tests/unit/doc_drift/test_resolved_references.py b/tests/unit/doc_drift/test_resolved_references.py
new file mode 100644
index 000000000..e944da997
--- /dev/null
+++ b/tests/unit/doc_drift/test_resolved_references.py
@@ -0,0 +1,155 @@
+"""What the pass retains besides findings: the references that resolved.
+
+The reverse view is built on these rows, so the thing worth pinning is what
+never becomes one. A row asserts that a document names a file and the name
+still resolves; an ambiguous or uncheckable reference asserts nothing, and
+recording one as a fact is how "which documents mention this file" would start
+answering with documents that do not.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.doc_drift import DocDriftAnalyzer
+from repowise.core.analysis.doc_drift.models import DriftKind
+
+
+def _analyze(files: dict[str, str], config: dict | None = None):
+ source_map = {k: v.encode("utf-8") for k, v in files.items()}
+ return DocDriftAnalyzer("repo", source_map=source_map).analyze(config)
+
+
+def _refs(report):
+ return {(r.doc_path, r.target_path, r.kind, r.line) for r in report.resolved_references}
+
+
+def test_a_resolved_path_is_retained():
+ report = _analyze(
+ {
+ "docs/a.md": "## Auth\n\nSee `src/auth.py` for tokens.\n",
+ "src/auth.py": "",
+ }
+ )
+
+ assert report.total_findings == 0
+ (ref,) = report.resolved_references
+ assert ref.doc_path == "docs/a.md"
+ assert ref.target_path == "src/auth.py"
+ assert ref.kind is DriftKind.PATH
+ assert ref.line == 3
+ assert ref.section == "Auth"
+
+
+def test_a_relative_link_is_stored_as_the_path_it_resolves_to():
+ """The join the resolver used to compute and throw away.
+
+ ``docs/guide.md`` written inside ``docs/a.md`` means ``docs/docs/...``
+ only if you ignore the document's own directory. Storing what was written
+ rather than what it resolved to would file every relative link under a
+ path that does not exist.
+ """
+ report = _analyze(
+ {
+ "docs/a.md": "See [the guide](guide.md).\n",
+ "docs/guide.md": "# Guide\n",
+ }
+ )
+
+ targets = {r.target_path for r in report.resolved_references}
+ assert targets == {"docs/guide.md"}
+
+
+def test_a_drifted_reference_becomes_a_finding_and_not_a_row():
+ """The two are complements. A missing target resolves to nothing at all."""
+ report = _analyze(
+ {
+ "docs/a.md": "See `src/gone.py`.\n",
+ "src/present.py": "",
+ }
+ )
+
+ assert report.total_findings == 1
+ assert report.resolved_references == []
+
+
+def test_an_ambiguous_reference_is_not_recorded_as_a_fact():
+ """A basename match is not a resolution, and this store holds only resolutions."""
+ report = _analyze(
+ {
+ "docs/a.md": "See `src/models.py`.\n",
+ "src/auth/models.py": "",
+ }
+ )
+
+ assert report.verdict_summary["ambiguous"] == 1
+ assert report.resolved_references == []
+
+
+def test_an_uncheckable_reference_is_not_recorded():
+ """Unanchored targets are files this repository was never supposed to have."""
+ report = _analyze({"docs/a.md": "Edit `config.yaml` to begin.\n"})
+
+ assert report.verdict_summary["uncheckable"] == 1
+ assert report.resolved_references == []
+
+
+def test_a_document_naming_itself_is_dropped():
+ """A table of contents anchoring its own headings answers no reverse question."""
+ report = _analyze({"docs/a.md": "# Setup\n\n[jump](#setup)\n"})
+
+ assert report.verdict_summary["resolved"] == 1
+ assert report.resolved_references == []
+
+
+def test_a_cross_document_anchor_points_at_the_host_document():
+ report = _analyze(
+ {
+ "docs/a.md": "See [setup](guide.md#setup).\n",
+ "docs/guide.md": "# Setup\n",
+ }
+ )
+
+ rows = {(r.target_path, r.kind) for r in report.resolved_references}
+ assert ("docs/guide.md", DriftKind.ANCHOR) in rows
+ assert all(r.doc_path == "docs/a.md" for r in report.resolved_references)
+
+
+def test_a_resolved_command_is_not_a_row():
+ """A make target is not a file, so it has no place in a path-keyed store."""
+ report = _analyze(
+ {
+ "docs/a.md": "Run `make build` to compile.\n",
+ "Makefile": "build:\n\techo hi\n",
+ }
+ )
+
+ assert report.verdict_summary["resolved"] == 1
+ assert report.resolved_references == []
+
+
+def test_two_references_on_one_line_are_both_retained():
+ """The same reason the findings key carries the target: one line, two claims."""
+ report = _analyze(
+ {
+ "docs/a.md": "See [setup](guide.md#setup).\n",
+ "docs/guide.md": "# Setup\n",
+ }
+ )
+
+ assert {r.kind for r in report.resolved_references} == {
+ DriftKind.LINK,
+ DriftKind.ANCHOR,
+ }
+ assert len(_refs(report)) == 2
+
+
+def test_retention_changes_no_finding():
+ """The pass's own answer must not move because a second consumer was added."""
+ files = {
+ "docs/a.md": "See `src/gone.py` and `src/here.py`.\n",
+ "src/here.py": "",
+ }
+ report = _analyze(files)
+
+ assert report.total_findings == 1
+ assert report.verdict_summary["resolved"] == 1
+ assert [r.target_path for r in report.resolved_references] == ["src/here.py"]
diff --git a/tests/unit/persistence/test_doc_drift_references.py b/tests/unit/persistence/test_doc_drift_references.py
new file mode 100644
index 000000000..6b9bc61a0
--- /dev/null
+++ b/tests/unit/persistence/test_doc_drift_references.py
@@ -0,0 +1,284 @@
+"""Persistence for the resolved-reference store, the drift reverse index.
+
+The claim this table makes is weaker than a finding's and easier to corrupt: a
+row says a document names a file that exists. These tests pin the two ways it
+could start lying --- a scoped rewrite deleting rows it did not recompute, and
+an empty store being indistinguishable from a clean one.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from sqlalchemy import select
+
+from repowise.core.analysis.doc_drift.models import (
+ DocDriftFindingData,
+ DriftKind,
+ ResolvedDocReference,
+)
+from repowise.core.persistence.crud import (
+ doc_drift_references_stored,
+ get_doc_drift_references,
+ replace_doc_drift_guarded,
+ replace_doc_drift_references,
+ serialize_doc_drift_reference_row,
+)
+from repowise.core.persistence.models import DocDriftReference
+from tests.unit.persistence.helpers import insert_repo
+
+
+def _ref(
+ doc_path: str = "docs/a.md",
+ target_path: str = "src/auth.py",
+ line: int = 10,
+ kind: DriftKind = DriftKind.PATH,
+ section: str = "Authentication > Tokens",
+) -> ResolvedDocReference:
+ return ResolvedDocReference(
+ doc_path=doc_path,
+ target_path=target_path,
+ kind=kind,
+ line=line,
+ section=section,
+ )
+
+
+async def _rows(session, repo_id: str) -> list[DocDriftReference]:
+ stmt = select(DocDriftReference).where(DocDriftReference.repository_id == repo_id)
+ return list((await session.execute(stmt)).scalars().all())
+
+
+async def test_references_round_trip(async_session):
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(async_session, repo.id, [_ref()])
+ await async_session.commit()
+
+ (row,) = await get_doc_drift_references(async_session, repo.id)
+ assert row.document_path == "docs/a.md"
+ assert row.target_path == "src/auth.py"
+ assert row.kind == "path"
+ assert row.line_number == 10
+ assert row.section == "Authentication > Tokens"
+
+
+async def test_rerunning_the_pass_changes_no_rows(async_session):
+ """Idempotency, the same exit criterion the findings table has."""
+ repo = await insert_repo(async_session)
+ refs = [_ref(), _ref(doc_path="docs/b.md", line=4)]
+ await replace_doc_drift_references(async_session, repo.id, refs)
+ await async_session.commit()
+ first = {(r.document_path, r.target_path, r.line_number) for r in await _rows(async_session, repo.id)}
+
+ await replace_doc_drift_references(async_session, repo.id, refs)
+ await async_session.commit()
+ second = await _rows(async_session, repo.id)
+
+ assert len(second) == 2
+ assert {(r.document_path, r.target_path, r.line_number) for r in second} == first
+
+
+async def test_two_references_at_one_site_do_not_collide(async_session):
+ """A markdown link with a fragment yields a link row and an anchor row."""
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(
+ async_session,
+ repo.id,
+ [
+ _ref(kind=DriftKind.LINK, target_path="docs/guide.md"),
+ _ref(kind=DriftKind.ANCHOR, target_path="docs/guide.md"),
+ ],
+ )
+ await async_session.commit()
+
+ assert len(await _rows(async_session, repo.id)) == 2
+
+
+async def test_duplicate_references_in_one_batch_collapse(async_session):
+ """A document naming the same file twice on one line is ordinary prose."""
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(async_session, repo.id, [_ref(), _ref()])
+ await async_session.commit()
+
+ assert len(await _rows(async_session, repo.id)) == 1
+
+
+async def test_scoped_write_keeps_rows_for_documents_it_did_not_read(async_session):
+ """The hazard: a partial run must not delete what it never recomputed."""
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(
+ async_session,
+ repo.id,
+ [_ref(doc_path="docs/a.md"), _ref(doc_path="docs/b.md")],
+ )
+ await async_session.commit()
+
+ # A run that only re-read docs/a.md, and found it now names nothing.
+ await replace_doc_drift_references(
+ async_session, repo.id, [], scope=frozenset({"docs/a.md"})
+ )
+ await async_session.commit()
+
+ remaining = await _rows(async_session, repo.id)
+ assert [r.document_path for r in remaining] == ["docs/b.md"]
+
+
+async def test_scoped_write_refuses_a_row_outside_its_scope(async_session):
+ """Inserted but never deleted by the next scoped run, it would outlive its evidence."""
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(
+ async_session,
+ repo.id,
+ [_ref(doc_path="docs/a.md"), _ref(doc_path="docs/elsewhere.md")],
+ scope=frozenset({"docs/a.md"}),
+ )
+ await async_session.commit()
+
+ assert [r.document_path for r in await _rows(async_session, repo.id)] == ["docs/a.md"]
+
+
+async def test_unscoped_write_replaces_the_repository(async_session):
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(
+ async_session, repo.id, [_ref(doc_path="docs/a.md")]
+ )
+ await async_session.commit()
+
+ await replace_doc_drift_references(
+ async_session, repo.id, [_ref(doc_path="docs/b.md")]
+ )
+ await async_session.commit()
+
+ assert [r.document_path for r in await _rows(async_session, repo.id)] == ["docs/b.md"]
+
+
+async def test_reader_narrows_by_target(async_session):
+ """The question this table exists for, asked about a code file."""
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(
+ async_session,
+ repo.id,
+ [
+ _ref(doc_path="docs/a.md", target_path="src/auth.py"),
+ _ref(doc_path="docs/b.md", target_path="src/auth.py", line=2),
+ _ref(doc_path="docs/c.md", target_path="src/other.py"),
+ ],
+ )
+ await async_session.commit()
+
+ rows = await get_doc_drift_references(
+ async_session, repo.id, target_paths=["src/auth.py"]
+ )
+ assert [r.document_path for r in rows] == ["docs/a.md", "docs/b.md"]
+
+
+async def test_the_reader_answers_about_several_targets_at_once(async_session):
+ """One query for a batch of targets, because they share a session."""
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(
+ async_session,
+ repo.id,
+ [
+ _ref(doc_path="docs/a.md", target_path="src/auth.py"),
+ _ref(doc_path="docs/b.md", target_path="src/db.py"),
+ _ref(doc_path="docs/c.md", target_path="src/other.py"),
+ ],
+ )
+ await async_session.commit()
+
+ rows = await get_doc_drift_references(
+ async_session, repo.id, target_paths=["src/auth.py", "src/db.py"]
+ )
+ assert {r.target_path for r in rows} == {"src/auth.py", "src/db.py"}
+
+
+async def test_asking_about_no_targets_answers_about_none(async_session):
+ """An empty batch must not fall through to "every row in the repository"."""
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(async_session, repo.id, [_ref()])
+ await async_session.commit()
+
+ assert await get_doc_drift_references(async_session, repo.id, target_paths=[]) == []
+
+
+async def test_stored_probe_separates_never_computed_from_genuinely_none(async_session):
+ """An empty table is not a clean tree, and the probe is what tells them apart."""
+ repo = await insert_repo(async_session)
+ assert await doc_drift_references_stored(async_session, repo.id) is False
+
+ await replace_doc_drift_references(async_session, repo.id, [_ref()])
+ await async_session.commit()
+
+ assert await doc_drift_references_stored(async_session, repo.id) is True
+ # A file nothing names, in a repository that was analysed: a real zero.
+ assert (
+ await get_doc_drift_references(async_session, repo.id, target_paths=["src/x.py"])
+ == []
+ )
+
+
+async def test_the_probe_is_scoped_to_its_own_repository(async_session):
+ repo = await insert_repo(async_session)
+ other = await insert_repo(
+ async_session,
+ name="other",
+ local_path="/tmp/other-repo",
+ url="https://github.com/example/other-repo",
+ )
+ await replace_doc_drift_references(async_session, other.id, [_ref()])
+ await async_session.commit()
+
+ assert await doc_drift_references_stored(async_session, other.id) is True
+ assert await doc_drift_references_stored(async_session, repo.id) is False
+
+
+async def test_one_writer_keeps_findings_and_references_on_one_run(async_session):
+ """Written apart they could describe different runs; the reverse view would lie."""
+ repo = await insert_repo(async_session)
+
+ report = SimpleNamespace(
+ findings=[
+ DocDriftFindingData(
+ kind=DriftKind.PATH,
+ file_path="docs/a.md",
+ line_number=3,
+ target="src/gone.py",
+ confidence=0.9,
+ reason="gone",
+ origin="path_no_candidate",
+ evidence=[],
+ )
+ ],
+ resolved_references=[_ref(doc_path="docs/a.md")],
+ authoritative_paths=None,
+ )
+
+ written = await replace_doc_drift_guarded(async_session, repo.id, report)
+ await async_session.commit()
+
+ assert written == 1
+ assert len(await _rows(async_session, repo.id)) == 1
+
+
+async def test_serializer_omits_the_target_every_row_shares(async_session):
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(async_session, repo.id, [_ref()])
+ await async_session.commit()
+
+ (row,) = await get_doc_drift_references(async_session, repo.id)
+ out = serialize_doc_drift_reference_row(row)
+ assert out == {
+ "document": "docs/a.md",
+ "line": 10,
+ "kind": "path",
+ "section": "Authentication > Tokens",
+ }
+
+
+async def test_serializer_drops_an_empty_section(async_session):
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_references(async_session, repo.id, [_ref(section="")])
+ await async_session.commit()
+
+ (row,) = await get_doc_drift_references(async_session, repo.id)
+ assert "section" not in serialize_doc_drift_reference_row(row)
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index d0f6b5385..3d864112c 100644
--- a/tests/unit/persistence/test_models.py
+++ b/tests/unit/persistence/test_models.py
@@ -306,6 +306,7 @@ def test_base_includes_all_models():
"fix_events",
"dead_code_findings",
"doc_drift_findings",
+ "doc_drift_references",
"decision_records",
"decision_evidence",
"decision_edges",
diff --git a/tests/unit/server/mcp/test_change_risk_prior_fixes.py b/tests/unit/server/mcp/test_change_risk_prior_fixes.py
index d7b79d9ff..3a04cf327 100644
--- a/tests/unit/server/mcp/test_change_risk_prior_fixes.py
+++ b/tests/unit/server/mcp/test_change_risk_prior_fixes.py
@@ -163,9 +163,12 @@ async def test_concentration_only_names_a_file_the_block_shows(monkeypatch):
],
)
def test_a_missing_table_is_told_apart_from_a_broken_read(message, missing):
+ """Shared by every tool that reads an analysis table, hence its home."""
+ from repowise.server.mcp_server._helpers import is_missing_table
+
exc = OperationalError("SELECT 1", {}, Exception(message))
- assert tool._is_missing_table(exc) is missing
+ assert is_missing_table(exc) is missing
def test_the_failure_reason_names_the_class_without_quoting_the_driver():
diff --git a/tests/unit/server/mcp/test_context_doc_drift.py b/tests/unit/server/mcp/test_context_doc_drift.py
new file mode 100644
index 000000000..92d245719
--- /dev/null
+++ b/tests/unit/server/mcp/test_context_doc_drift.py
@@ -0,0 +1,368 @@
+"""``get_context(include=["doc_drift"])`` — the drift reverse view.
+
+The drift pass files a finding against the *document*, so a question asked
+about a code file can only be answered from the stored reference rows. What
+these tests pin is the honesty of that answer: the two claims it makes must
+stay apart, and an answer it cannot support must not render as a confident
+zero. "No document mentions src/auth.py" is a far stronger statement than "no
+drift findings", and an unpopulated store produces it silently.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.exc import OperationalError
+
+from repowise.core.analysis.doc_drift.constants import REFERENCE_BASIS
+from repowise.core.persistence.models import DocDriftFinding, DocDriftReference
+
+_TARGET = "src/auth/service.py"
+
+
+def _ref(repo_id: str, document: str, line: int, **kw) -> DocDriftReference:
+ return DocDriftReference(
+ repository_id=repo_id,
+ document_path=document,
+ target_path=kw.get("target", _TARGET),
+ kind=kw.get("kind", "path"),
+ line_number=line,
+ section=kw.get("section", "Authentication"),
+ )
+
+
+def _finding(repo_id: str, document: str, line: int) -> DocDriftFinding:
+ return DocDriftFinding(
+ repository_id=repo_id,
+ file_path=document,
+ line_number=line,
+ kind="path",
+ target="src/gone.py",
+ confidence=0.9,
+ reason="Document names src/gone.py, which no longer exists.",
+ origin="path_no_candidate",
+ evidence_json="[]",
+ raw="src/gone.py",
+ context="see src/gone.py",
+ )
+
+
+async def reference_rows(session, repo_id):
+ session.add_all(
+ [
+ _ref(repo_id, "docs/auth.md", 12),
+ _ref(repo_id, "docs/auth.md", 40, kind="link"),
+ _ref(repo_id, "docs/overview.md", 3, section=""),
+ # A different file entirely: it must not reach the answer.
+ _ref(repo_id, "docs/db.md", 5, target="src/db/models.py"),
+ ]
+ )
+ await session.commit()
+ return repo_id
+
+
+async def test_the_block_is_absent_until_it_is_asked_for(setup_mcp, reference_rows):
+ from repowise.server.mcp_server import get_context
+
+ card = (await get_context(targets=[_TARGET]))["targets"][_TARGET]
+ assert "doc_drift" not in card
+
+
+async def test_doc_drift_is_a_known_include_key(setup_mcp, reference_rows):
+ """An unrecognised key lands in ignored_arguments, so this would be visible."""
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(targets=[_TARGET], include=["doc_drift"])
+
+ ignored = [
+ value
+ for entry in (result.get("ignored_arguments") or [])
+ for value in entry.get("values", [])
+ ]
+ assert "doc_drift" not in ignored
+
+
+async def test_it_answers_with_the_documents_that_name_this_file(
+ setup_mcp, reference_rows
+):
+ from repowise.server.mcp_server import get_context
+
+ card = (await get_context(targets=[_TARGET], include=["doc_drift"]))["targets"][
+ _TARGET
+ ]
+ block = card["doc_drift"]
+
+ assert [r["document"] for r in block["references"]] == [
+ "docs/auth.md",
+ "docs/auth.md",
+ "docs/overview.md",
+ ]
+ assert block["documents"] == 2
+ assert block["references"][0] == {
+ "document": "docs/auth.md",
+ "line": 12,
+ "kind": "path",
+ "section": "Authentication",
+ }
+
+
+async def test_a_reference_to_another_file_stays_out_of_the_answer(
+ setup_mcp, reference_rows
+):
+ """The reverse index is keyed by target; a leak here answers the wrong question."""
+ from repowise.server.mcp_server import get_context
+
+ card = (await get_context(targets=[_TARGET], include=["doc_drift"]))["targets"][
+ _TARGET
+ ]
+
+ assert "docs/db.md" not in {r["document"] for r in card["doc_drift"]["references"]}
+
+
+async def test_the_basis_rides_along_even_when_nothing_was_found(
+ setup_mcp, reference_rows
+):
+ """The empty answer is the one most likely to be read as proof of absence."""
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(
+ targets=["src/auth/middleware.py"], include=["doc_drift"]
+ )
+ block = result["targets"]["src/auth/middleware.py"]["doc_drift"]
+
+ assert block["references"] == []
+ assert block["documents"] == 0
+ assert block["references_basis"] == REFERENCE_BASIS
+
+
+async def test_an_unpopulated_store_is_not_reported_as_a_clean_tree(setup_mcp, repo_id):
+ """The gate this slice had to settle.
+
+ The table is created on the ordinary schema-reconcile path, but the pass
+ only runs when an update has work to do. "Upgraded, never analysed" is a
+ real state, and without this it is indistinguishable from "no document
+ mentions this file" --- a far stronger claim, wrong in the same silent way.
+ """
+ from repowise.server.mcp_server import get_context
+
+ card = (await get_context(targets=[_TARGET], include=["doc_drift"]))["targets"][
+ _TARGET
+ ]
+
+ assert card["doc_drift"] == {"unavailable": "not_computed"}
+
+
+async def test_an_index_without_the_reference_table_says_so(
+ setup_mcp, reference_rows, monkeypatch
+):
+ """"Could not read" must never render as "nothing to report"."""
+ import repowise.server.mcp_server.tool_context.enrichment as enrichment
+ from repowise.server.mcp_server import get_context
+
+ async def _raise(*_a, **_k):
+ raise OperationalError(
+ "select", {}, Exception("no such table: doc_drift_references")
+ )
+
+ monkeypatch.setattr(enrichment, "get_doc_drift_references", _raise)
+
+ result = await get_context(targets=[_TARGET], include=["doc_drift"])
+ card = result["targets"][_TARGET]
+
+ assert card["doc_drift"] == {"unavailable": "index_predates_doc_drift"}
+ # And the failed read did not take the rest of the card with it.
+ assert card["type"] == "file"
+ assert "docs" in card
+
+
+async def test_a_transient_read_failure_is_not_reported_as_an_old_index(
+ setup_mcp, reference_rows, monkeypatch
+):
+ """"Reindex" is the wrong advice for a locked database.
+
+ Both refusals name a cause the reader will act on, so mapping every
+ failure onto the schema one sends them to rebuild an index that was
+ never the problem.
+ """
+ import repowise.server.mcp_server.tool_context.enrichment as enrichment
+ from repowise.server.mcp_server import get_context
+
+ async def _raise(*_a, **_k):
+ raise OperationalError("select", {}, Exception("database is locked"))
+
+ monkeypatch.setattr(enrichment, "get_doc_drift_references", _raise)
+
+ card = (await get_context(targets=[_TARGET], include=["doc_drift"]))["targets"][
+ _TARGET
+ ]
+
+ assert card["doc_drift"] == {"unavailable": "drift_read_failed"}
+
+
+async def test_one_link_with_a_fragment_is_counted_once(setup_mcp, session, repo_id):
+ """The store keeps the link and the anchor apart; a reader counts mentions.
+
+ ``[guide](x.py#top)`` yields both a link row and an anchor row at the same
+ site, because the two drift apart and a finding has to name which. Showing
+ the reader the same document and line twice over-reports how many places
+ mention the file, and spends two of twenty card slots saying it.
+ """
+ from repowise.server.mcp_server import get_context
+
+ session.add_all(
+ [
+ _ref(repo_id, "docs/auth.md", 12, kind="link"),
+ _ref(repo_id, "docs/auth.md", 12, kind="anchor"),
+ ]
+ )
+ await session.commit()
+
+ block = (await get_context(targets=[_TARGET], include=["doc_drift"]))["targets"][
+ _TARGET
+ ]["doc_drift"]
+
+ assert len(block["references"]) == 1
+ assert block["documents"] == 1
+
+
+async def test_an_answer_emptied_by_exclusions_says_so(
+ setup_mcp, session, repo_id, monkeypatch
+):
+ """An excluded document is not an absent one.
+
+ Without the count, a repository whose documentation directory is excluded
+ reports every file in it as mentioned by nothing --- the same false claim
+ the unpopulated-store guard exists to prevent, reached by another route.
+ """
+ import repowise.server.mcp_server.tool_context.context as context_mod
+ from repowise.server.mcp_server import get_context
+
+ session.add(_ref(repo_id, "docs/auth.md", 12))
+ await session.commit()
+
+ import pathspec
+
+ # Excludes the naming document, not the target, which is the case that
+ # empties the answer without emptying the card.
+ spec = pathspec.PathSpec.from_lines("gitwildmatch", ["docs/"])
+ monkeypatch.setattr(context_mod, "_get_exclude_spec", lambda *_a, **_k: spec)
+
+ block = (await get_context(targets=[_TARGET], include=["doc_drift"]))["targets"][
+ _TARGET
+ ]["doc_drift"]
+
+ assert block["references"] == []
+ assert block["references_excluded"] == 1
+
+
+async def test_a_documents_own_drift_is_reported_as_the_documents_and_not_the_targets(
+ setup_mcp, session, reference_rows
+):
+ """The easiest way for this surface to lie.
+
+ A document that describes this file and a document carrying a drifted
+ reference are different claims. The drifted reference here points at
+ ``src/gone.py``, not at the target, and the block must keep that separate
+ rather than implying the description of the target is wrong.
+ """
+ from repowise.server.mcp_server import get_context
+
+ session.add(_finding(reference_rows, "docs/auth.md", 90))
+ await session.commit()
+
+ card = (await get_context(targets=[_TARGET], include=["doc_drift"]))["targets"][
+ _TARGET
+ ]
+ block = card["doc_drift"]
+
+ assert block["documents_with_drift"] == [{"document": "docs/auth.md", "findings": 1}]
+ # The reference rows themselves are untouched by it.
+ assert len(block["references"]) == 3
+ assert "which need not be about this file" in block["references_basis"]
+
+
+async def test_several_targets_in_one_call_each_get_their_own_answer(
+ setup_mcp, reference_rows
+):
+ """Targets are resolved concurrently over ONE shared session.
+
+ This block is the only enrichment helper that opens a savepoint, and
+ ``asyncio.gather`` means a second target can enter one while the first is
+ still inside. If those nest, the first to exit closes the other's
+ transaction and every later statement in the call fails --- turning the
+ guard meant to isolate one bad read into the thing that breaks the rest.
+ """
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(
+ targets=[_TARGET, "src/auth/middleware.py", "src/db/models.py"],
+ include=["doc_drift"],
+ )
+
+ cards = result["targets"]
+ assert len(cards) == 3
+ assert [r["document"] for r in cards[_TARGET]["doc_drift"]["references"]] == [
+ "docs/auth.md",
+ "docs/auth.md",
+ "docs/overview.md",
+ ]
+ assert cards["src/db/models.py"]["doc_drift"]["references"] == [
+ {"document": "docs/db.md", "line": 5, "kind": "path", "section": "Authentication"}
+ ]
+ assert cards["src/auth/middleware.py"]["doc_drift"]["references"] == []
+ # No target reported a failure, and the rest of each card survived.
+ assert not any("error" in c for c in cards.values())
+ assert all("docs" in c for c in cards.values())
+
+
+async def test_a_clean_document_gets_no_drift_entry(setup_mcp, reference_rows):
+ from repowise.server.mcp_server import get_context
+
+ card = (await get_context(targets=[_TARGET], include=["doc_drift"]))["targets"][
+ _TARGET
+ ]
+
+ assert "documents_with_drift" not in card["doc_drift"]
+
+
+async def test_a_target_with_no_file_path_gets_a_null_block(setup_mcp, reference_rows):
+ """A module target resolves to a directory, which nothing can reference."""
+ from repowise.server.mcp_server import get_context
+
+ result = await get_context(targets=["nonexistent-target-xyz"], include=["doc_drift"])
+ card = result["targets"]["nonexistent-target-xyz"]
+
+ assert card.get("doc_drift") in (None, {"unavailable": "not_computed"})
+
+
+async def test_the_answer_is_capped_with_a_recoverable_receipt(setup_mcp, session, repo_id):
+ """Twenty documents is a card; the rest is a CLI question."""
+ from repowise.server.mcp_server import get_context
+
+ session.add_all([_ref(repo_id, f"docs/g{i:03d}.md", 1) for i in range(30)])
+ await session.commit()
+
+ card = (await get_context(targets=[_TARGET], include=["doc_drift"]))["targets"][
+ _TARGET
+ ]
+ block = card["doc_drift"]
+
+ assert len(block["references"]) == 20
+ assert block["references_total"] == 30
+ assert block["references_omitted"] == 10
+ assert block["references_reduced_reason"] == "construction_cap"
diff --git a/website/cli-reference.md b/website/cli-reference.md
index 5cf4e019c..1c57f0abe 100644
--- a/website/cli-reference.md
+++ b/website/cli-reference.md
@@ -320,7 +320,7 @@ TARGETS are file paths, module paths, or `path/to/file.py::Symbol` ids.
| Flag | Type | Default | Description |
|------|------|---------|-------------|
-| `--include` | choice | — | Opt-in block, repeatable: `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `health`, `skeleton` |
+| `--include` | choice | — | Opt-in block, repeatable: `full_doc`, `ownership`, `last_change`, `callers`, `callees`, `metrics`, `community`, `decisions`, `health`, `skeleton`, `doc_drift` |
| `--no-compact` | flag | false | Add structure, imports and docstrings to each card |
| `--path` | string | cwd | Repo (or workspace) root |
| `--repo` | string | — | Workspace repo alias to query |
diff --git a/website/mcp-server.md b/website/mcp-server.md
index 5ad302d70..c957332ed 100644
--- a/website/mcp-server.md
+++ b/website/mcp-server.md
@@ -247,7 +247,7 @@ Returns rich context for one or more files, modules, or symbols: documentation,
**Parameters:**
- `targets` (list of strings) — file paths, module names, or symbol names
-- `include` (optional) — subset of `["docs", "ownership", "last_change", "decisions", "freshness"]`
+- `include` (optional) — opt-in blocks such as `"ownership"`, `"last_change"`, `"decisions"`, `"callers"`, `"metrics"`, `"skeleton"`, `"health"`, and `"doc_drift"` (the documents that name this file)
- `compact` (optional, default `True`) — when `True`, drops the `structure` block, the `imported_by` list, and per-symbol docstrings/end-line fields to keep the response under ~10K characters. Pass `compact=False` to receive the full payload, e.g. when you specifically need the import-graph dependents or every symbol docstring on a dense file.
**When to use:** Before reading or editing any file. Faster and richer than reading the raw source.