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): put documentation drift on the dashboard (#2370)

Raghav Chamadiyaa46847b8ad9d
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md
index 9edcbd8bf..819fe0115 100644
--- a/docs/architecture/ARCHITECTURE.md
+++ b/docs/architecture/ARCHITECTURE.md
@@ -171,7 +171,7 @@ repowise/
│ │
│ ├── server/ # Python: FastAPI REST API + MCP server
│ │ └── src/repowise/server/
-│ │ ├── routers/ # FastAPI routers (repos, pages, jobs, symbols, graph, git, dead-code, decisions, search, claude-md)
+│ │ ├── routers/ # FastAPI routers (repos, pages, jobs, symbols, graph, git, dead-code, doc-drift, decisions, search, claude-md)
│ │ ├── mcp_server/ # MCP server package (11 default tools, split into focused modules)
│ │ ├── webhooks/ # GitHub + GitLab handlers
│ │ ├── job_executor.py # Background pipeline executor: bridges REST to core pipeline
@@ -1136,6 +1136,8 @@ Key routers:
- `/api/repos/{id}/dead-code`: dead code findings (GET list, POST trigger analysis)
- `/api/repos/{id}/dead-code/summary`: aggregate dead code stats
- `/api/dead-code/{finding_id}`: PATCH to resolve/acknowledge findings
+- `/api/repos/{id}/doc-drift`: documents whose assertions the repo no longer satisfies, with a server-computed summary
+- `/api/repos/{id}/doc-drift/references`: which documents name one file (the reverse view)
- `/api/repos/{id}/claude-md`: GET preview of generated CLAUDE.md section (JSON, no disk write)
- `/api/repos/{id}/claude-md/generate`: POST to regenerate and write CLAUDE.md to disk
- `/health`: liveness + readiness (checks DB + provider)
diff --git a/packages/api-client/package.json b/packages/api-client/package.json
index 0ce09b97e..da6e5a6d4 100644
--- a/packages/api-client/package.json
+++ b/packages/api-client/package.json
@@ -20,6 +20,7 @@
"./coupling": "./src/coupling.ts",
"./dead-code": "./src/dead-code.ts",
"./decisions": "./src/decisions.ts",
+ "./doc-drift": "./src/doc-drift.ts",
"./episodes": "./src/episodes.ts",
"./external-systems": "./src/external-systems.ts",
"./feedback": "./src/feedback.ts",
diff --git a/packages/api-client/src/doc-drift.ts b/packages/api-client/src/doc-drift.ts
new file mode 100644
index 000000000..472cd23c2
--- /dev/null
+++ b/packages/api-client/src/doc-drift.ts
@@ -0,0 +1,56 @@
+/**
+ * Documentation-drift API client. The response types live in the shared
+ * `@repowise-dev/types/doc-drift` contract; this module re-exports them and
+ * keeps only the fetch functions.
+ */
+import type {
+ DocDriftReferencesResponse,
+ DocDriftResponse,
+} from "@repowise-dev/types/doc-drift";
+import { apiGet } from "./client";
+
+export type {
+ DocDriftDocumentDrift,
+ DocDriftFinding,
+ DocDriftKind,
+ DocDriftReference,
+ DocDriftReferencesResponse,
+ DocDriftResponse,
+ DocDriftSummary,
+ DocDriftUnavailable,
+} from "@repowise-dev/types/doc-drift";
+
+/**
+ * Documents whose assertions the repository no longer satisfies.
+ *
+ * The response carries its own summary; do not recompute one from `findings`,
+ * which is capped by `limit` while the summary counts the whole query.
+ */
+export async function getDocDrift(
+ repoId: string,
+ opts?: {
+ min_confidence?: number;
+ kind?: string;
+ document?: string;
+ limit?: number;
+ },
+): Promise<DocDriftResponse> {
+ return apiGet<DocDriftResponse>(`/api/repos/${repoId}/doc-drift`, opts);
+}
+
+/**
+ * Which documents name `target`, and which of them carry drift.
+ *
+ * A reference says a document names a file the repository still has. It does
+ * not say the document describes it.
+ */
+export async function getDocDriftReferences(
+ repoId: string,
+ target: string,
+ opts?: { limit?: number },
+): Promise<DocDriftReferencesResponse> {
+ return apiGet<DocDriftReferencesResponse>(
+ `/api/repos/${repoId}/doc-drift/references`,
+ { target, ...opts },
+ );
+}
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/serialize.py b/packages/core/src/repowise/core/analysis/doc_drift/serialize.py
new file mode 100644
index 000000000..7fb154e36
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/doc_drift/serialize.py
@@ -0,0 +1,282 @@
+"""Session-free serialization and read-time rules for documentation drift.
+
+One place where a drift finding becomes a dict, whatever produced it. Two
+producers exist and they hold different objects: a store holds ORM rows, while
+a pipeline run holds the analyzer's :class:`~.models.DocDriftReport` before
+anything is written. Both reach the same keys through the builders here, so the
+two shapes are identical by construction rather than by a test that notices
+afterwards.
+
+Nothing in this module touches a session, a query or an ORM class. That is what
+lets a consumer serialize a run it never persisted --- and it is why the
+read-time rules live here too. A rule left inside a route handler is forked by
+the next surface that needs it, which is the drift
+``tests/unit/dead_code/test_confidence_parity.py`` exists to remember.
+
+The no-serializer rule in :mod:`~.models` still holds: it is about the
+analyzer's dataclasses carrying their own ``to_dict``, and these are free
+functions over them.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from collections import Counter
+from collections.abc import Mapping, Sequence
+from typing import Any
+
+from .constants import DETECTION_BASIS, bucket_confidences
+
+#: Namespace for :func:`derive_doc_drift_id`, mirroring ``derive_decision_id``.
+#: Versioned so a future change to the key can be told from a hash collision.
+_ID_NAMESPACE = "repowise.doc_drift.id.v1"
+
+#: Field separator for the digest. NUL cannot occur in a path, a kind or a
+#: target, so no two distinct keys can join to the same string.
+_FIELD_SEP = "\x00"
+
+
+def _kind_str(kind: Any) -> str:
+ """A ``DriftKind`` or a stored string, as the string both sides write."""
+ return str(kind.value) if hasattr(kind, "value") else str(kind)
+
+
+def derive_doc_drift_id(
+ file_path: str,
+ kind: Any,
+ line_number: int,
+ target: str,
+) -> str:
+ """The id a finding at this site has, in every store, on every run.
+
+ Deliberately the four columns ``uq_doc_drift_finding_site`` names minus the
+ repository, so a finding keeps one id across the surfaces that serve it.
+ ``DocDriftFinding.id`` is an autoincrement integer, which is re-minted
+ whenever a store is rebuilt rather than updated and means nothing to a
+ consumer holding a report instead of rows; this is what a client keys
+ triage on.
+
+ The repository is left out on purpose, and that is the difference from
+ :func:`~repowise.core.persistence.crud.decisions.derive_decision_id`. Two
+ deployments index the same tree under different repository ids, so
+ including it would give the same finding two ids and split the triage a
+ reader thinks is one list. The consequence is accepted: ids are unique
+ within a repository and are not a global key.
+
+ 32 lowercase hex, the house width.
+ """
+ parts = (
+ _ID_NAMESPACE,
+ file_path,
+ _kind_str(kind),
+ str(int(line_number)),
+ target,
+ )
+ return hashlib.sha256(_FIELD_SEP.join(parts).encode("utf-8")).hexdigest()[:32]
+
+
+def finding_dict(
+ *,
+ file_path: str,
+ kind: Any,
+ line_number: int,
+ target: str,
+ confidence: float,
+ origin: str,
+ reason: str,
+ raw: str,
+ context: str,
+ evidence: Sequence[str] | None = None,
+) -> dict:
+ """One finding as a dict, from primitives either producer can supply.
+
+ The parameters are the finding's fields, which is the point: a store holds
+ an ORM row and a pipeline run holds a dataclass, and neither should have to
+ build the other's type to be serialized. Taking the analyzer's dataclass
+ instead would also force the evidence decode that ``evidence=None`` exists
+ to skip.
+
+ ``evidence=None`` drops the key for a caller under a response budget: its
+ first line restates ``file_path``, ``line_number`` and ``raw``, and the
+ rest is the resolver's own trace.
+ """
+ out = {
+ "file_path": file_path,
+ "line_number": int(line_number),
+ "kind": _kind_str(kind),
+ "target": 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(float(confidence), 2),
+ "origin": origin,
+ "reason": reason,
+ "raw": raw,
+ "context": context,
+ }
+ if evidence is not None:
+ out["evidence"] = [str(line) for line in evidence]
+ return out
+
+
+def reference_dict(
+ *,
+ document_path: str,
+ kind: Any,
+ line_number: int,
+ section: str = "",
+) -> dict:
+ """One resolved reference as a dict, from primitives.
+
+ ``target_path`` is absent because every row in a reverse answer shares it.
+ The keys are ``document``/``line`` rather than the finding builder'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": document_path,
+ "line": int(line_number),
+ "kind": _kind_str(kind),
+ }
+ if section:
+ out["section"] = section
+ return out
+
+
+def serialize_finding(finding: Any, *, evidence: bool = True) -> dict:
+ """A ``DocDriftFindingData`` as a dict, identical to the stored row's.
+
+ The dataclass carries ``evidence`` as a list where the row carries it as a
+ JSON blob; that difference ends here.
+ """
+ return finding_dict(
+ file_path=finding.file_path,
+ kind=finding.kind,
+ line_number=finding.line_number,
+ target=finding.target,
+ confidence=finding.confidence,
+ origin=finding.origin,
+ reason=finding.reason,
+ raw=finding.raw,
+ context=finding.context,
+ evidence=list(finding.evidence or []) if evidence else None,
+ )
+
+
+def serialize_reference(reference: Any) -> dict:
+ """A ``ResolvedDocReference`` as a dict, identical to the stored row's."""
+ return reference_dict(
+ document_path=reference.doc_path,
+ kind=reference.kind,
+ line_number=reference.line,
+ section=reference.section,
+ )
+
+
+def summarize_findings(findings: Sequence[Mapping[str, Any]]) -> dict:
+ """The rollup a surface shows above a finding list.
+
+ Computed once, server-side, rather than by each client over the rows it
+ happens to have been served: a client that recomputes it reports the page
+ it holds as the repository. ``findings_total`` is therefore the count
+ *before* any display cap, and a caller that caps says so beside it.
+
+ ``findings_basis`` rides along because a count without it claims coverage
+ this detector does not have: most references in a real tree are
+ uncheckable, and a summary is exactly where that gets forgotten.
+ """
+ return {
+ "findings_total": len(findings),
+ "documents": len({f["file_path"] for f in findings}),
+ "confidence": bucket_confidences(f["confidence"] for f in findings),
+ "by_kind": _count_by(f["kind"] for f in findings),
+ "findings_basis": DETECTION_BASIS,
+ }
+
+
+def _count_by(values) -> dict[str, int]:
+ """Ordered counts, so two runs over equal data serialize equal bytes."""
+ return dict(sorted(Counter(values).items()))
+
+
+def collapse_reference_sites(
+ references: Sequence[Mapping[str, Any]],
+) -> list[dict]:
+ """Drop the second reference at a document site, keeping the first.
+
+ One markdown link with a fragment yields both a ``link`` row and an
+ ``anchor`` row at the same line. The store keeps them apart because they
+ drift apart, but a reader counting mentions should not be shown the same
+ document and line twice, and a display cap should not be spent saying it
+ twice.
+ """
+ seen: set[tuple[str, int]] = set()
+ kept: list[dict] = []
+ for reference in references:
+ site = (reference["document"], reference["line"])
+ if site in seen:
+ continue
+ seen.add(site)
+ kept.append(dict(reference))
+ return kept
+
+
+def documents_with_drift(
+ references: Sequence[Mapping[str, Any]],
+ findings_by_document: Mapping[str, int],
+) -> list[dict]:
+ """Which of these documents carry drift, and how much.
+
+ A weaker claim than it looks, and the easiest place for a surface to start
+ lying: a drifted reference resolves to nothing, so no row here can say that
+ a document's description of the target is wrong. It says only that a
+ document naming the target has some assertion, anywhere in it, that no
+ longer holds.
+
+ Pass the full reference list, not a capped one, or a document past the cap
+ reads as clean.
+ """
+ matched = sorted({r["document"] for r in references} & set(findings_by_document))
+ return [{"document": path, "findings": findings_by_document[path]} for path in matched]
+
+
+def serialize_report(report: Any) -> dict:
+ """A whole ``DocDriftReport`` as one JSON-ready dict, with no session.
+
+ For a consumer that holds a pipeline result rather than a store: it gets
+ the same finding dicts a store would serve, so a surface reading one cannot
+ disagree with a surface reading the other.
+
+ References arrive pre-inverted by target path because that is the only
+ question the reverse view asks, and a consumer without a database has no
+ index to ask it with. Each list is ordered the way the store's own
+ ``ORDER BY`` returns it, so the two agree row for row.
+ """
+ findings = []
+ for finding in report.findings:
+ # The id the route mints from a stored row, minted here too. Without it
+ # a consumer serving drift from this artifact would emit findings the
+ # wire contract marks as carrying one, and the table that keys its rows
+ # on it would key every row on nothing.
+ data = serialize_finding(finding)
+ data["id"] = derive_doc_drift_id(
+ data["file_path"], data["kind"], data["line_number"], data["target"]
+ )
+ findings.append(data)
+
+ by_target: dict[str, list[dict]] = {}
+ for reference in report.resolved_references:
+ by_target.setdefault(reference.target_path, []).append(
+ serialize_reference(reference)
+ )
+ for rows in by_target.values():
+ rows.sort(key=lambda r: (r["document"], r["line"], r["kind"]))
+
+ return {
+ "findings": findings,
+ "summary": summarize_findings(findings),
+ "references_by_target": {k: by_target[k] for k in sorted(by_target)},
+ "documents_scanned": report.documents_scanned,
+ "references_checked": report.references_checked,
+ "verdict_summary": dict(report.verdict_summary),
+ "anchor_renderer": report.anchor_renderer,
+ }
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 a22e0b1d8..0ec307ac9 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -38,6 +38,7 @@ from .dead_code import (
update_dead_code_status,
)
from .doc_drift import (
+ doc_drift_findings_stored,
doc_drift_references_stored,
get_doc_drift_findings,
get_doc_drift_references,
@@ -116,6 +117,7 @@ __all__ = [
"backfill_module_attribution",
"count_refactoring_suggestions",
"covered_source_files",
+ "doc_drift_findings_stored",
"doc_drift_references_stored",
"files_covered_by",
"finalize_performance_opportunities",
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 0a33710b8..71f52e520 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
@@ -11,6 +11,7 @@ from sqlalchemy import delete, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.analysis.doc_drift.constants import bucket_confidences
+from repowise.core.analysis.doc_drift.serialize import finding_dict, reference_dict
from ...models import DocDriftFinding, DocDriftReference
from .._shared import _BATCH_SIZE
@@ -321,24 +322,38 @@ async def doc_drift_references_stored(session: AsyncSession, repository_id: str)
return (await session.execute(stmt.limit(1))).scalar_one_or_none() is not None
+async def doc_drift_findings_stored(session: AsyncSession, repository_id: str) -> bool:
+ """Whether this repository has any stored finding at all.
+
+ The findings half of :func:`doc_drift_references_stored`, and it exists for
+ the case that one cannot cover: a repository whose documents resolve to
+ nothing has no reference rows, so the reference probe alone would report a
+ tree that *does* carry findings as never analysed. Either row anywhere is
+ proof the pass ran.
+
+ Asked only when a narrowed query came back empty, so the common case pays
+ nothing.
+ """
+ stmt = select(DocDriftFinding.id).where(
+ DocDriftFinding.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.
+ The row half of :func:`~repowise.core.analysis.doc_drift.serialize.reference_dict`,
+ which holds the key names and the reasons for them. Delegating rather than
+ restating is what makes a store-backed answer and a report-backed one the
+ same bytes.
"""
- out = {
- "document": row.document_path,
- "line": row.line_number,
- "kind": row.kind,
- }
- if row.section:
- out["section"] = row.section
- return out
+ return reference_dict(
+ document_path=row.document_path,
+ kind=row.kind,
+ line_number=row.line_number,
+ section=row.section,
+ )
def _decode_evidence(raw: str) -> list[str]:
@@ -358,35 +373,26 @@ def _decode_evidence(raw: str) -> list[str]:
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.
+ The row half of :func:`~repowise.core.analysis.doc_drift.serialize.finding_dict`,
+ which holds the keys and the rounding. All this adds is the JSON decode the
+ column needs and the report's list does not.
``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
+ return finding_dict(
+ file_path=row.file_path,
+ kind=row.kind,
+ line_number=row.line_number,
+ target=row.target,
+ confidence=row.confidence,
+ origin=row.origin,
+ reason=row.reason,
+ raw=row.raw,
+ context=row.context,
+ evidence=_decode_evidence(row.evidence_json) if evidence else None,
+ )
def summarize_confidence_rows(rows: list[DocDriftFinding]) -> dict:
@@ -394,5 +400,11 @@ def summarize_confidence_rows(rows: list[DocDriftFinding]) -> dict:
Calls the same function the analyzer does, so the summary a reader sees
cannot disagree with the one the pass computed.
+
+ Bucketed on the *rounded* confidence, which is the number every surface
+ displays and the one :func:`~repowise.core.analysis.doc_drift.serialize.finding_dict`
+ emits. Bucketing the raw value instead would put a stored 0.695 in
+ ``medium`` here and in ``high`` on any surface reading the serialized
+ dicts, beside a figure both render as 0.70.
"""
- return bucket_confidences(r.confidence for r in rows)
+ return bucket_confidences(round(r.confidence, 2) for r in rows)
diff --git a/packages/core/src/repowise/core/persistence/sql.py b/packages/core/src/repowise/core/persistence/sql.py
index 05437d200..a7938041d 100644
--- a/packages/core/src/repowise/core/persistence/sql.py
+++ b/packages/core/src/repowise/core/persistence/sql.py
@@ -23,3 +23,22 @@ def escape_like(value: str) -> str:
quietly returns rows the caller never asked for.
"""
return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
+
+
+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 check 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)
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 3a08ff3d9..53e0b5ada 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -49,6 +49,7 @@ from repowise.server.routers import (
coupling,
dead_code,
decisions,
+ doc_drift,
episodes,
external_systems,
feedback,
@@ -575,6 +576,7 @@ def create_app() -> FastAPI:
app.include_router(webhooks.router)
app.include_router(git.router)
app.include_router(dead_code.router)
+ app.include_router(doc_drift.router)
app.include_router(code_health.router)
app.include_router(coupling.router)
app.include_router(claude_md.router)
diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.py
index 7c22b61da..e2dcf2d3f 100644
--- a/packages/server/src/repowise/server/mcp_server/_helpers.py
+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py
@@ -21,7 +21,11 @@ from repowise.core.persistence.models import (
# Re-exported: MCP tools import their helpers from here, but the definition
# lives in core because the CRUD layer needs the same escaping.
-from repowise.core.persistence.sql import LIKE_ESCAPE, escape_like # noqa: F401
+from repowise.core.persistence.sql import ( # noqa: F401
+ LIKE_ESCAPE,
+ escape_like,
+ is_missing_table,
+)
from repowise.server.mcp_server import _state
_log = logging.getLogger("repowise.mcp")
@@ -718,25 +722,6 @@ 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_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index 5825535c8..78d44f570 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
@@ -23,6 +23,10 @@ from repowise.core.analysis.doc_drift.constants import (
UNAVAILABLE_NOT_COMPUTED,
UNAVAILABLE_READ_FAILED,
)
+from repowise.core.analysis.doc_drift.serialize import (
+ collapse_reference_sites,
+ documents_with_drift,
+)
from repowise.core.analysis.health.signals import file_signals
from repowise.core.ingestion.models import (
FILE_DEPENDENCY_EDGE_TYPES,
@@ -863,17 +867,9 @@ def _doc_reference_block(
) -> 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))
+ emitted = collapse_reference_sites(
+ [serialize_doc_drift_reference_row(row) for row in rows]
+ )
cap_collection(
block,
"references",
@@ -889,12 +885,11 @@ def _doc_reference_block(
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
- ]
+ # ``get_health(include=["doc_drift"])`` is for. Read off the uncapped list,
+ # or a document past the display cap reports as clean.
+ drifted = documents_with_drift(emitted, drift_by_document)
+ if drifted:
+ block["documents_with_drift"] = drifted
# Emitted on an empty answer too: that is the one most likely to be
# read as proof that nothing documents this file.
diff --git a/packages/server/src/repowise/server/routers/doc_drift.py b/packages/server/src/repowise/server/routers/doc_drift.py
new file mode 100644
index 000000000..db2610c7c
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/doc_drift.py
@@ -0,0 +1,216 @@
+"""/api/repos/{repo_id}/doc-drift — documentation drift endpoints.
+
+Two questions, in opposite directions. The findings endpoint asks which
+documents make assertions the repository no longer satisfies; the references
+endpoint asks which documents name one file, which is the question a reader
+about to change that file has.
+
+Every derivation here is a call into
+:mod:`repowise.core.analysis.doc_drift.serialize`. A rule computed in a handler
+is a rule the next consumer of this data re-implements, so the handlers select
+rows and hand them straight to the engine.
+"""
+
+from __future__ import annotations
+
+from fastapi import APIRouter, Depends, HTTPException, Query
+from sqlalchemy.exc import SQLAlchemyError
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.doc_drift.constants import (
+ DEFAULT_MIN_CONFIDENCE,
+ REFERENCE_BASIS,
+ UNAVAILABLE_NO_TABLE,
+ UNAVAILABLE_NOT_COMPUTED,
+ UNAVAILABLE_READ_FAILED,
+)
+from repowise.core.analysis.doc_drift.serialize import (
+ collapse_reference_sites,
+ documents_with_drift,
+ summarize_findings,
+)
+from repowise.core.persistence import crud
+from repowise.core.persistence.sql import is_missing_table
+from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas import (
+ DocDriftFindingResponse,
+ DocDriftReferencesResponse,
+ DocDriftResponse,
+)
+
+router = APIRouter(
+ tags=["doc-drift"],
+ dependencies=[Depends(verify_api_key)],
+)
+
+#: Rows one findings request may serve. The table is a defect list and is
+#: bounded by design, so this is a guard against a pathological tree rather
+#: than a paging scheme; ``summary.findings_total`` always counts the rest.
+_MAX_FINDINGS = 500
+
+#: Reference rows one reverse answer may serve. A widely-named file can be
+#: mentioned by hundreds of documents, and a reader scans the first screen.
+_MAX_REFERENCES = 200
+
+
+def _unavailable_reason(exc: Exception) -> str:
+ """Which refusal *exc* is, since "reindex" is wrong advice for a lock."""
+ return UNAVAILABLE_NO_TABLE if is_missing_table(exc) else UNAVAILABLE_READ_FAILED
+
+
+async def _require_repo(session: AsyncSession, repo_id: str) -> None:
+ """404 an unknown repository rather than reporting it as documented.
+
+ Every other refusal here is a 200 carrying a cause. This one is not: an id
+ that names nothing is a bad request, and answering it with a clean drift
+ report is the same lie the ``unavailable`` field exists to prevent.
+ """
+ if await crud.get_repository(session, repo_id) is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+
+ "/api/repos/{repo_id}/doc-drift",
+ response_model=DocDriftResponse,
+)
+async def list_doc_drift(
+ repo_id: str,
+ min_confidence: float = Query(DEFAULT_MIN_CONFIDENCE, ge=0.0, le=1.0),
+ kind: str | None = Query(None, description="Filter by reference class"),
+ document: str | None = Query(None, description="Only this document's findings"),
+ limit: int = Query(100, ge=1, le=_MAX_FINDINGS),
+ session: AsyncSession = Depends(get_db_session),
+) -> DocDriftResponse:
+ """Documents whose assertions the repository no longer satisfies.
+
+ The summary describes the same filters as the list, so the two cannot
+ disagree, and counts before ``limit`` so a capped page is never mistaken
+ for the repository.
+ """
+ await _require_repo(session, repo_id)
+
+ try:
+ rows = await crud.get_doc_drift_findings(
+ session,
+ repo_id,
+ file_path=document,
+ min_confidence=min_confidence,
+ )
+ # An empty answer is not a clean tree: the drift pass only runs when an
+ # update has work to do, so "upgraded, never analysed" looks exactly
+ # like "every document is correct". Both stores are probed, unfiltered,
+ # and only when the answer would otherwise be the strong one.
+ #
+ # Unfiltered is the whole point. Probing with ``rows`` would let a
+ # narrowing query answer a question about the index: a repository whose
+ # documents resolve to nothing has no reference rows, so
+ # ``?min_confidence=0.7`` over findings that all sit lower would report
+ # a tree holding findings as one nobody has ever checked.
+ computed = (
+ bool(rows)
+ or await crud.doc_drift_findings_stored(session, repo_id)
+ or await crud.doc_drift_references_stored(session, repo_id)
+ )
+ except (SQLAlchemyError, OSError, LookupError) as exc:
+ return DocDriftResponse(
+ findings=[],
+ findings_emitted=0,
+ summary=None,
+ unavailable=_unavailable_reason(exc),
+ )
+
+ if not computed:
+ return DocDriftResponse(
+ findings=[],
+ findings_emitted=0,
+ summary=None,
+ unavailable=UNAVAILABLE_NOT_COMPUTED,
+ )
+
+ if kind is not None:
+ rows = [row for row in rows if row.kind == kind]
+
+ serialized = [crud.serialize_doc_drift_row(row) for row in rows]
+ emitted = serialized[:limit]
+ return DocDriftResponse(
+ findings=[DocDriftFindingResponse.from_dict(f) for f in emitted],
+ findings_emitted=len(emitted),
+ summary=summarize_findings(serialized),
+ )
+
+
+ "/api/repos/{repo_id}/doc-drift/references",
+ response_model=DocDriftReferencesResponse,
+)
+async def doc_drift_references(
+ repo_id: str,
+ target: str = Query(..., description="Repo-relative path of the file"),
+ limit: int = Query(50, ge=1, le=_MAX_REFERENCES),
+ session: AsyncSession = Depends(get_db_session),
+) -> DocDriftReferencesResponse:
+ """Which documents name *target*, and which of them carry drift.
+
+ A reference says a document names a file the repository still has. It does
+ not say the document describes it, and ``documents_with_drift`` is a fact
+ about the document rather than about *target*: a drifted reference resolves
+ to nothing, so the store cannot express "this description of your file is
+ wrong" and must not be read as doing so.
+ """
+ await _require_repo(session, repo_id)
+
+ try:
+ rows = await crud.get_doc_drift_references(
+ session, repo_id, target_paths=[target]
+ )
+ stored = bool(rows) or await crud.doc_drift_references_stored(session, repo_id)
+ # Read whole, and only when there is something to match against: the
+ # findings table is a defect list and is bounded by design.
+ finding_rows = (
+ await crud.get_doc_drift_findings(session, repo_id) if rows else []
+ )
+ except (SQLAlchemyError, OSError, LookupError) as exc:
+ # Returns immediately, and must keep doing so: a failed statement
+ # poisons the transaction on Postgres, so anything issued on this
+ # session between here and the return would raise on its own.
+ return _empty_references(target, _unavailable_reason(exc))
+
+ if not stored:
+ return _empty_references(target, UNAVAILABLE_NOT_COMPUTED)
+
+ references = collapse_reference_sites(
+ [crud.serialize_doc_drift_reference_row(row) for row in rows]
+ )
+ drift_counts: dict[str, int] = {}
+ for finding in finding_rows:
+ drift_counts[finding.file_path] = drift_counts.get(finding.file_path, 0) + 1
+
+ emitted = references[:limit]
+ return DocDriftReferencesResponse(
+ target_path=target,
+ references=emitted,
+ references_emitted=len(emitted),
+ # Both counts are over the uncapped list: a document past the display
+ # cap still names the target and still carries its drift, and reading
+ # either off the capped list would report it as absent. That is why the
+ # emitted count is reported beside them rather than left to be inferred
+ # from the length of a list the caller cannot tell is complete.
+ references_total=len(references),
+ documents=len({r["document"] for r in references}),
+ documents_with_drift=documents_with_drift(references, drift_counts),
+ references_basis=REFERENCE_BASIS,
+ )
+
+
+def _empty_references(target: str, reason: str) -> DocDriftReferencesResponse:
+ """A refusal that still carries what a reference row would have claimed."""
+ return DocDriftReferencesResponse(
+ target_path=target,
+ references=[],
+ references_emitted=0,
+ references_total=0,
+ documents=0,
+ documents_with_drift=[],
+ references_basis=REFERENCE_BASIS,
+ unavailable=reason,
+ )
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 9bd002d8a..f33e5f8c6 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -98,6 +98,14 @@ from .decisions import (
DecisionSourceState,
DecisionStatusUpdate,
)
+from .doc_drift import (
+ DocDriftDocumentDriftResponse,
+ DocDriftFindingResponse,
+ DocDriftReferenceResponse,
+ DocDriftReferencesResponse,
+ DocDriftResponse,
+ DocDriftSummaryResponse,
+)
from .episodes import (
EpisodeCountsResponse,
EpisodeDetail,
@@ -377,6 +385,12 @@ __all__ = [
"DirectRiskEntry",
"DistillSavingsGroup",
"DistillSavingsResponse",
+ "DocDriftDocumentDriftResponse",
+ "DocDriftFindingResponse",
+ "DocDriftReferenceResponse",
+ "DocDriftReferencesResponse",
+ "DocDriftResponse",
+ "DocDriftSummaryResponse",
"EgoGraphResponse",
"EpisodeCountsResponse",
"EpisodeDetail",
diff --git a/packages/server/src/repowise/server/schemas/doc_drift.py b/packages/server/src/repowise/server/schemas/doc_drift.py
new file mode 100644
index 000000000..c8e736bc6
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/doc_drift.py
@@ -0,0 +1,147 @@
+"""Documentation drift response models.
+
+The wire shape, and the only place it is declared. Each model is built from a
+dict the engine produced rather than from an ORM row, so the route serves what
+:mod:`repowise.core.analysis.doc_drift.serialize` emits without a second
+hand-maintained mapping in between.
+
+``unavailable`` is a first-class field on both responses and not an HTTP error.
+"The drift pass has not run here" is an answer about the index, not a failure
+of the request, and a client that received a 4xx would have to guess which of
+the three causes it was. An empty list with no ``unavailable`` is the strong
+claim that the tree is clean, and only a populated store can support it.
+"""
+
+from __future__ import annotations
+
+from typing import Literal
+
+from pydantic import BaseModel
+
+from repowise.core.analysis.doc_drift.constants import (
+ UNAVAILABLE_NO_TABLE,
+ UNAVAILABLE_NOT_COMPUTED,
+ UNAVAILABLE_READ_FAILED,
+)
+from repowise.core.analysis.doc_drift.serialize import derive_doc_drift_id
+
+#: Why a drift answer could not be given, from the engine's own vocabulary so
+#: the literal cannot be renamed on one side alone.
+DocDriftUnavailable = Literal[
+ UNAVAILABLE_NOT_COMPUTED, # type: ignore[valid-type]
+ UNAVAILABLE_NO_TABLE, # type: ignore[valid-type]
+ UNAVAILABLE_READ_FAILED, # type: ignore[valid-type]
+]
+
+
+class DocDriftFindingResponse(BaseModel):
+ """One assertion a document makes that the repository no longer satisfies.
+
+ ``file_path`` is the *document* to edit, never the target it names. A
+ reader who reads it as the broken file has been told the opposite of the
+ truth, which is why the field keeps the name every other drift surface
+ gives it.
+ """
+
+ #: Stable across stores and rebuilds; see :func:`derive_doc_drift_id`.
+ id: str
+ file_path: str
+ line_number: int
+ kind: str
+ target: str
+ confidence: float
+ origin: str
+ reason: str
+ raw: str
+ context: str
+ evidence: list[str]
+
+ @classmethod
+ def from_dict(cls, data: dict) -> DocDriftFindingResponse:
+ """One serialized finding, given the id the store cannot hold."""
+ return cls(
+ id=derive_doc_drift_id(
+ data["file_path"],
+ data["kind"],
+ data["line_number"],
+ data["target"],
+ ),
+ file_path=data["file_path"],
+ line_number=data["line_number"],
+ kind=data["kind"],
+ target=data["target"],
+ confidence=data["confidence"],
+ origin=data["origin"],
+ reason=data["reason"],
+ raw=data["raw"],
+ context=data["context"],
+ evidence=data.get("evidence", []),
+ )
+
+
+class DocDriftSummaryResponse(BaseModel):
+ """The rollup above the list, computed server-side over the same rows.
+
+ ``findings_total`` counts every finding matching the query, including any
+ the display cap left out, so a client cannot recompute a page as if it were
+ the repository.
+ """
+
+ findings_total: int
+ documents: int
+ confidence: dict[str, int]
+ by_kind: dict[str, int]
+ #: What the counts do and do not cover. No surface may show them without it.
+ findings_basis: str
+
+
+class DocDriftResponse(BaseModel):
+ """Findings for a repository, with the rollup that makes them legible."""
+
+ findings: list[DocDriftFindingResponse]
+ #: Rows served after ``limit``; below ``summary.findings_total`` when capped.
+ findings_emitted: int
+ summary: DocDriftSummaryResponse | None
+ unavailable: DocDriftUnavailable | None = None
+
+
+class DocDriftReferenceResponse(BaseModel):
+ """A document that names a file the repository still has.
+
+ Deliberately weaker than a finding: it does not claim the document
+ describes the file, or that its prose is current.
+ """
+
+ document: str
+ line: int
+ kind: str
+ section: str = ""
+
+
+class DocDriftDocumentDriftResponse(BaseModel):
+ """A naming document that carries drift somewhere in it.
+
+ ``findings`` counts the whole document, not assertions about the file that
+ was asked about. A drifted reference resolves to nothing, so no row here
+ can say a document's description of that file is wrong.
+ """
+
+ document: str
+ findings: int
+
+
+class DocDriftReferencesResponse(BaseModel):
+ """Which documents name one file: the reverse view, over HTTP."""
+
+ target_path: str
+ references: list[DocDriftReferenceResponse]
+ #: Rows served after the cap; below ``references_total`` when capped.
+ references_emitted: int
+ #: Every reference to the target, so a capped list cannot read as complete.
+ references_total: int
+ #: Distinct documents naming the target, before any display cap.
+ documents: int
+ documents_with_drift: list[DocDriftDocumentDriftResponse]
+ #: What a reference row claims, and what its absence does not prove.
+ references_basis: str
+ unavailable: DocDriftUnavailable | None = None
diff --git a/packages/types/package.json b/packages/types/package.json
index 54e0f0dfc..1e4b2ef96 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -15,6 +15,7 @@
"./decisions": "./src/decisions.ts",
"./episodes": "./src/episodes.ts",
"./dead-code": "./src/dead-code.ts",
+ "./doc-drift": "./src/doc-drift.ts",
"./symbols": "./src/symbols.ts",
"./chat": "./src/chat.ts",
"./workspace": "./src/workspace.ts",
diff --git a/packages/types/src/doc-drift.ts b/packages/types/src/doc-drift.ts
new file mode 100644
index 000000000..1a76f7eb5
--- /dev/null
+++ b/packages/types/src/doc-drift.ts
@@ -0,0 +1,184 @@
+/**
+ * Canonical documentation-drift types.
+ *
+ * Canonical source: the engine's `DocDriftResponse` / `DocDriftReferencesResponse`
+ * (`packages/server/src/repowise/server/schemas/doc_drift.py`), emitted verbatim
+ * by the route. Nothing here is a normalisation of the wire: a client that
+ * reshapes this contract is a client that recomputes the summary, and the
+ * summary is served precisely so it cannot be recomputed from a page.
+ *
+ * The vocabulary carries a claim, and the claims are not the same size:
+ * a *finding* says a document asserts something the repository no longer
+ * satisfies, and is filed against the document. A *reference* says only that a
+ * document names a file the repository still has. It never says the document
+ * describes that file.
+ */
+
+/**
+ * Why a drift answer could not be given.
+ *
+ * Not an error state. `not_computed` means the drift pass has never run on
+ * this index, which must not render as a repository with clean documentation;
+ * `index_predates_doc_drift` means the index is older than the store;
+ * `drift_read_failed` is anything else, and is separate because "reindex" is
+ * the wrong advice for a locked database.
+ *
+ * Mirrors `UNAVAILABLE_NOT_COMPUTED` / `UNAVAILABLE_NO_TABLE` /
+ * `UNAVAILABLE_READ_FAILED` in `core/analysis/doc_drift/constants.py`, pinned
+ * by `tests/unit/doc_drift/test_ts_contract_parity.py`.
+ */
+export type DocDriftUnavailable =
+ | "not_computed"
+ | "index_predates_doc_drift"
+ | "drift_read_failed";
+
+/**
+ * The reference classes the detector ships.
+ *
+ * `symbol` is deliberately absent: it was measured at a 55-69% flag rate and
+ * killed, because backticks in technical prose mean "this is a literal token",
+ * not "this is a code symbol".
+ */
+export type DocDriftKind = "path" | "link" | "anchor" | "command";
+
+/**
+ * The one set of confidence boundaries, mirroring the engine.
+ *
+ * `HIGH` is `HIGH_CONFIDENCE_THRESHOLD` and `MEDIUM` is
+ * `REVIEW_CONFIDENCE_THRESHOLD` in `core/analysis/doc_drift/constants.py`,
+ * which are themselves held equal to dead code's boundaries so that "high"
+ * means one thing to a reader comparing the two reports.
+ *
+ * Duplicated across languages rather than derived, and pinned by a parity
+ * test, because three surfaces disagreeing about where "high" starts is a
+ * failure this repository has already had once
+ * (`tests/unit/dead_code/test_confidence_parity.py`).
+ */
+export const DOC_DRIFT_CONFIDENCE = {
+ /** At or above this, a finding is near-certain. */
+ HIGH: 0.7,
+ /** The default floor; below it findings are not fetched. */
+ MEDIUM: 0.4,
+} as const;
+
+/** Which tier a confidence falls in, using the boundaries above. */
+export function docDriftConfidenceTier(confidence: number): "high" | "medium" | "low" {
+ if (confidence >= DOC_DRIFT_CONFIDENCE.HIGH) return "high";
+ if (confidence >= DOC_DRIFT_CONFIDENCE.MEDIUM) return "medium";
+ return "low";
+}
+
+/**
+ * What each reference class is, in a reader's words.
+ *
+ * The slugs are an API vocabulary, not English: a table column headed `anchor`
+ * tells a reader nothing about a heading link whose heading was renamed.
+ * Keyed on every value `DocDriftKind` can take, pinned by the same parity test.
+ */
+export const DOC_DRIFT_KIND_LABELS: Record<DocDriftKind, string> = {
+ path: "File path",
+ link: "Link",
+ anchor: "Heading link",
+ command: "Command",
+};
+
+/** Label for one reference class, falling back to the raw slug. */
+export function docDriftKindLabel(kind: string): string {
+ return DOC_DRIFT_KIND_LABELS[kind as DocDriftKind] ?? kind;
+}
+
+export interface DocDriftFinding {
+ /**
+ * Stable across stores and rebuilds, derived from
+ * `(file_path, kind, line_number, target)`. The row's own primary key is an
+ * autoincrement integer and is re-minted whenever a store is rebuilt, so it
+ * is this id that a client keys triage on.
+ */
+ id: string;
+ /**
+ * The *document* that is wrong, and the file a reader has to edit. Never the
+ * target it names. Rendering this as the broken code file tells the reader
+ * the opposite of the truth.
+ */
+ file_path: string;
+ line_number: number;
+ kind: string;
+ /** What the document claims exists. */
+ target: string;
+ confidence: number;
+ /** Which named resolution strategy produced this. */
+ origin: string;
+ /** One human sentence. */
+ reason: string;
+ /** The reference exactly as written. */
+ raw: string;
+ /** The source line, trimmed, so a finding can be judged without opening the file. */
+ context: string;
+ /** Lines a reader can check for themselves. */
+ evidence: string[];
+}
+
+/**
+ * The rollup above a findings list, computed server-side over the same rows.
+ *
+ * `findings_total` counts every finding matching the query, including any the
+ * display cap left out, so a client must not recompute these numbers from the
+ * page it holds.
+ */
+export interface DocDriftSummary {
+ findings_total: number;
+ /** Distinct documents carrying at least one finding. */
+ documents: number;
+ confidence: Record<string, number>;
+ by_kind: Record<string, number>;
+ /**
+ * What the counts do and do not cover. Most references in a real tree are
+ * uncheckable by design, so no surface may show the counts without it.
+ */
+ findings_basis: string;
+}
+
+export interface DocDriftResponse {
+ findings: DocDriftFinding[];
+ /** Rows served after the cap; below `summary.findings_total` when capped. */
+ findings_emitted: number;
+ /** Null exactly when `unavailable` is set. */
+ summary: DocDriftSummary | null;
+ unavailable: DocDriftUnavailable | null;
+}
+
+/** A document that names a file the repository still has. */
+export interface DocDriftReference {
+ document: string;
+ line: number;
+ kind: string;
+ /** The enclosing heading trail, so a reader can find the passage. */
+ section?: string;
+}
+
+/**
+ * A naming document that carries drift somewhere in it.
+ *
+ * `findings` counts the whole document. A drifted reference resolves to
+ * nothing, so this can never mean "this document's description of your file is
+ * wrong", and a surface that words it that way is lying.
+ */
+export interface DocDriftDocumentDrift {
+ document: string;
+ findings: number;
+}
+
+export interface DocDriftReferencesResponse {
+ target_path: string;
+ references: DocDriftReference[];
+ /** Rows served after the cap; below `references_total` when capped. */
+ references_emitted: number;
+ /** Every reference to the target, so a capped list cannot read as complete. */
+ references_total: number;
+ /** Distinct documents naming the target, before any display cap. */
+ documents: number;
+ documents_with_drift: DocDriftDocumentDrift[];
+ /** What a reference claims, and what its absence does not prove. */
+ references_basis: string;
+ unavailable: DocDriftUnavailable | null;
+}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index cc6f347cf..7e485e291 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -1026,6 +1026,88 @@ export interface DistillSavingsResponse {
reread_tokens_est?: number;
}
+/**
+ * A naming document that carries drift somewhere in it.
+ *
+ * ``findings`` counts the whole document, not assertions about the file that
+ * was asked about. A drifted reference resolves to nothing, so no row here
+ * can say a document's description of that file is wrong.
+ */
+export interface DocDriftDocumentDriftResponse {
+ document: string;
+ findings: number;
+}
+
+/**
+ * One assertion a document makes that the repository no longer satisfies.
+ *
+ * ``file_path`` is the *document* to edit, never the target it names. A
+ * reader who reads it as the broken file has been told the opposite of the
+ * truth, which is why the field keeps the name every other drift surface
+ * gives it.
+ */
+export interface DocDriftFindingResponse {
+ id: string;
+ file_path: string;
+ line_number: number;
+ kind: string;
+ target: string;
+ confidence: number;
+ origin: string;
+ reason: string;
+ raw: string;
+ context: string;
+ evidence: string[];
+}
+
+/**
+ * A document that names a file the repository still has.
+ *
+ * Deliberately weaker than a finding: it does not claim the document
+ * describes the file, or that its prose is current.
+ */
+export interface DocDriftReferenceResponse {
+ document: string;
+ line: number;
+ kind: string;
+ section?: string;
+}
+
+/** Which documents name one file: the reverse view, over HTTP. */
+export interface DocDriftReferencesResponse {
+ target_path: string;
+ references: DocDriftReferenceResponse[];
+ references_emitted: number;
+ references_total: number;
+ documents: number;
+ documents_with_drift: DocDriftDocumentDriftResponse[];
+ references_basis: string;
+ unavailable?: "not_computed" | "index_predates_doc_drift" | "drift_read_failed" | null;
+}
+
+/** Findings for a repository, with the rollup that makes them legible. */
+export interface DocDriftResponse {
+ findings: DocDriftFindingResponse[];
+ findings_emitted: number;
+ summary: DocDriftSummaryResponse | null;
+ unavailable?: "not_computed" | "index_predates_doc_drift" | "drift_read_failed" | null;
+}
+
+/**
+ * The rollup above the list, computed server-side over the same rows.
+ *
+ * ``findings_total`` counts every finding matching the query, including any
+ * the display cap left out, so a client cannot recompute a page as if it were
+ * the repository.
+ */
+export interface DocDriftSummaryResponse {
+ findings_total: number;
+ documents: number;
+ confidence: Record<string, number>;
+ by_kind: Record<string, number>;
+ findings_basis: string;
+}
+
export interface EgoGraphResponse {
nodes: GraphNodeResponse[];
links: GraphEdgeResponse[];
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 0a8252cdd..2db796006 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -15,6 +15,7 @@ export * from "./docs.js";
export * from "./decisions.js";
export * from "./episodes.js";
export * from "./dead-code.js";
+export * from "./doc-drift.js";
export * from "./symbols.js";
export * from "./chat.js";
export * from "./workspace.js";
diff --git a/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsx b/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsx
new file mode 100644
index 000000000..0f0ed654b
--- /dev/null
+++ b/packages/ui/__tests__/doc-drift/doc-drift-view.test.tsx
@@ -0,0 +1,329 @@
+import { describe, it, expect, vi } from "vitest";
+import { render, screen, fireEvent, waitFor, within } from "@testing-library/react";
+import { SWRConfig } from "swr";
+import type { ReactElement } from "react";
+
+import { DocDriftView } from "../../src/doc-drift/doc-drift-view.js";
+import type { DocDriftAdapter } from "../../src/doc-drift/doc-drift-adapter.js";
+import type {
+ DocDriftFinding,
+ DocDriftResponse,
+} from "@repowise-dev/types/doc-drift";
+
+// jsdom has no layout engine; the shared table's virtualization path reads one.
+class RO {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+vi.stubGlobal("ResizeObserver", RO);
+
+/**
+ * The findings table stacks into a card list beside the real table and lets CSS
+ * pick one. jsdom applies no CSS, so a cell matches in both; scope by caption.
+ */
+const TABLE = { name: /Documentation assertions/i };
+
+const BASIS =
+ "Covers only references this detector can resolve; uncheckable ones are neither counted nor reported.";
+
+const FINDINGS: DocDriftFinding[] = [
+ {
+ id: "f1",
+ file_path: "docs/architecture.md",
+ line_number: 42,
+ kind: "path",
+ target: "src/auth.py",
+ confidence: 0.9,
+ origin: "path_no_candidate",
+ reason: "No file matches this path.",
+ raw: "src/auth.py",
+ context: "The resolver lives in src/auth.py.",
+ evidence: [],
+ },
+ {
+ id: "f2",
+ file_path: "docs/cli.md",
+ line_number: 7,
+ kind: "anchor",
+ target: "docs/cli.md#usage",
+ confidence: 0.5,
+ origin: "anchor_no_heading",
+ reason: "No heading slugs to this fragment.",
+ raw: "#usage",
+ context: "See [usage](#usage).",
+ evidence: [],
+ },
+];
+
+function response(over: Partial<DocDriftResponse> = {}): DocDriftResponse {
+ return {
+ findings: FINDINGS,
+ findings_emitted: FINDINGS.length,
+ summary: {
+ findings_total: FINDINGS.length,
+ documents: 2,
+ confidence: { high: 1, medium: 1, low: 0 },
+ by_kind: { anchor: 1, path: 1 },
+ findings_basis: BASIS,
+ },
+ unavailable: null,
+ ...over,
+ };
+}
+
+/** The shape the engine returns when it will not answer: a cause, no summary. */
+function refusal(reason: string): DocDriftResponse {
+ return response({
+ findings: [],
+ findings_emitted: 0,
+ summary: null,
+ unavailable: reason as DocDriftResponse["unavailable"],
+ });
+}
+
+function makeAdapter(over: Partial<DocDriftAdapter> = {}): DocDriftAdapter {
+ return {
+ cacheKey: "repo-1",
+ listFindings: vi.fn(async () => response()),
+ documentHref: (path, line) =>
+ `/repos/repo-1/files/${path}${line ? `#L${line}` : ""}`,
+ navigate: vi.fn(),
+ ...over,
+ };
+}
+
+function renderView(node: ReactElement) {
+ return render(
+ <SWRConfig value={{ provider: () => new Map(), dedupingInterval: 0 }}>
+ {node}
+ </SWRConfig>,
+ );
+}
+
+describe("DocDriftView", () => {
+ it("leads with the count and names the documents to edit", async () => {
+ renderView(<DocDriftView adapter={makeAdapter()} />);
+
+ const table = await screen.findByRole("table", TABLE);
+ expect(within(table).getByText(/docs\/architecture\.md/)).toBeTruthy();
+ expect(within(table).getByText("src/auth.py")).toBeTruthy();
+ });
+
+ it("never shows a count without saying what it covers", async () => {
+ // Most references in a real tree are uncheckable; a bare figure claims a
+ // coverage this detector does not have.
+ renderView(<DocDriftView adapter={makeAdapter()} />);
+ expect(await screen.findByText(new RegExp(BASIS.slice(0, 40)))).toBeTruthy();
+ });
+
+ it("refuses rather than reporting an unchecked repository as clean", async () => {
+ const adapter = makeAdapter({
+ listFindings: vi.fn(async () =>
+ refusal("not_computed"),
+ ),
+ });
+ renderView(<DocDriftView adapter={adapter} />);
+
+ expect(
+ await screen.findByText(/has not been checked yet/i),
+ ).toBeTruthy();
+ // The one thing it must not render: an empty table reading as a clean tree.
+ expect(screen.queryByRole("table", TABLE)).toBeNull();
+ expect(screen.queryByText(/No documentation drift found/i)).toBeNull();
+ });
+
+ it("tells a stale index apart from a failed read", async () => {
+ const adapter = makeAdapter({
+ listFindings: vi.fn(async () =>
+ refusal("drift_read_failed"),
+ ),
+ });
+ renderView(<DocDriftView adapter={adapter} />);
+
+ // "Reindex" is wrong advice for a locked database, so the copy must not
+ // give it here.
+ const message = await screen.findByText(/Re-indexing will not help/i);
+ expect(message).toBeTruthy();
+ });
+
+ it("offers a way out of a transient read failure", async () => {
+ // Nothing revalidates on focus, so without this the tab is stranded until
+ // a full page reload.
+ const listFindings = vi
+ .fn()
+ .mockResolvedValueOnce(
+ refusal("drift_read_failed"),
+ )
+ .mockResolvedValue(response());
+ renderView(<DocDriftView adapter={makeAdapter({ listFindings })} />);
+
+ fireEvent.click(await screen.findByRole("button", { name: /Try again/i }));
+ expect(await screen.findByRole("table", TABLE)).toBeTruthy();
+ });
+
+ it("does not offer a retry where retrying cannot change the answer", async () => {
+ const adapter = makeAdapter({
+ listFindings: vi.fn(async () =>
+ refusal("index_predates_doc_drift"),
+ ),
+ });
+ renderView(<DocDriftView adapter={adapter} />);
+
+ await screen.findByText(/predates documentation drift/i);
+ expect(screen.queryByRole("button", { name: /Try again/i })).toBeNull();
+ });
+
+ it("degrades rather than unmounting on a cause it does not know", async () => {
+ const adapter = makeAdapter({
+ listFindings: vi.fn(async () =>
+ // A newer engine may grow the vocabulary; a hard lookup would take
+ // the whole tab down with it.
+ refusal("some_future_cause"),
+ ),
+ });
+ renderView(<DocDriftView adapter={adapter} />);
+
+ expect(
+ await screen.findByText(/documentation drift is unavailable/i),
+ ).toBeTruthy();
+ });
+
+ it("reports a genuinely clean repository as clean", async () => {
+ const adapter = makeAdapter({
+ listFindings: vi.fn(async () =>
+ response({
+ findings: [],
+ findings_emitted: 0,
+ summary: {
+ findings_total: 0,
+ documents: 0,
+ confidence: { high: 0, medium: 0, low: 0 },
+ by_kind: {},
+ findings_basis: BASIS,
+ },
+ }),
+ ),
+ });
+ renderView(<DocDriftView adapter={adapter} />);
+
+ expect(await screen.findByText(/No documentation drift found/i)).toBeTruthy();
+ });
+
+ it("says so when the page is a slice of the repository", async () => {
+ const adapter = makeAdapter({
+ listFindings: vi.fn(async () =>
+ response({
+ findings_emitted: 2,
+ summary: { ...response().summary!, findings_total: 40 },
+ }),
+ ),
+ });
+ renderView(<DocDriftView adapter={adapter} />);
+
+ expect(await screen.findByText(/Showing 2 of 40 findings/i)).toBeTruthy();
+ });
+
+ it("narrows the summary with the rows, not just the rows", async () => {
+ const listFindings = vi.fn(async (opts?: { min_confidence?: number }) =>
+ opts?.min_confidence === 0.7
+ ? response({
+ findings: [FINDINGS[0]!],
+ findings_emitted: 1,
+ summary: {
+ findings_total: 1,
+ documents: 1,
+ confidence: { high: 1, medium: 0, low: 0 },
+ by_kind: { path: 1 },
+ findings_basis: BASIS,
+ },
+ })
+ : response(),
+ );
+ renderView(<DocDriftView adapter={makeAdapter({ listFindings })} />);
+
+ await screen.findByRole("table", TABLE);
+ fireEvent.change(screen.getByLabelText(/Minimum confidence/i), {
+ target: { value: "0.7" },
+ });
+
+ await waitFor(() =>
+ expect(listFindings).toHaveBeenCalledWith(
+ expect.objectContaining({ min_confidence: 0.7 }),
+ ),
+ );
+ });
+
+ it("keeps the reference filter clearable after it is used", async () => {
+ // A selected filter that erases its own alternatives is a dead end.
+ renderView(<DocDriftView adapter={makeAdapter()} />);
+ await screen.findByRole("table", TABLE);
+
+ const select = screen.getByLabelText(/Reference class/i);
+ fireEvent.change(select, { target: { value: "path" } });
+
+ await waitFor(() => {
+ const options = within(select as HTMLSelectElement).getAllByRole("option");
+ expect(options.length).toBeGreaterThan(1);
+ });
+ });
+
+ it("does not offer a reference filter a repository cannot use", async () => {
+ const adapter = makeAdapter({
+ listFindings: vi.fn(async () =>
+ response({
+ findings: [FINDINGS[0]!],
+ findings_emitted: 1,
+ summary: { ...response().summary!, by_kind: { path: 1 } },
+ }),
+ ),
+ });
+ renderView(<DocDriftView adapter={adapter} />);
+
+ await screen.findByRole("table", TABLE);
+ expect(screen.queryByLabelText(/Reference class/i)).toBeNull();
+ });
+
+ it("shows the failure rather than an empty list when the fetch fails", async () => {
+ const adapter = makeAdapter({
+ listFindings: vi.fn(async () => {
+ throw new Error("boom");
+ }),
+ });
+ renderView(<DocDriftView adapter={adapter} />);
+
+ expect(
+ await screen.findByText(/Couldn't load documentation drift/i),
+ ).toBeTruthy();
+ });
+
+ it("lets a host supply its own failure card", async () => {
+ const adapter = makeAdapter({
+ listFindings: vi.fn(async () => {
+ throw new Error("boom");
+ }),
+ });
+ renderView(
+ <DocDriftView
+ adapter={adapter}
+ renderError={() => <p>Sign in to see this</p>}
+ />,
+ );
+
+ expect(await screen.findByText("Sign in to see this")).toBeTruthy();
+ });
+
+ it("opens the document, not the file it names", async () => {
+ const navigate = vi.fn();
+ renderView(<DocDriftView adapter={makeAdapter({ navigate })} />);
+
+ const table = await screen.findByRole("table", TABLE);
+ fireEvent.click(within(table).getByText(/docs\/architecture\.md/));
+
+ await waitFor(() =>
+ expect(navigate).toHaveBeenCalledWith(
+ "/repos/repo-1/files/docs/architecture.md#L42",
+ ),
+ );
+ });
+});
diff --git a/packages/ui/__tests__/types-alias-parity.test.ts b/packages/ui/__tests__/types-alias-parity.test.ts
new file mode 100644
index 000000000..54271b00c
--- /dev/null
+++ b/packages/ui/__tests__/types-alias-parity.test.ts
@@ -0,0 +1,50 @@
+// @vitest-environment node
+/**
+ * Every `@repowise-dev/types` subpath resolves under vitest.
+ *
+ * `vitest.config.ts` hand-mirrors the types package's `exports` map, because
+ * the alias order matters and a bare entry would shadow the subpaths. A
+ * hand-mirrored list drifts, and it drifts silently: a missing alias only
+ * breaks the day a test transitively *value*-imports that subpath, since
+ * type-only imports are erased before the resolver ever sees them.
+ *
+ * This is the notice. Adding a subpath to the types package and not to the
+ * alias map fails here rather than in whichever unrelated suite imports it
+ * next.
+ */
+import { existsSync } from "node:fs";
+import { dirname, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { describe, expect, it } from "vitest";
+
+import manifest from "../../types/package.json" with { type: "json" };
+import config from "../vitest.config";
+
+const here = dirname(fileURLToPath(import.meta.url));
+
+function aliasMap(): Record<string, string> {
+ return (config.resolve?.alias ?? {}) as Record<string, string>;
+}
+
+describe("types subpath aliases", () => {
+ it("covers every subpath the types package publishes", () => {
+ const declared = Object.keys(manifest.exports as Record<string, string>)
+ .filter((key) => key !== "." && !key.includes("*"))
+ .map((key) => `@repowise-dev/types${key.slice(1)}`);
+ const aliased = new Set(Object.keys(aliasMap()));
+ expect(declared.filter((name) => !aliased.has(name))).toEqual([]);
+ });
+
+ it("points every alias at a file that exists", () => {
+ const missing = Object.entries(aliasMap()).filter(
+ ([, target]) => !existsSync(resolve(here, target)),
+ );
+ expect(missing).toEqual([]);
+ });
+
+ it("keeps the bare entry last so it cannot shadow a subpath", () => {
+ const keys = Object.keys(aliasMap());
+ expect(keys.indexOf("@repowise-dev/types")).toBe(keys.length - 1);
+ });
+});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 45f61cb0a..9f5fabe21 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -33,6 +33,8 @@
"./commits/*": "./src/commits/*.tsx",
"./dead-code": "./src/dead-code/index.ts",
"./dead-code/*": "./src/dead-code/*.tsx",
+ "./doc-drift": "./src/doc-drift/index.ts",
+ "./doc-drift/*": "./src/doc-drift/*.tsx",
"./health": "./src/health/index.ts",
"./health/ai-prompt-builder": "./src/health/ai-prompt-builder.ts",
"./health/tokens": "./src/health/tokens.ts",
diff --git a/packages/ui/src/doc-drift/doc-drift-adapter.ts b/packages/ui/src/doc-drift/doc-drift-adapter.ts
new file mode 100644
index 000000000..59afd0ff4
--- /dev/null
+++ b/packages/ui/src/doc-drift/doc-drift-adapter.ts
@@ -0,0 +1,53 @@
+import type {
+ DocDriftReferencesResponse,
+ DocDriftResponse,
+} from "@repowise-dev/types/doc-drift";
+
+/**
+ * App-injected data + navigation for the shared {@link DocDriftView}.
+ *
+ * The view owns the composition — the lede, the confidence split, the filter,
+ * the findings table, and every refusal and empty state. The host supplies
+ * *how* to fetch and *where* document links go, so web and hosted render the
+ * same view from one source.
+ *
+ * Fetch methods are keyed off `cacheKey` for SWR, so a page-level fetch that
+ * shares a key dedupes onto the same request.
+ *
+ * Only the two required members are ones every host can honestly implement.
+ * Dead code made `analyze()` required and hosted had to implement it as a
+ * deliberate throw; what a host cannot do is optional here, and the view
+ * drops the affordance rather than offering a control that explains its own
+ * impossibility after it is pressed.
+ */
+export interface DocDriftAdapter {
+ /** Seeds the view's SWR cache keys — keep it stable per repo/snapshot. */
+ cacheKey: string;
+
+ /**
+ * Findings, with the summary the server computed over the same query.
+ *
+ * Never recompute the summary from `findings`: that list is capped by
+ * `limit` while `summary.findings_total` counts the whole query, and a
+ * client that recomputes reports the page it holds as the repository.
+ */
+ listFindings(opts?: {
+ min_confidence?: number;
+ kind?: string;
+ limit?: number;
+ }): Promise<DocDriftResponse>;
+
+ /** Build an href to a document, at a line when the host supports it. */
+ documentHref(path: string, line?: number): string;
+
+ /**
+ * Which documents name one file. Optional: a host serving drift from a
+ * pre-computed artifact may carry only the findings half, and the view then
+ * omits the affordances that would need it.
+ */
+ listReferences?(target: string): Promise<DocDriftReferencesResponse>;
+
+ /** Navigate to an href (host wires this to its router). Optional: a host
+ * whose document links are plain anchors does not need it. */
+ navigate?(href: string): void;
+}
diff --git a/packages/ui/src/doc-drift/doc-drift-lede.tsx b/packages/ui/src/doc-drift/doc-drift-lede.tsx
new file mode 100644
index 000000000..3b5c2e7ab
--- /dev/null
+++ b/packages/ui/src/doc-drift/doc-drift-lede.tsx
@@ -0,0 +1,201 @@
+/**
+ * The Doc drift tab's opening read.
+ *
+ * The figure is the count of findings, because unlike dead code there is no
+ * second unit here: a drift finding is one sentence in one document that is no
+ * longer true, and lines would say nothing. The document count sits beside it
+ * because it is what turns the figure into work — twelve findings across two
+ * documents is an afternoon, twelve across twelve is a sweep.
+ *
+ * The basis sentence is not decoration and is not optional. Most references in
+ * a real tree are uncheckable by design, so a bare count implies a coverage
+ * this detector does not have. It is rendered as prose next to the figure
+ * rather than as a footnote for exactly that reason.
+ */
+
+import {
+ DOC_DRIFT_CONFIDENCE,
+ docDriftKindLabel,
+ type DocDriftSummary,
+} from "@repowise-dev/types/doc-drift";
+
+import { PageLede } from "../shared/page-lede";
+import { StatRibbon, type RibbonStat } from "../stats/stat-ribbon";
+import { formatNumber } from "../lib/format";
+
+export interface DocDriftLedeProps {
+ summary: DocDriftSummary;
+ /** Rows on screen, when fewer than the summary counts. */
+ shownCount?: number;
+ truncated?: boolean;
+}
+
+/** "a, b and c", built rather than interpolated so one kind does not trail "and". */
+function joinPhrases(parts: string[]): string {
+ if (parts.length <= 1) return parts[0] ?? "";
+ return `${parts.slice(0, -1).join(", ")} and ${parts[parts.length - 1]}`;
+}
+
+export function DocDriftLede({
+ summary,
+ shownCount,
+ truncated = false,
+}: DocDriftLedeProps) {
+ const high = summary.confidence.high ?? 0;
+ const medium = summary.confidence.medium ?? 0;
+ const low = summary.confidence.low ?? 0;
+ const graded = high + medium + low;
+
+ const kinds = Object.entries(summary.by_kind)
+ .filter(([, count]) => count > 0)
+ .sort((a, b) => b[1] - a[1]);
+
+ const stats: RibbonStat[] = [
+ {
+ label: "Findings",
+ value: formatNumber(summary.findings_total),
+ ...(truncated && shownCount != null
+ ? { sub: `${formatNumber(shownCount)} on this page` }
+ : {}),
+ hint: "One assertion a document makes that the repository no longer satisfies.",
+ },
+ {
+ label: "Documents",
+ value: formatNumber(summary.documents),
+ sub: "carry at least one",
+ hint: "The files you would edit. A finding is filed against the document, never against the file it names.",
+ },
+ {
+ label: "Near-certain",
+ value: formatNumber(high),
+ valueColor: high > 0 ? "text-[var(--color-warning)]" : undefined,
+ sub: `confidence ${DOC_DRIFT_CONFIDENCE.HIGH} or better`,
+ hint: "A path with no candidate anywhere in the tree, or a heading link whose heading is gone.",
+ },
+ {
+ label: "Worth a look",
+ value: formatNumber(medium + low),
+ sub: "check before editing",
+ hint: "Most often a path inside a guide that teaches rather than describes, where the author may have invented the example.",
+ },
+ ];
+
+ return (
+ <div className="flex flex-col gap-6">
+ <PageLede
+ label="Drifted"
+ value={formatNumber(summary.findings_total)}
+ unit={summary.findings_total === 1 ? "assertion" : "assertions"}
+ layout="beside"
+ figureFooter={
+ graded > 0 ? (
+ <ConfidenceSplit high={high} medium={medium} low={low} />
+ ) : undefined
+ }
+ >
+ {summary.findings_total === 0 ? (
+ <>
+ <p>
+ Every reference this detector could resolve still resolves. No document
+ names a file, a heading or a command that the repository has since moved
+ or removed.
+ </p>
+ <p className="mt-2.5">{summary.findings_basis}</p>
+ </>
+ ) : (
+ <>
+ <p>
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {formatNumber(summary.findings_total)}{" "}
+ {summary.findings_total === 1 ? "assertion" : "assertions"}
+ </strong>{" "}
+ across{" "}
+ <strong className="font-semibold text-[var(--color-text-primary)]">
+ {formatNumber(summary.documents)}{" "}
+ {summary.documents === 1 ? "document" : "documents"}
+ </strong>{" "}
+ no longer hold
+ {kinds.length > 0 ? (
+ <>
+ {" "}
+ &mdash; they are{" "}
+ {joinPhrases(
+ kinds.map(
+ ([kind, count]) =>
+ `${formatNumber(count)} ${docDriftKindLabel(kind).toLowerCase()}${count === 1 ? "" : "s"}`,
+ ),
+ )}
+ </>
+ ) : null}
+ . Each one names the document to edit, not the file it points at.
+ </p>
+ <p className="mt-2.5">{summary.findings_basis}</p>
+ <p className="mt-2.5">
+ Confidence here is a statement about the evidence, not a hedge. A path
+ with no candidate anywhere in the tree is near-certain; the same
+ evidence inside a contributor guide is not, because a guide teaching
+ you to add a file may name one that was never meant to exist.
+ </p>
+ </>
+ )}
+ </PageLede>
+
+ <StatRibbon stats={stats} />
+ </div>
+ );
+}
+
+/**
+ * How the pile splits by confidence. Stepped down from one family rather than
+ * reaching for three hues, because confidence is an ordered scale and not
+ * three categories; amber leads because drift is an attention state.
+ */
+function ConfidenceSplit({
+ high,
+ medium,
+ low,
+}: {
+ high: number;
+ medium: number;
+ low: number;
+}) {
+ const total = high + medium + low;
+ const segments = [
+ { key: "high", label: "near-certain", count: high, bar: "bg-[var(--color-warning)]" },
+ {
+ key: "medium",
+ label: "medium",
+ count: medium,
+ bar: "bg-[color-mix(in_srgb,var(--color-warning)_45%,var(--color-bg-inset))]",
+ },
+ {
+ key: "low",
+ label: "low",
+ count: low,
+ bar: "bg-[color-mix(in_srgb,var(--color-warning)_18%,var(--color-bg-inset))]",
+ },
+ ].filter((s) => s.count > 0);
+
+ return (
+ <div className="space-y-1.5">
+ <div className="flex h-1.5 w-full overflow-hidden rounded-full bg-[var(--color-bg-inset)]">
+ {segments.map((s) => (
+ <div
+ key={s.key}
+ className={s.bar}
+ style={{ width: `${(s.count / total) * 100}%` }}
+ aria-label={`${s.count} ${s.label} confidence`}
+ />
+ ))}
+ </div>
+ <div className="flex flex-wrap gap-x-3 gap-y-0.5 text-xs text-[var(--color-text-tertiary)]">
+ {segments.map((s) => (
+ <span key={s.key} className="inline-flex items-center gap-1 tabular-nums">
+ <span className={`inline-block h-1.5 w-1.5 rounded-full ${s.bar}`} />
+ {formatNumber(s.count)} {s.label}
+ </span>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/doc-drift/doc-drift-unavailable.tsx b/packages/ui/src/doc-drift/doc-drift-unavailable.tsx
new file mode 100644
index 000000000..c01586a57
--- /dev/null
+++ b/packages/ui/src/doc-drift/doc-drift-unavailable.tsx
@@ -0,0 +1,78 @@
+import { FileQuestion } from "lucide-react";
+import type { DocDriftUnavailable } from "@repowise-dev/types/doc-drift";
+
+import { EmptyState } from "../shared/empty-state";
+
+/**
+ * The three refusals, rendered here rather than pre-gated by each host.
+ *
+ * This is the state that matters most on this surface and the one most easily
+ * lost. A drift pass that never ran produces an empty findings list, which is
+ * indistinguishable from a repository whose documentation is correct — so the
+ * engine returns a cause instead of an empty list, and a host that gates on
+ * the cause itself grows its own wording for it. Health did exactly that and
+ * hosted ended up with a forked "unscored" component.
+ *
+ * Each cause names something a reader can act on. "Reindex" in particular is
+ * wrong advice for a locked database, which is why `drift_read_failed` is a
+ * separate cause and not folded into the stale-index one.
+ */
+type Copy = { title: string; description: string; retryable: boolean };
+
+const COPY: Record<DocDriftUnavailable, Copy> = {
+ not_computed: {
+ title: "Documentation has not been checked yet",
+ description:
+ "This index carries no drift results, so the pass has not run on it. It runs as part of an update. Until then this view cannot tell a repository with correct documentation from one nobody has looked at, and it will not guess.",
+ retryable: false,
+ },
+ index_predates_doc_drift: {
+ title: "This index predates documentation drift",
+ description:
+ "The index was built before this check existed, so there is nothing to read. Re-index the repository to populate it.",
+ retryable: false,
+ },
+ drift_read_failed: {
+ title: "Could not read the drift results",
+ description:
+ "The index is there but the read failed, which usually means the database is locked by another process rather than that anything is missing. Re-indexing will not help; try again once the other process has finished.",
+ retryable: true,
+ },
+};
+
+/**
+ * For a cause this build does not know. The engine owns the vocabulary and can
+ * grow it, and a hard lookup would take the whole tab down with an
+ * `undefined.title` rather than degrade. Retryable, because an unrecognised
+ * cause is not evidence that retrying is pointless.
+ */
+const UNKNOWN: Copy = {
+ title: "Documentation drift is unavailable",
+ description:
+ "The index could not answer, and gave a reason this version does not recognise. Updating Repowise may explain it.",
+ retryable: true,
+};
+
+export function DocDriftUnavailableState({
+ reason,
+ titleAs,
+ onRetry,
+}: {
+ reason: DocDriftUnavailable;
+ titleAs?: "h2" | "h3";
+ /** Offered only where retrying could change the answer. */
+ onRetry?: (() => void) | undefined;
+}) {
+ const copy = COPY[reason] ?? UNKNOWN;
+ return (
+ <EmptyState
+ icon={<FileQuestion className="h-6 w-6" />}
+ title={copy.title}
+ description={copy.description}
+ {...(titleAs ? { titleAs } : {})}
+ {...(copy.retryable && onRetry
+ ? { action: { label: "Try again", onClick: onRetry } }
+ : {})}
+ />
+ );
+}
diff --git a/packages/ui/src/doc-drift/doc-drift-view.tsx b/packages/ui/src/doc-drift/doc-drift-view.tsx
new file mode 100644
index 000000000..953200379
--- /dev/null
+++ b/packages/ui/src/doc-drift/doc-drift-view.tsx
@@ -0,0 +1,282 @@
+"use client";
+
+/**
+ * Documentation drift view, on the section design language.
+ *
+ * The shape is: a lede that leads with the count of drifted assertions and
+ * says in prose what the count does and does not cover, then the drill-down
+ * table with its own filters in the section header that owns them.
+ *
+ * Three things this view must not do, each of which is an easy and specific
+ * lie:
+ *
+ * - Report an unfilled store as a clean repository. The engine answers with a
+ * cause instead of an empty list, and that cause is rendered here rather
+ * than pre-gated by each host, so the wording cannot fork.
+ * - Show a count without its basis. Most references in a real tree are
+ * uncheckable by design, so a bare figure claims a coverage this detector
+ * does not have. `findings_basis` is prose in the lede, not a footnote.
+ * - Read as a list of broken code files. A finding is filed against the
+ * *document*, which is why the document leads every row.
+ *
+ * Presentation and orchestration only: the host injects fetching and links
+ * through a {@link DocDriftAdapter}, so web and hosted render one source.
+ */
+
+import { useState } from "react";
+import useSWR from "swr";
+import { FileCheck2 } from "lucide-react";
+import {
+ DOC_DRIFT_CONFIDENCE,
+ docDriftKindLabel,
+ type DocDriftResponse,
+} from "@repowise-dev/types/doc-drift";
+
+import { Skeleton } from "../ui/skeleton";
+import { ApiError } from "../shared/api-error";
+import { EmptyState } from "../shared/empty-state";
+import { OverviewSection } from "../overview/section";
+import { toFriendlyMessage } from "../lib/errors";
+
+import { DocDriftLede } from "./doc-drift-lede";
+import { DriftFindingsTable } from "./drift-findings-table";
+import { DocDriftUnavailableState } from "./doc-drift-unavailable";
+import type { DocDriftAdapter } from "./doc-drift-adapter";
+
+/**
+ * Server ceiling for one page of findings. Reaching it means the table shows a
+ * slice, and the lede says so rather than letting the slice read as the repo.
+ */
+const FINDINGS_LIMIT = 500;
+
+/**
+ * Reference classes for the filter, from what this repository actually has
+ * rather than from the vocabulary: an option for a class with no findings is a
+ * control that cannot act.
+ *
+ * Read off the *unfiltered* distribution, and the selected class is always
+ * included. Read off the filtered response, selecting one class would leave it
+ * as the only option and there would be no way back.
+ */
+function filterKinds(
+ distribution: DocDriftResponse | undefined,
+ selected: string,
+): string[] {
+ const keys = new Set(Object.keys(distribution?.summary?.by_kind ?? {}));
+ if (selected) keys.add(selected);
+ return [...keys].sort();
+}
+
+export function DocDriftView({
+ adapter,
+ renderError,
+ renderLoading,
+}: {
+ adapter: DocDriftAdapter;
+ /** Host-specific failure card — an auth toast, a permissions notice. */
+ renderError?: (error: unknown, retry: () => void) => React.ReactNode;
+ /** Host-specific skeleton, for a shell that has its own loading language. */
+ renderLoading?: () => React.ReactNode;
+}) {
+ /** Which slice the table shows. Both narrow the summary too, server-side,
+ * so the figures and the rows always describe one population. */
+ const [minConfidence, setMinConfidence] = useState<number>(
+ DOC_DRIFT_CONFIDENCE.MEDIUM,
+ );
+ const [kind, setKind] = useState<string>("");
+
+ const { data, isLoading, error, mutate } = useSWR<DocDriftResponse>(
+ `doc-drift:${adapter.cacheKey}:${minConfidence}:${kind}`,
+ () =>
+ adapter.listFindings({
+ min_confidence: minConfidence,
+ limit: FINDINGS_LIMIT,
+ ...(kind ? { kind } : {}),
+ }),
+ { revalidateOnFocus: false, keepPreviousData: true },
+ );
+
+ // The kind options come from the same query without the kind filter. When
+ // nothing is selected that is the key above, so SWR serves both from one
+ // request; only a narrowed view pays for a second.
+ const { data: distribution } = useSWR<DocDriftResponse>(
+ kind ? `doc-drift:${adapter.cacheKey}:${minConfidence}:` : null,
+ () =>
+ adapter.listFindings({
+ min_confidence: minConfidence,
+ limit: FINDINGS_LIMIT,
+ }),
+ { revalidateOnFocus: false },
+ );
+
+ const retry = () => void mutate();
+
+ if (error && !data) {
+ return (
+ <>
+ {renderError?.(error, retry) ?? (
+ <ApiError
+ title="Couldn't load documentation drift"
+ message={toFriendlyMessage(error)}
+ onRetry={retry}
+ />
+ )}
+ </>
+ );
+ }
+
+ if (isLoading && !data) {
+ return <>{renderLoading?.() ?? <DocDriftSkeleton />}</>;
+ }
+
+ if (!data) return null;
+
+ // The refusal outranks everything below it: with no summary there is no
+ // honest figure to lead with, and an empty table here would be the exact
+ // false clean the cause exists to prevent.
+ if (data.unavailable) {
+ // With a retry: nothing revalidates on focus, so a transient read failure
+ // would otherwise strand the tab until a full page reload.
+ return (
+ <DocDriftUnavailableState
+ reason={data.unavailable}
+ titleAs="h2"
+ onRetry={retry}
+ />
+ );
+ }
+
+ const summary = data.summary;
+ if (!summary) return null;
+
+ const truncated = data.findings_emitted < summary.findings_total;
+ const kinds = filterKinds(kind ? (distribution ?? data) : data, kind);
+ const filtered = minConfidence !== DOC_DRIFT_CONFIDENCE.MEDIUM || kind !== "";
+
+ return (
+ <div className="flex flex-col gap-8">
+ <DocDriftLede
+ summary={summary}
+ shownCount={data.findings_emitted}
+ truncated={truncated}
+ />
+
+ {summary.findings_total === 0 && !filtered ? (
+ <EmptyState
+ icon={<FileCheck2 className="h-6 w-6" />}
+ title="No documentation drift found"
+ description="Every reference this detector could resolve still resolves. It re-checks on each update, so this is worth a second look after a rename or a move."
+ />
+ ) : (
+ <OverviewSection
+ title="Drifted assertions"
+ description="Each row names the document to edit and the line to edit it on. It does not claim the document describes the file it names, only that the file is no longer there."
+ action={
+ <Filters
+ minConfidence={minConfidence}
+ onMinConfidence={setMinConfidence}
+ kind={kind}
+ onKind={setKind}
+ kinds={kinds}
+ />
+ }
+ >
+ {error ? (
+ // Over rows we already hold: say so, but keep them.
+ <ApiError
+ title="Couldn't refresh findings"
+ // Named, because the filters above already show the selection
+ // that failed while the figures below still describe the last
+ // one that loaded.
+ message={`${toFriendlyMessage(error)} The findings below are from the previous filter.`}
+ onRetry={retry}
+ />
+ ) : null}
+ {truncated && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ Showing {data.findings_emitted} of {summary.findings_total} findings.
+ </p>
+ )}
+ <DriftFindingsTable
+ findings={data.findings}
+ documentHref={adapter.documentHref}
+ navigate={adapter.navigate}
+ />
+ </OverviewSection>
+ )}
+ </div>
+ );
+}
+
+const SELECT_CLS =
+ "h-8 rounded-md border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] px-2 text-xs text-[var(--color-text-secondary)]";
+
+/**
+ * Two filters, each on its own axis: how sure the finding is, and how it was
+ * found. Both go to the server so the lede's figures narrow with the rows.
+ */
+function Filters({
+ minConfidence,
+ onMinConfidence,
+ kind,
+ onKind,
+ kinds,
+}: {
+ minConfidence: number;
+ onMinConfidence: (value: number) => void;
+ kind: string;
+ onKind: (value: string) => void;
+ kinds: string[];
+}) {
+ return (
+ <div className="flex flex-wrap items-center gap-2">
+ <label className="sr-only" htmlFor="doc-drift-confidence">
+ Minimum confidence
+ </label>
+ <select
+ id="doc-drift-confidence"
+ className={SELECT_CLS}
+ value={String(minConfidence)}
+ onChange={(e) => onMinConfidence(Number(e.target.value))}
+ >
+ <option value={String(DOC_DRIFT_CONFIDENCE.MEDIUM)}>All findings</option>
+ <option value={String(DOC_DRIFT_CONFIDENCE.HIGH)}>Near-certain only</option>
+ </select>
+
+ {/* Rendered whenever a class is selected, so the filter can always be
+ cleared even before the unfiltered distribution has arrived. */}
+ {(kinds.length > 1 || kind !== "") && (
+ <>
+ <label className="sr-only" htmlFor="doc-drift-kind">
+ Reference class
+ </label>
+ <select
+ id="doc-drift-kind"
+ className={SELECT_CLS}
+ value={kind}
+ onChange={(e) => onKind(e.target.value)}
+ >
+ <option value="">All references</option>
+ {kinds.map((k) => (
+ <option key={k} value={k}>
+ {docDriftKindLabel(k)}
+ </option>
+ ))}
+ </select>
+ </>
+ )}
+ </div>
+ );
+}
+
+function DocDriftSkeleton() {
+ return (
+ <div className="flex flex-col gap-8">
+ <div className="flex flex-col gap-3">
+ <Skeleton className="h-12 w-48" />
+ <Skeleton className="h-16 w-full max-w-[62ch]" />
+ </div>
+ <Skeleton className="h-40 w-full rounded-lg" />
+ </div>
+ );
+}
diff --git a/packages/ui/src/doc-drift/drift-findings-table.tsx b/packages/ui/src/doc-drift/drift-findings-table.tsx
new file mode 100644
index 000000000..5f292f6cb
--- /dev/null
+++ b/packages/ui/src/doc-drift/drift-findings-table.tsx
@@ -0,0 +1,154 @@
+"use client";
+
+/**
+ * The drill-down: one row per drifted assertion.
+ *
+ * Column order is the reading order of the sentence the row makes: *this
+ * document*, at *this line*, claims *this thing* exists, and here is why we
+ * think it does not. The document leads because it is the file the reader
+ * opens; putting the target first would read as a list of broken code files,
+ * which is the opposite of what a finding says.
+ */
+
+import { FileText } from "lucide-react";
+import {
+ docDriftConfidenceTier,
+ docDriftKindLabel,
+ type DocDriftFinding,
+} from "@repowise-dev/types/doc-drift";
+
+import {
+ ResponsiveTable,
+ type ResponsiveColumn,
+} from "../shared/responsive-table";
+import { EmptyState } from "../shared/empty-state";
+
+export interface DriftFindingsTableProps {
+ findings: DocDriftFinding[];
+ /** Where a document link goes; the row is clickable when given. */
+ documentHref: (path: string, line?: number) => string;
+ navigate?: ((href: string) => void) | undefined;
+}
+
+/**
+ * Colour is not the name of the tier. Critical and high need labels because
+ * amber alone is not a sufficient word, and the same holds here: the tier is
+ * written out and the colour only reinforces it.
+ */
+const TIER_CLS: Record<string, string> = {
+ high: "text-[var(--color-warning)]",
+ medium: "text-[var(--color-text-secondary)]",
+ low: "text-[var(--color-text-tertiary)]",
+};
+
+const TIER_LABEL: Record<string, string> = {
+ high: "Near-certain",
+ medium: "Medium",
+ low: "Low",
+};
+
+export function DriftFindingsTable({
+ findings,
+ documentHref,
+ navigate,
+}: DriftFindingsTableProps) {
+ const open = (finding: DocDriftFinding) => {
+ navigate?.(documentHref(finding.file_path, finding.line_number));
+ };
+
+ const columns: ResponsiveColumn<DocDriftFinding>[] = [
+ {
+ key: "document",
+ header: "Document",
+ priority: 1,
+ // Widths are capped per cell, not left to the table: a repo-relative
+ // path and a heading slug are both long and unbreakable, and an
+ // auto-laid-out table gives them the room by pushing the confidence
+ // column off the side, which is the one column a reader triages on.
+ cellClassName: "max-w-[34ch]",
+ render: (f) => (
+ <div className="flex min-w-0 flex-col gap-0.5">
+ <span
+ className="truncate font-mono text-xs text-[var(--color-text-primary)]"
+ title={`${f.file_path}:${f.line_number}`}
+ >
+ {f.file_path}
+ <span className="text-[var(--color-text-tertiary)]">:{f.line_number}</span>
+ </span>
+ <span
+ className="truncate text-xs text-[var(--color-text-tertiary)]"
+ title={f.reason}
+ >
+ {f.reason}
+ </span>
+ </div>
+ ),
+ },
+ {
+ key: "target",
+ header: "Claims this exists",
+ mobileLabel: "Claims",
+ priority: 1,
+ cellClassName: "max-w-[34ch]",
+ render: (f) => (
+ <span
+ className="block truncate font-mono text-xs text-[var(--color-text-secondary)]"
+ title={f.target}
+ >
+ {f.target}
+ </span>
+ ),
+ },
+ {
+ key: "kind",
+ header: "Reference",
+ priority: 2,
+ render: (f) => (
+ <span className="text-xs text-[var(--color-text-secondary)]">
+ {docDriftKindLabel(f.kind)}
+ </span>
+ ),
+ },
+ {
+ key: "confidence",
+ header: "Confidence",
+ align: "right",
+ priority: 2,
+ cellClassName: "whitespace-nowrap",
+ render: (f) => {
+ const tier = docDriftConfidenceTier(f.confidence);
+ return (
+ <span className={`text-xs tabular-nums ${TIER_CLS[tier]}`}>
+ {TIER_LABEL[tier]}{" "}
+ <span className="font-mono text-[var(--color-text-tertiary)]">
+ {f.confidence.toFixed(2)}
+ </span>
+ </span>
+ );
+ },
+ },
+ ];
+
+ return (
+ <ResponsiveTable
+ columns={columns}
+ rows={findings}
+ rowKey={(f) => f.id}
+ stacked="md"
+ caption="Documentation assertions the repository no longer satisfies"
+ {...(navigate
+ ? {
+ onRowClick: open,
+ rowClassName: () => "cursor-pointer",
+ }
+ : {})}
+ empty={
+ <EmptyState
+ icon={<FileText className="h-6 w-6" />}
+ title="No findings in this slice"
+ description="Widen the confidence floor or clear the reference filter to see the rest."
+ />
+ }
+ />
+ );
+}
diff --git a/packages/ui/src/doc-drift/index.ts b/packages/ui/src/doc-drift/index.ts
new file mode 100644
index 000000000..2344ab652
--- /dev/null
+++ b/packages/ui/src/doc-drift/index.ts
@@ -0,0 +1,5 @@
+export * from "./doc-drift-adapter";
+export * from "./doc-drift-lede";
+export * from "./doc-drift-unavailable";
+export * from "./doc-drift-view";
+export * from "./drift-findings-table";
diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.ts
index 7ee86cf9f..2c2d841b4 100644
--- a/packages/ui/vitest.config.ts
+++ b/packages/ui/vitest.config.ts
@@ -19,13 +19,16 @@ export default defineConfig({
// `@repowise-dev/types/health` → `<…/index.ts>/health`. That only breaks
// runtime *value* imports (type-only imports are erased), which is why it
// stayed latent until a test transitively value-imported a types subpath.
- // Keep this list in sync with packages/types/package.json `exports`.
+ // Kept in sync with packages/types/package.json `exports` by
+ // __tests__/types-alias-parity.test.ts, because the comment alone was not
+ // enough the last time a subpath was added.
alias: {
"@repowise-dev/types/graph": path.resolve(__dirname, "../types/src/graph.ts"),
"@repowise-dev/types/git": path.resolve(__dirname, "../types/src/git.ts"),
"@repowise-dev/types/docs": path.resolve(__dirname, "../types/src/docs.ts"),
"@repowise-dev/types/decisions": path.resolve(__dirname, "../types/src/decisions.ts"),
"@repowise-dev/types/dead-code": path.resolve(__dirname, "../types/src/dead-code.ts"),
+ "@repowise-dev/types/doc-drift": path.resolve(__dirname, "../types/src/doc-drift.ts"),
"@repowise-dev/types/symbols": path.resolve(__dirname, "../types/src/symbols.ts"),
"@repowise-dev/types/chat": path.resolve(__dirname, "../types/src/chat.ts"),
"@repowise-dev/types/workspace": path.resolve(__dirname, "../types/src/workspace.ts"),
@@ -48,6 +51,16 @@ export default defineConfig({
),
"@repowise-dev/types/coupling": path.resolve(__dirname, "../types/src/coupling.ts"),
"@repowise-dev/types/stats": path.resolve(__dirname, "../types/src/stats.ts"),
+ "@repowise-dev/types/episodes": path.resolve(__dirname, "../types/src/episodes.ts"),
+ "@repowise-dev/types/risk-semantics": path.resolve(
+ __dirname,
+ "../types/src/risk-semantics.ts",
+ ),
+ "@repowise-dev/types/repos": path.resolve(__dirname, "../types/src/repos.ts"),
+ "@repowise-dev/types/generated/http": path.resolve(
+ __dirname,
+ "../types/src/generated/http.ts",
+ ),
"@repowise-dev/types": path.resolve(__dirname, "../types/src/index.ts"),
},
},
diff --git a/packages/web/src/app/repos/[id]/code-health/page.tsx b/packages/web/src/app/repos/[id]/code-health/page.tsx
index 560516e89..a0dca4975 100644
--- a/packages/web/src/app/repos/[id]/code-health/page.tsx
+++ b/packages/web/src/app/repos/[id]/code-health/page.tsx
@@ -34,6 +34,7 @@ import {
LayoutDashboard,
RotateCw,
Scissors,
+ BookText,
Shield,
Waypoints,
type LucideIcon,
@@ -58,6 +59,7 @@ import {
type HealthCounts,
type HealthScope,
} from "@repowise-dev/types/health";
+import type { DocDriftResponse } from "@repowise-dev/types/doc-drift";
import { TriageTab } from "@/components/code-health/triage-tab";
import { HotspotsSection } from "@/components/code-health/hotspots-section";
import { FindingsTab } from "@/components/code-health/findings-tab";
@@ -65,9 +67,11 @@ import { PerformanceTab } from "@/components/code-health/performance-tab";
import { CoverageTab } from "@/components/code-health/coverage-tab";
import { TrendSection } from "@/components/code-health/trend-tab";
import { DeadCodeTab } from "@/components/risk/dead-code-tab";
+import { DocDriftTab } from "@/components/risk/doc-drift-tab";
import { ImpactTab } from "@/components/risk/impact-tab";
import { SecurityTab } from "@/components/risk/security-tab";
import { getDeadCodeSummary } from "@/lib/api/dead-code";
+import { getDocDrift } from "@/lib/api/doc-drift";
import {
getChurnComplexity,
getHealthCoverage,
@@ -88,6 +92,7 @@ const TABS = [
"findings",
"coverage",
"dead-code",
+ "doc-drift",
"security",
"impact",
] as const;
@@ -99,6 +104,7 @@ const TAB_LABELS: Record<TabId, string> = {
findings: "Findings",
coverage: "Tests",
"dead-code": "Dead code",
+ "doc-drift": "Doc drift",
security: "Security",
impact: "Blast radius",
};
@@ -115,6 +121,7 @@ const TAB_ICONS: Record<TabId, LucideIcon> = {
findings: Bug,
coverage: FlaskConical,
"dead-code": Scissors,
+ "doc-drift": BookText,
security: Shield,
impact: Waypoints,
};
@@ -404,6 +411,15 @@ export default function CodeHealthPage() {
{ revalidateOnFocus: false },
);
const coveragePct = coverage?.summary.line_coverage_pct;
+ // `limit: 1` rather than the tab's own key: the summary is computed over the
+ // whole query and `findings_total` counts before any cap, so one row of
+ // payload carries the badge. Sharing the tab's key would dedupe but pull
+ // every finding on page load for a number.
+ const { data: docDrift } = useSWR<DocDriftResponse>(
+ `doc-drift-badge:${repoId}`,
+ () => getDocDrift(repoId, { limit: 1 }),
+ { revalidateOnFocus: false },
+ );
const badges: Partial<Record<TabId, number | string>> = {};
// Performance has its own tab and is out of the findings list, so counting
@@ -413,6 +429,9 @@ export default function CodeHealthPage() {
overview.summary.open_findings - (overview.summary.performance_findings ?? 0);
}
if (deadCode) badges["dead-code"] = deadCode.total_findings;
+ // No badge when the drift pass has not run: the response carries a cause
+ // rather than a summary, and a 0 there would read as clean documentation.
+ if (docDrift?.summary) badges["doc-drift"] = docDrift.summary.findings_total;
if (coveragePct != null) badges.coverage = `${Math.round(coveragePct)}%`;
const setTab = useCallback(
@@ -569,6 +588,7 @@ export default function CodeHealthPage() {
{activeTab === "performance" && <PerformanceTab repoId={repoId} />}
{activeTab === "coverage" && <CoverageTab repoId={repoId} />}
{activeTab === "dead-code" && <DeadCodeTab repoId={repoId} />}
+ {activeTab === "doc-drift" && <DocDriftTab repoId={repoId} />}
{activeTab === "security" && <SecurityTab repoId={repoId} />}
{activeTab === "impact" && <ImpactTab repoId={repoId} />}
</ViewTabs>
diff --git a/packages/web/src/components/risk/doc-drift-tab.tsx b/packages/web/src/components/risk/doc-drift-tab.tsx
new file mode 100644
index 000000000..857c9a34c
--- /dev/null
+++ b/packages/web/src/components/risk/doc-drift-tab.tsx
@@ -0,0 +1,32 @@
+"use client";
+
+/**
+ * Doc drift host — binds the shared {@link DocDriftView} to web's `/api`
+ * client and `/repos/:id` routing. The composition (lede, confidence split,
+ * filters, findings table, and every refusal state) lives in
+ * `@repowise-dev/ui/doc-drift`; this file only injects the app-specific
+ * pieces, so web and hosted render the same view.
+ */
+
+import { useRouter } from "next/navigation";
+import { DocDriftView, type DocDriftAdapter } from "@repowise-dev/ui/doc-drift";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import { getDocDrift, getDocDriftReferences } from "@/lib/api/doc-drift";
+
+export function DocDriftTab({ repoId }: { repoId: string }) {
+ const router = useRouter();
+ const prefix = `/repos/${repoId}`;
+
+ const adapter: DocDriftAdapter = {
+ cacheKey: repoId,
+ listFindings: (opts) => getDocDrift(repoId, opts),
+ listReferences: (target) => getDocDriftReferences(repoId, target),
+ // The line is dropped rather than appended: no file view renders `#L<n>`
+ // anchors yet, and a fragment that resolves nowhere teaches the reader
+ // that the link goes somewhere it does not.
+ documentHref: (path) => fileEntityPath(prefix, path),
+ navigate: (href) => router.push(href),
+ };
+
+ return <DocDriftView adapter={adapter} />;
+}
diff --git a/packages/web/src/lib/api/doc-drift.ts b/packages/web/src/lib/api/doc-drift.ts
new file mode 100644
index 000000000..25671a35f
--- /dev/null
+++ b/packages/web/src/lib/api/doc-drift.ts
@@ -0,0 +1,3 @@
+import "./client";
+
+export * from "@repowise-dev/api-client/doc-drift";
diff --git a/tests/unit/doc_drift/test_serialize.py b/tests/unit/doc_drift/test_serialize.py
new file mode 100644
index 000000000..a6c635f71
--- /dev/null
+++ b/tests/unit/doc_drift/test_serialize.py
@@ -0,0 +1,290 @@
+"""A report and a store serialize to the same bytes.
+
+The reason this file exists: one consumer of this data holds ORM rows and
+another holds a ``DocDriftReport`` with no database under it at all. Those were
+two hand-written dicts waiting to drift, which is the failure
+``tests/unit/dead_code/test_confidence_parity.py`` records having already
+happened once. Both paths now go through one builder, and these tests assert
+the identity rather than the resemblance.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime
+
+import pytest
+
+from repowise.core.analysis.doc_drift.constants import DETECTION_BASIS
+from repowise.core.analysis.doc_drift.models import (
+ DocDriftFindingData,
+ DocDriftReport,
+ DriftKind,
+ ResolvedDocReference,
+)
+from repowise.core.analysis.doc_drift.serialize import (
+ collapse_reference_sites,
+ derive_doc_drift_id,
+ documents_with_drift,
+ serialize_finding,
+ serialize_reference,
+ serialize_report,
+ summarize_findings,
+)
+from repowise.core.persistence.crud.analysis.doc_drift import (
+ serialize_doc_drift_reference_row,
+ serialize_doc_drift_row,
+)
+from repowise.core.persistence.models import DocDriftFinding, DocDriftReference
+
+
+def _finding(**over) -> DocDriftFindingData:
+ base = {
+ "kind": DriftKind.PATH,
+ "file_path": "docs/architecture.md",
+ "line_number": 42,
+ "target": "src/auth.py",
+ "confidence": 0.9,
+ "reason": "No file matches this path.",
+ "origin": "path_no_candidate",
+ "evidence": ["line 42: see src/auth.py"],
+ "raw": "src/auth.py",
+ "context": "The resolver lives in src/auth.py.",
+ }
+ base.update(over)
+ return DocDriftFindingData(**base)
+
+
+def _row_from(finding: DocDriftFindingData) -> DocDriftFinding:
+ """The ORM row the writer would have produced for *finding*."""
+ return DocDriftFinding(
+ repository_id="r1",
+ file_path=finding.file_path,
+ kind=str(finding.kind.value),
+ line_number=finding.line_number,
+ target=finding.target,
+ confidence=finding.confidence,
+ reason=finding.reason,
+ origin=finding.origin,
+ evidence_json=json.dumps(list(finding.evidence)),
+ raw=finding.raw,
+ context=finding.context,
+ )
+
+
+def test_a_report_finding_and_its_stored_row_serialize_identically():
+ finding = _finding()
+ assert serialize_finding(finding) == serialize_doc_drift_row(_row_from(finding))
+
+
+def test_the_evidence_toggle_agrees_on_both_paths():
+ finding = _finding()
+ assert serialize_finding(finding, evidence=False) == serialize_doc_drift_row(
+ _row_from(finding), evidence=False
+ )
+ assert "evidence" not in serialize_finding(finding, evidence=False)
+
+
+def test_a_report_reference_and_its_stored_row_serialize_identically():
+ reference = ResolvedDocReference(
+ doc_path="docs/architecture.md",
+ target_path="src/auth.py",
+ kind=DriftKind.LINK,
+ line=7,
+ section="Extension points",
+ )
+ row = DocDriftReference(
+ repository_id="r1",
+ document_path=reference.doc_path,
+ target_path=reference.target_path,
+ kind=str(reference.kind.value),
+ line_number=reference.line,
+ section=reference.section,
+ )
+ assert serialize_reference(reference) == serialize_doc_drift_reference_row(row)
+
+
+def test_an_empty_section_is_absent_rather_than_blank():
+ reference = ResolvedDocReference(
+ doc_path="docs/a.md", target_path="src/x.py", kind=DriftKind.PATH, line=1
+ )
+ assert "section" not in serialize_reference(reference)
+
+
+def test_confidence_is_rounded_once_so_two_surfaces_cannot_disagree():
+ finding = _finding(confidence=0.925)
+ assert serialize_finding(finding)["confidence"] == 0.93
+ assert serialize_doc_drift_row(_row_from(finding))["confidence"] == 0.93
+
+
+class TestDeriveId:
+ def test_the_same_site_gets_the_same_id_across_runs(self):
+ first = derive_doc_drift_id("docs/a.md", DriftKind.PATH, 3, "src/x.py")
+ second = derive_doc_drift_id("docs/a.md", "path", 3, "src/x.py")
+ assert first == second
+
+ def test_the_id_is_the_house_width(self):
+ value = derive_doc_drift_id("docs/a.md", DriftKind.PATH, 3, "src/x.py")
+ assert len(value) == 32
+ assert value == value.lower()
+
+ @pytest.mark.parametrize(
+ "args",
+ [
+ ("docs/b.md", DriftKind.PATH, 3, "src/x.py"),
+ ("docs/a.md", DriftKind.LINK, 3, "src/x.py"),
+ ("docs/a.md", DriftKind.PATH, 4, "src/x.py"),
+ ("docs/a.md", DriftKind.PATH, 3, "src/y.py"),
+ ],
+ )
+ def test_every_part_of_the_key_moves_the_id(self, args):
+ base = derive_doc_drift_id("docs/a.md", DriftKind.PATH, 3, "src/x.py")
+ assert derive_doc_drift_id(*args) != base
+
+ def test_the_separator_cannot_be_forged_by_concatenation(self):
+ """Two different keys must not join to one string."""
+ assert derive_doc_drift_id("a", "path", 1, "bc") != derive_doc_drift_id(
+ "a", "path", 1, "b\x00c"
+ )
+
+
+class TestSummary:
+ def test_it_counts_documents_not_findings(self):
+ findings = [
+ serialize_finding(_finding(file_path="docs/a.md", line_number=1)),
+ serialize_finding(_finding(file_path="docs/a.md", line_number=2)),
+ serialize_finding(_finding(file_path="docs/b.md")),
+ ]
+ summary = summarize_findings(findings)
+ assert summary["findings_total"] == 3
+ assert summary["documents"] == 2
+
+ def test_it_carries_the_basis_so_a_count_never_travels_alone(self):
+ assert summarize_findings([])["findings_basis"] == DETECTION_BASIS
+
+ def test_an_empty_repository_still_names_every_tier(self):
+ assert summarize_findings([])["confidence"] == {
+ "high": 0,
+ "medium": 0,
+ "low": 0,
+ }
+
+ def test_kinds_are_ordered_so_equal_data_serializes_equal_bytes(self):
+ findings = [
+ serialize_finding(_finding(kind=DriftKind.PATH)),
+ serialize_finding(_finding(kind=DriftKind.ANCHOR, line_number=2)),
+ serialize_finding(_finding(kind=DriftKind.LINK, line_number=3)),
+ ]
+ assert list(summarize_findings(findings)["by_kind"]) == [
+ "anchor",
+ "link",
+ "path",
+ ]
+
+
+class TestCollapseAndDrift:
+ def test_a_link_with_a_fragment_is_one_mention_not_two(self):
+ rows = [
+ {"document": "docs/a.md", "line": 5, "kind": "link"},
+ {"document": "docs/a.md", "line": 5, "kind": "anchor"},
+ {"document": "docs/a.md", "line": 6, "kind": "link"},
+ ]
+ collapsed = collapse_reference_sites(rows)
+ assert [r["kind"] for r in collapsed] == ["link", "link"]
+ assert [r["line"] for r in collapsed] == [5, 6]
+
+ def test_collapsing_does_not_mutate_the_caller_s_rows(self):
+ rows = [{"document": "docs/a.md", "line": 5, "kind": "link"}]
+ collapse_reference_sites(rows)[0]["kind"] = "anchor"
+ assert rows[0]["kind"] == "link"
+
+ def test_only_documents_that_carry_drift_are_listed(self):
+ references = [
+ {"document": "docs/a.md", "line": 1, "kind": "path"},
+ {"document": "docs/b.md", "line": 1, "kind": "path"},
+ ]
+ assert documents_with_drift(references, {"docs/b.md": 2, "docs/c.md": 9}) == [
+ {"document": "docs/b.md", "findings": 2}
+ ]
+
+ def test_a_clean_answer_lists_nothing(self):
+ references = [{"document": "docs/a.md", "line": 1, "kind": "path"}]
+ assert documents_with_drift(references, {}) == []
+
+
+class TestSerializeReport:
+ def _report(self) -> DocDriftReport:
+ return DocDriftReport(
+ repo_id="r1",
+ analyzed_at=datetime(2026, 9, 18, tzinfo=UTC),
+ total_findings=1,
+ findings=[_finding()],
+ confidence_summary={"high": 1, "medium": 0, "low": 0},
+ documents_scanned=12,
+ references_checked=340,
+ verdict_summary={
+ "resolved": 300,
+ "missing": 1,
+ "ambiguous": 5,
+ "uncheckable": 34,
+ },
+ resolved_references=[
+ ResolvedDocReference(
+ doc_path="docs/b.md",
+ target_path="src/auth.py",
+ kind=DriftKind.LINK,
+ line=9,
+ ),
+ ResolvedDocReference(
+ doc_path="docs/a.md",
+ target_path="src/auth.py",
+ kind=DriftKind.PATH,
+ line=3,
+ ),
+ ResolvedDocReference(
+ doc_path="docs/a.md",
+ target_path="src/other.py",
+ kind=DriftKind.PATH,
+ line=4,
+ ),
+ ],
+ )
+
+ def test_references_arrive_inverted_by_the_file_that_was_named(self):
+ payload = serialize_report(self._report())
+ assert set(payload["references_by_target"]) == {"src/auth.py", "src/other.py"}
+ assert len(payload["references_by_target"]["src/auth.py"]) == 2
+
+ def test_each_target_is_ordered_the_way_the_store_returns_it(self):
+ payload = serialize_report(self._report())
+ rows = payload["references_by_target"]["src/auth.py"]
+ assert [r["document"] for r in rows] == ["docs/a.md", "docs/b.md"]
+
+ def test_the_findings_are_the_same_dicts_a_store_would_serve(self):
+ """Identical but for the id, which no store column holds."""
+ report = self._report()
+ payload = serialize_report(report)
+ served = [{k: v for k, v in f.items() if k != "id"} for f in payload["findings"]]
+ assert served == [
+ serialize_doc_drift_row(_row_from(f)) for f in report.findings
+ ]
+
+ def test_every_finding_carries_the_id_the_wire_contract_requires(self):
+ """A consumer serving drift from this artifact feeds a table that keys
+ its rows on the id; without one, every row keys on nothing."""
+ report = self._report()
+ payload = serialize_report(report)
+ assert [f["id"] for f in payload["findings"]] == [
+ derive_doc_drift_id(f.file_path, f.kind, f.line_number, f.target)
+ for f in report.findings
+ ]
+
+ def test_the_uncheckable_denominator_survives_serialization(self):
+ """The count that keeps the detector honest about its own coverage."""
+ payload = serialize_report(self._report())
+ assert payload["verdict_summary"]["uncheckable"] == 34
+ assert payload["references_checked"] == 340
+
+ def test_the_summary_rides_along_so_no_consumer_recomputes_it(self):
+ payload = serialize_report(self._report())
+ assert payload["summary"] == summarize_findings(payload["findings"])
diff --git a/tests/unit/doc_drift/test_ts_contract_parity.py b/tests/unit/doc_drift/test_ts_contract_parity.py
new file mode 100644
index 000000000..d28e783ec
--- /dev/null
+++ b/tests/unit/doc_drift/test_ts_contract_parity.py
@@ -0,0 +1,138 @@
+"""The TypeScript contract still says what the engine says.
+
+``packages/types/src/doc-drift.ts`` duplicates four things the engine owns: the
+two confidence boundaries, the refusal strings a client keys on, and the
+reference-class vocabulary. It duplicates them because the dashboard cannot
+import Python, and it is only safe to duplicate them if someone notices when
+they part.
+
+This is that notice, and it is the house pattern:
+``tests/unit/dead_code/test_confidence_parity.py`` exists because three
+surfaces had already drifted on exactly these numbers once. Read as a text
+file rather than through a TypeScript parser, because a parser is a dependency
+this suite does not have and the values are declared as literals.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.doc_drift.constants import (
+ HIGH_CONFIDENCE_THRESHOLD,
+ REVIEW_CONFIDENCE_THRESHOLD,
+ UNAVAILABLE_NO_TABLE,
+ UNAVAILABLE_NOT_COMPUTED,
+ UNAVAILABLE_READ_FAILED,
+)
+from repowise.core.analysis.doc_drift.models import DriftKind
+
+_CONTRACT = (
+ Path(__file__).resolve().parents[3] / "packages" / "types" / "src" / "doc-drift.ts"
+)
+
+
[email protected](scope="module")
+def contract() -> str:
+ assert _CONTRACT.is_file(), f"missing TypeScript contract at {_CONTRACT}"
+ return _CONTRACT.read_text(encoding="utf-8")
+
+
+def _number_after(source: str, key: str) -> float:
+ match = re.search(rf"\b{key}:\s*([0-9.]+)", source)
+ assert match, f"{key} is not declared as a literal in doc-drift.ts"
+ return float(match.group(1))
+
+
+def test_the_high_boundary_matches_the_engine(contract: str) -> None:
+ assert _number_after(contract, "HIGH") == HIGH_CONFIDENCE_THRESHOLD
+
+
+def test_the_medium_boundary_matches_the_engine(contract: str) -> None:
+ assert _number_after(contract, "MEDIUM") == REVIEW_CONFIDENCE_THRESHOLD
+
+
+def test_every_refusal_the_engine_can_return_is_in_the_union(contract: str) -> None:
+ """A client keys on these strings; one renamed alone renders as unhandled."""
+ union = re.search(
+ r"export type DocDriftUnavailable =(.*?);", contract, re.S
+ )
+ assert union, "DocDriftUnavailable is not declared"
+ declared = set(re.findall(r'"([a-z_]+)"', union.group(1)))
+ assert declared == {
+ UNAVAILABLE_NOT_COMPUTED,
+ UNAVAILABLE_NO_TABLE,
+ UNAVAILABLE_READ_FAILED,
+ }
+
+
+def test_the_reference_classes_match_the_engine_vocabulary(contract: str) -> None:
+ union = re.search(r"export type DocDriftKind =(.*?);", contract, re.S)
+ assert union, "DocDriftKind is not declared"
+ declared = set(re.findall(r'"([a-z_]+)"', union.group(1)))
+ assert declared == {kind.value for kind in DriftKind}
+
+
+def test_every_reference_class_has_a_reader_facing_label(contract: str) -> None:
+ """An unlabelled class renders its API slug as a column heading."""
+ block = re.search(
+ r"DOC_DRIFT_KIND_LABELS: Record<DocDriftKind, string> = \{(.*?)\};",
+ contract,
+ re.S,
+ )
+ assert block, "DOC_DRIFT_KIND_LABELS is not declared"
+ labelled = set(re.findall(r"^\s*([a-z_]+):", block.group(1), re.M))
+ assert labelled == {kind.value for kind in DriftKind}
+
+
+def _interface_fields(source: str, name: str) -> set[str]:
+ """The field names one exported TS interface declares."""
+ block = re.search(rf"export interface {name} \{{(.*?)\n\}}", source, re.S)
+ assert block, f"{name} is not declared in doc-drift.ts"
+ # Optional members carry a trailing "?", which is not part of the name.
+ return set(re.findall(r"^\s{2}(\w+)\??:", block.group(1), re.M))
+
+
+#: The response models whose field names the dashboard reads, paired with the
+#: interface that has to keep saying the same thing. A rename on the Python
+#: side fails loudly there (pydantic rejects the dict); nothing made the
+#: TypeScript follow, and the frontend would read ``undefined`` at runtime.
+_WIRE_PAIRS = [
+ ("DocDriftFindingResponse", "DocDriftFinding"),
+ ("DocDriftSummaryResponse", "DocDriftSummary"),
+ ("DocDriftResponse", "DocDriftResponse"),
+ ("DocDriftReferenceResponse", "DocDriftReference"),
+ ("DocDriftDocumentDriftResponse", "DocDriftDocumentDrift"),
+ ("DocDriftReferencesResponse", "DocDriftReferencesResponse"),
+]
+
+
[email protected](("model_name", "interface"), _WIRE_PAIRS)
+def test_the_wire_shape_says_the_same_thing_in_both_languages(
+ contract: str, model_name: str, interface: str
+) -> None:
+ from repowise.server import schemas
+
+ model = getattr(schemas, model_name)
+ assert _interface_fields(contract, interface) == set(model.model_fields)
+
+
+def test_the_typescript_tier_function_splits_where_the_engine_splits(
+ contract: str,
+) -> None:
+ """The boundaries are pinned above; this pins the comparison using them.
+
+ Two numbers can agree while the code around them does not: a ``>`` where
+ the engine writes ``>=`` moves every finding sitting exactly on a boundary
+ into the tier below, on the surface most people read.
+ """
+ body = re.search(
+ r"export function docDriftConfidenceTier\(.*?\n\}", contract, re.S
+ )
+ assert body, "docDriftConfidenceTier is not declared"
+ comparisons = re.findall(
+ r"confidence (>=?|<=?) DOC_DRIFT_CONFIDENCE\.(\w+)", body.group(0)
+ )
+ assert comparisons == [(">=", "HIGH"), (">=", "MEDIUM")]
diff --git a/tests/unit/server/conftest.py b/tests/unit/server/conftest.py
index cfe1ad890..ed2bca92a 100644
--- a/tests/unit/server/conftest.py
+++ b/tests/unit/server/conftest.py
@@ -34,6 +34,7 @@ def _create_test_app():
costs,
dead_code,
decisions,
+ doc_drift,
episodes,
external_systems,
files,
@@ -90,6 +91,7 @@ def _create_test_app():
app.include_router(git.router)
app.include_router(files.router)
app.include_router(dead_code.router)
+ app.include_router(doc_drift.router)
# Same position as app.py, so route precedence in tests matches production.
app.include_router(code_health.router)
app.include_router(owners.router)
diff --git a/tests/unit/server/test_doc_drift.py b/tests/unit/server/test_doc_drift.py
new file mode 100644
index 000000000..89a03d874
--- /dev/null
+++ b/tests/unit/server/test_doc_drift.py
@@ -0,0 +1,516 @@
+"""Tests for the documentation drift endpoints.
+
+Weighted toward what the surface may not claim rather than toward what it
+serves. A drift dashboard has two easy ways to lie: reporting a store nobody
+filled as a clean tree, and letting a reference row read as "this document
+describes your file". Both have a test here.
+"""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+from sqlalchemy import text
+
+from repowise.core.analysis.doc_drift.constants import (
+ DETECTION_BASIS,
+ REFERENCE_BASIS,
+)
+from repowise.core.analysis.doc_drift.models import (
+ DocDriftFindingData,
+ DriftKind,
+ ResolvedDocReference,
+)
+from repowise.core.analysis.doc_drift.serialize import derive_doc_drift_id
+from repowise.core.persistence import crud
+from repowise.core.persistence.database import get_session
+from tests.unit.server.conftest import create_test_repo
+
+
+def _finding(**over) -> DocDriftFindingData:
+ base = {
+ "kind": DriftKind.PATH,
+ "file_path": "docs/architecture.md",
+ "line_number": 42,
+ "target": "src/auth.py",
+ "confidence": 0.9,
+ "reason": "No file matches this path.",
+ "origin": "path_no_candidate",
+ "evidence": ["line 42: src/auth.py"],
+ "raw": "src/auth.py",
+ "context": "The resolver lives in src/auth.py.",
+ }
+ base.update(over)
+ return DocDriftFindingData(**base)
+
+
+async def _seed(session_factory, repo_id: str, *, findings=None, references=None):
+ """Write drift rows the way the pipeline writes them."""
+ async with get_session(session_factory) as session:
+ await crud.replace_doc_drift_findings(session, repo_id, list(findings or []))
+ await crud.replace_doc_drift_references(
+ session, repo_id, list(references or [])
+ )
+
+
+def _reference(**over) -> ResolvedDocReference:
+ base = {
+ "doc_path": "docs/overview.md",
+ "target_path": "src/auth.py",
+ "kind": DriftKind.LINK,
+ "line": 9,
+ "section": "Extension points",
+ }
+ base.update(over)
+ return ResolvedDocReference(**base)
+
+
+class TestFindings:
+ @pytest.mark.asyncio
+ async def test_it_serves_findings_with_the_rollup_over_them(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[
+ _finding(),
+ _finding(line_number=50, kind=DriftKind.ANCHOR, confidence=0.95),
+ _finding(file_path="docs/cli.md", confidence=0.5),
+ ],
+ references=[_reference()],
+ )
+
+ resp = await client.get(f"/api/repos/{repo['id']}/doc-drift")
+ assert resp.status_code == 200
+ data = resp.json()
+
+ assert data["unavailable"] is None
+ assert len(data["findings"]) == 3
+ assert data["findings_emitted"] == 3
+ assert data["summary"]["findings_total"] == 3
+ assert data["summary"]["documents"] == 2
+ assert data["summary"]["confidence"] == {"high": 2, "medium": 1, "low": 0}
+ assert data["summary"]["by_kind"] == {"anchor": 1, "path": 2}
+
+ @pytest.mark.asyncio
+ async def test_a_count_never_travels_without_what_it_covers(
+ self, client: AsyncClient, app
+ ) -> None:
+ """Most references in a real tree are uncheckable; the basis says so."""
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[_finding()],
+ references=[_reference()],
+ )
+
+ resp = await client.get(f"/api/repos/{repo['id']}/doc-drift")
+ assert resp.json()["summary"]["findings_basis"] == DETECTION_BASIS
+
+ @pytest.mark.asyncio
+ async def test_the_finding_names_the_document_to_edit(
+ self, client: AsyncClient, app
+ ) -> None:
+ """Not the target it names. The opposite reading is the whole risk."""
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[_finding()],
+ references=[_reference()],
+ )
+
+ finding = (await client.get(f"/api/repos/{repo['id']}/doc-drift")).json()[
+ "findings"
+ ][0]
+ assert finding["file_path"] == "docs/architecture.md"
+ assert finding["target"] == "src/auth.py"
+
+ @pytest.mark.asyncio
+ async def test_every_finding_carries_the_id_a_client_keys_triage_on(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[_finding()],
+ references=[_reference()],
+ )
+
+ finding = (await client.get(f"/api/repos/{repo['id']}/doc-drift")).json()[
+ "findings"
+ ][0]
+ assert finding["id"] == derive_doc_drift_id(
+ "docs/architecture.md", "path", 42, "src/auth.py"
+ )
+
+ @pytest.mark.asyncio
+ async def test_an_unfilled_store_refuses_rather_than_reporting_a_clean_tree(
+ self, client: AsyncClient, app
+ ) -> None:
+ """The pass only runs when an update has work, so "never analysed"
+ looks exactly like "every document is correct"."""
+ repo = await create_test_repo(client)
+
+ resp = await client.get(f"/api/repos/{repo['id']}/doc-drift")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["unavailable"] == "not_computed"
+ assert data["findings"] == []
+ assert data["summary"] is None
+
+ @pytest.mark.asyncio
+ async def test_a_repository_with_documentation_and_no_drift_reads_as_clean(
+ self, client: AsyncClient, app
+ ) -> None:
+ """The other side of the probe: references stored, no findings."""
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"], references=[_reference()])
+
+ data = (await client.get(f"/api/repos/{repo['id']}/doc-drift")).json()
+ assert data["unavailable"] is None
+ assert data["summary"]["findings_total"] == 0
+
+ @pytest.mark.asyncio
+ async def test_a_narrowing_filter_cannot_claim_the_pass_never_ran(
+ self, client: AsyncClient, app
+ ) -> None:
+ """The probe answers a question about the index, not about the query.
+
+ A repository whose documents resolve to nothing stores no references,
+ so probing the reference table alone would let ``min_confidence`` turn
+ findings that exist into "nobody has ever checked this".
+ """
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[_finding(confidence=0.5)],
+ references=[],
+ )
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift", params={"min_confidence": 0.9}
+ )
+ ).json()
+ assert data["unavailable"] is None
+ assert data["summary"]["findings_total"] == 0
+
+ @pytest.mark.asyncio
+ async def test_a_document_filter_matching_nothing_is_not_a_missing_pass(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory, repo["id"], findings=[_finding()], references=[]
+ )
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift",
+ params={"document": "docs/absent.md"},
+ )
+ ).json()
+ assert data["unavailable"] is None
+
+ @pytest.mark.asyncio
+ async def test_an_unknown_repository_is_not_answered_as_documented(
+ self, client: AsyncClient
+ ) -> None:
+ resp = await client.get("/api/repos/does-not-exist/doc-drift")
+ assert resp.status_code == 404
+
+ @pytest.mark.asyncio
+ async def test_the_confidence_floor_filters_the_list_and_its_summary_together(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[_finding(), _finding(file_path="docs/cli.md", confidence=0.5)],
+ references=[_reference()],
+ )
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift", params={"min_confidence": 0.8}
+ )
+ ).json()
+ assert len(data["findings"]) == 1
+ assert data["summary"]["findings_total"] == 1
+
+ @pytest.mark.asyncio
+ async def test_the_kind_filter_narrows_the_summary_too(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[_finding(), _finding(line_number=9, kind=DriftKind.ANCHOR)],
+ references=[_reference()],
+ )
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift", params={"kind": "anchor"}
+ )
+ ).json()
+ assert data["summary"]["by_kind"] == {"anchor": 1}
+ assert data["summary"]["findings_total"] == 1
+
+ @pytest.mark.asyncio
+ async def test_a_capped_page_still_counts_the_whole_repository(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[_finding(line_number=n) for n in range(1, 6)],
+ references=[_reference()],
+ )
+
+ data = (
+ await client.get(f"/api/repos/{repo['id']}/doc-drift", params={"limit": 2})
+ ).json()
+ assert data["findings_emitted"] == 2
+ assert len(data["findings"]) == 2
+ assert data["summary"]["findings_total"] == 5
+
+ @pytest.mark.asyncio
+ async def test_one_document_can_be_asked_about_on_its_own(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[_finding(), _finding(file_path="docs/cli.md")],
+ references=[_reference()],
+ )
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift",
+ params={"document": "docs/cli.md"},
+ )
+ ).json()
+ assert [f["file_path"] for f in data["findings"]] == ["docs/cli.md"]
+
+
+class TestStaleIndex:
+ """An index older than the store must say so, and say which cause.
+
+ Reached for real: starting the server against a pre-drift index creates
+ the tables without running the pass, so "table absent" and "table empty"
+ are different states with different advice. Telling a reader to re-index
+ when the database is merely locked is the third.
+ """
+
+ @staticmethod
+ async def _drop_tables(session_factory) -> None:
+ async with get_session(session_factory) as session:
+ await session.execute(text("DROP TABLE doc_drift_findings"))
+ await session.execute(text("DROP TABLE doc_drift_references"))
+
+ @pytest.mark.asyncio
+ async def test_findings_name_the_stale_index_rather_than_a_failure(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await self._drop_tables(app.state.session_factory)
+
+ resp = await client.get(f"/api/repos/{repo['id']}/doc-drift")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["unavailable"] == "index_predates_doc_drift"
+ assert data["summary"] is None
+
+ @pytest.mark.asyncio
+ async def test_the_reverse_view_says_the_same_thing(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await self._drop_tables(app.state.session_factory)
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift/references",
+ params={"target": "src/auth.py"},
+ )
+ ).json()
+ assert data["unavailable"] == "index_predates_doc_drift"
+ # The refusal still carries what a reference would have claimed, so a
+ # reader is never left to infer it from an empty list.
+ assert data["references_basis"] == REFERENCE_BASIS
+
+
+class TestReferences:
+ @pytest.mark.asyncio
+ async def test_it_answers_which_documents_name_a_file(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ references=[_reference(), _reference(doc_path="docs/cli.md", line=3)],
+ )
+
+ resp = await client.get(
+ f"/api/repos/{repo['id']}/doc-drift/references",
+ params={"target": "src/auth.py"},
+ )
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["target_path"] == "src/auth.py"
+ assert data["documents"] == 2
+ assert {r["document"] for r in data["references"]} == {
+ "docs/overview.md",
+ "docs/cli.md",
+ }
+ assert data["references"][0]["section"] in {"Extension points", ""}
+
+ @pytest.mark.asyncio
+ async def test_absence_is_not_proof_that_nothing_documents_the_file(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"], references=[_reference()])
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift/references",
+ params={"target": "src/never_mentioned.py"},
+ )
+ ).json()
+ assert data["references"] == []
+ assert data["references_basis"] == REFERENCE_BASIS
+
+ @pytest.mark.asyncio
+ async def test_an_unfilled_store_refuses_the_reverse_question_too(
+ self, client: AsyncClient
+ ) -> None:
+ repo = await create_test_repo(client)
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift/references",
+ params={"target": "src/auth.py"},
+ )
+ ).json()
+ assert data["unavailable"] == "not_computed"
+ assert data["references"] == []
+
+ @pytest.mark.asyncio
+ async def test_drift_is_reported_against_the_document_not_the_target(
+ self, client: AsyncClient, app
+ ) -> None:
+ """``documents_with_drift`` counts a document's own findings, which
+ need not be about the file that was asked about."""
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[_finding(file_path="docs/overview.md", target="src/gone.py")],
+ references=[_reference()],
+ )
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift/references",
+ params={"target": "src/auth.py"},
+ )
+ ).json()
+ assert data["documents_with_drift"] == [
+ {"document": "docs/overview.md", "findings": 1}
+ ]
+
+ @pytest.mark.asyncio
+ async def test_a_link_with_a_fragment_is_one_mention_not_two(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ references=[
+ _reference(kind=DriftKind.LINK),
+ _reference(kind=DriftKind.ANCHOR),
+ ],
+ )
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift/references",
+ params={"target": "src/auth.py"},
+ )
+ ).json()
+ assert len(data["references"]) == 1
+ assert data["documents"] == 1
+
+ @pytest.mark.asyncio
+ async def test_a_document_past_the_display_cap_still_reports_its_drift(
+ self, client: AsyncClient, app
+ ) -> None:
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ findings=[_finding(file_path="docs/z.md", target="src/gone.py")],
+ references=[
+ _reference(doc_path=f"docs/{name}.md", line=1)
+ for name in ("a", "b", "z")
+ ],
+ )
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift/references",
+ params={"target": "src/auth.py", "limit": 1},
+ )
+ ).json()
+ assert len(data["references"]) == 1
+ assert data["documents_with_drift"] == [{"document": "docs/z.md", "findings": 1}]
+
+ @pytest.mark.asyncio
+ async def test_a_capped_answer_says_how_much_it_left_out(
+ self, client: AsyncClient, app
+ ) -> None:
+ """Otherwise 50 rows sit beside an uncapped document count with no way
+ for a reader to tell a complete answer from a slice."""
+ repo = await create_test_repo(client)
+ await _seed(
+ app.state.session_factory,
+ repo["id"],
+ references=[
+ _reference(doc_path=f"docs/{n}.md", line=1) for n in range(1, 6)
+ ],
+ )
+
+ data = (
+ await client.get(
+ f"/api/repos/{repo['id']}/doc-drift/references",
+ params={"target": "src/auth.py", "limit": 2},
+ )
+ ).json()
+ assert data["references_emitted"] == 2
+ assert data["references_total"] == 5
+ assert data["documents"] == 5
+
+ @pytest.mark.asyncio
+ async def test_an_unknown_repository_is_not_answered_as_undocumented(
+ self, client: AsyncClient
+ ) -> None:
+ resp = await client.get(
+ "/api/repos/does-not-exist/doc-drift/references",
+ params={"target": "src/auth.py"},
+ )
+ assert resp.status_code == 404