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): scope the CI gate to the drift a change is answerable for (#2640)

Raghav Chamadiyaad09405ae4db
diff --git a/.github/doc-drift-baseline.json b/.github/doc-drift-baseline.json
new file mode 100644
index 000000000..e2c39eb0e
--- /dev/null
+++ b/.github/doc-drift-baseline.json
@@ -0,0 +1,18 @@
+{
+ "version": 1,
+ "basis": "Documentation drift accepted as known. A listed finding does not fail the gate; it is keyed on document, kind and target, not line.",
+ "entries": [
+ {
+ "fingerprint": "cbff1edf863eea0a013d3d97de98ef7e",
+ "file_path": "docs/architecture/editor-files.md",
+ "kind": "path",
+ "target": ".github/copilot-instructions.md"
+ },
+ {
+ "fingerprint": "af6d03fb19b64196881bb0a708447606",
+ "file_path": "docs/architecture/language-support.md",
+ "kind": "path",
+ "target": "packages/core/src/repowise/core/ingestion/languages/specs/mylang.py"
+ }
+ ]
+}
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e3ee82729..e97416b3e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -103,6 +103,28 @@ jobs:
- name: Run ruff
run: uv run ruff check .
+ # ---------------------------------------------------------------------------
+ # Documentation drift over the checkout, no index; the baseline says what it holds.
+ # ---------------------------------------------------------------------------
+ doc-drift:
+ name: Documentation drift
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Install uv
+ uses: astral-sh/setup-uv@v3
+ with:
+ version: "latest"
+ enable-cache: true
+
+ - name: Install dependencies
+ run: uv sync --all-packages
+
+ - name: Check documentation drift
+ run: uv run repowise doc-drift --check --baseline .github/doc-drift-baseline.json --format github
+
# ---------------------------------------------------------------------------
# Integration tests (run on push to main only, slower)
# ---------------------------------------------------------------------------
diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md
index a387b4f63..fcfaf01f3 100644
--- a/docs/architecture/ARCHITECTURE.md
+++ b/docs/architecture/ARCHITECTURE.md
@@ -865,7 +865,7 @@ The `GitIndexer` runs once during `repowise init` (after graph construction, bef
generation) and incrementally during `repowise update`. All git features degrade
gracefully when git metadata is unavailable; they simply skip git-enriched context.
-### 7.1 GitIndexer (`packages/core/ingestion/git_indexer.py`)
+### 7.1 GitIndexer (`packages/core/src/repowise/core/ingestion/git_indexer/`)
The `GitIndexer` class mines git history into the `git_metadata` SQL table. For each
tracked file, it computes:
@@ -1462,7 +1462,7 @@ in the existing `wiki_pages` table, queries are plain SQL with `<=>` cosine dist
and backup/restore is a single `pg_dump`. The HNSW index (`CREATE INDEX ... USING hnsw`)
gives query latency on par with LanceDB at typical repowise dataset sizes.
-The `VectorStore` abstraction in `packages/core/src/repowise/core/persistence/vector.py`
+The `VectorStore` abstraction in `packages/core/src/repowise/core/persistence/vector_store/`
selects the backend at startup based on `DATABASE_URL`: SQLite → LanceDB, PostgreSQL → pgvector.
### NetworkX + SQLite fallback, not Neo4j
diff --git a/docs/architecture/code-health.md b/docs/architecture/code-health.md
index 4a466c67d..1113fa3e2 100644
--- a/docs/architecture/code-health.md
+++ b/docs/architecture/code-health.md
@@ -251,7 +251,7 @@ The returned report rides on `PipelineResult.health_report`. Then
trend tracking (rolling 50-row window per repo), and a second
`{path: total_deduction}` map covering only the files whose score is held at
the floor. Both maps come from `trends.snapshot_file_maps`, which the other two
-snapshot writers (`repowise health` and `repowise upgrade`) also call — a repo
+snapshot writers (`repowise health` and `repowise update --full`) also call — a repo
whose writers disagreed would get a history whose depth changed depending on
which command last wrote it.
@@ -707,7 +707,7 @@ flag the exact uncovered surface, not just the percent.
## 11. CLI surface
-`packages/cli/src/repowise/cli/commands/health_cmd.py`. Mirrors the
+`packages/cli/src/repowise/cli/commands/health_cmd/`. Mirrors the
dead-code command's Click structure.
```bash
@@ -989,7 +989,7 @@ phases may revisit; the constraints kept v1 shippable.
| Add a new MCP `include` flag | `tool_health/`: name it in `request.py`, read it in `loading.py`, render it in `blocks.py` beside the existing `"coverage"` / `"refactoring"` blocks |
| Add a new REST route | `routers/code_health.py`: auth is wired at the router level |
| Add a new dashboard view | new file under `packages/web/src/app/repos/[id]/health/`, primitives under `packages/ui/src/health/` |
-| Add a CLI flag | `packages/cli/src/repowise/cli/commands/health_cmd.py` |
+| Add a CLI flag | `packages/cli/src/repowise/cli/commands/health_cmd/` |
| Wire the analyzer into a new entry point | call `HealthAnalyzer.analyze()` directly; persist via the upsert variants if your caller is incremental |
---
diff --git a/docs/architecture/editor-files.md b/docs/architecture/editor-files.md
index 825873631..1c6602def 100644
--- a/docs/architecture/editor-files.md
+++ b/docs/architecture/editor-files.md
@@ -480,6 +480,7 @@ Example: adding `cursor.md` support.
### Step 1 — Create the subclass
+<!-- repowise-drift-ignore -->
**`packages/core/src/repowise/core/generation/editor_files/cursor_md.py`**
```python
diff --git a/docs/business/SECURITY_COMPLIANCE.md b/docs/business/SECURITY_COMPLIANCE.md
index 756e532ee..9561093ed 100644
--- a/docs/business/SECURITY_COMPLIANCE.md
+++ b/docs/business/SECURITY_COMPLIANCE.md
@@ -143,14 +143,14 @@ off switches.
| Where the index lives | `.repowise/` on your machine | Postgres + LanceDB/pgvector in your network | Repowise-operated infrastructure |
| Who calls the LLM | you, with your key | you, with your key | the platform |
| Outbound from your network | anonymous telemetry (disableable), your LLM provider | same, plus configured integrations | n/a, you are sending code to the platform |
-| Commercial security features (CVE triage, SBOM/VEX, hosted secret detection, compliance reports, audit trail) | not included (local pattern + full-history scan via `repowise security scan --history` is OSS) | per [COMMERCIAL.md §5](COMMERCIAL.md#5-commercial-capabilities--in-detail) | GA today |
+| Commercial security features (CVE triage, SBOM/VEX, hosted secret detection, compliance reports, audit trail) | not included (local pattern + full-history scan via `repowise security scan --history` is OSS) | per [COMMERCIAL.md §5](COMMERCIAL.md#5-commercial-capabilities-in-detail) | GA today |
The honest framing: **several commercial security capabilities are GA on the
hosted platform first.** If your requirement is on-prem *and* CVE-aware
dependency analysis, SBOM/VEX, or compliance reporting, that sequencing is a
scoping conversation, not a checkbox. The status of each capability (GA / in
development / planned) is listed unvarnished in
-[COMMERCIAL.md §4](COMMERCIAL.md#4-commercial-capabilities--at-a-glance).
+[COMMERCIAL.md §4](COMMERCIAL.md#4-commercial-capabilities-at-a-glance).
**Secrets handling on the hosted secret-detection feature:** only a fingerprint
and a redacted preview are stored, never the secret value.
@@ -245,7 +245,7 @@ own product and adds the layer above.
| Can telemetry be tied back to a user or a repo? | No. `anon_id` is a random UUID in `~/.repowise/platform.json`, not derived from any machine or user identifier, and no repo-identifying field is sent. |
| Are you SOC 2 or ISO 27001 certified? | No. We publish PCI-DSS 4.0 and SOC 2 **control-coverage reports** on the hosted platform, explicitly labeled as coverage signals rather than an audit or certification. ISO 27001 Annex A mapping is roadmap. |
| Can we deploy on-prem or air-gapped? | Yes. Containerized API, indexer workers, and dashboard, backed by Postgres and LanceDB/pgvector, with optional Ollama. No outbound connectivity is required in air-gapped mode. A single packaged air-gapped bundle is planned, not shipped. |
-| Do you support SSO and SCIM? | SAML / OIDC SSO (Okta, Entra ID, Auth0, Google Workspace, generic SAML 2.0) and SCIM provisioning are rolling out commercially. RBAC and multi-tenant are planned. Confirm current status against [COMMERCIAL.md §4](COMMERCIAL.md#4-commercial-capabilities--at-a-glance). |
+| Do you support SSO and SCIM? | SAML / OIDC SSO (Okta, Entra ID, Auth0, Google Workspace, generic SAML 2.0) and SCIM provisioning are rolling out commercially. RBAC and multi-tenant are planned. Confirm current status against [COMMERCIAL.md §4](COMMERCIAL.md#4-commercial-capabilities-at-a-glance). |
| Is there an audit log? | On the hosted platform, insert-only, covering the security surface, with user, IP, and timestamp, JSON/CSV export, and an opt-in signed-webhook stream. Broader coverage is in development. |
| Do you store secrets you find? | Only a fingerprint and a redacted preview. Never the secret value. |
| What does the MCP server expose to an AI agent? | Read-only query tools over the local index. The lean MCP container exposes no ports and speaks stdio only. |
diff --git a/docs/layers/DOC_DRIFT.md b/docs/layers/DOC_DRIFT.md
index 75b3312bb..e54808ca4 100644
--- a/docs/layers/DOC_DRIFT.md
+++ b/docs/layers/DOC_DRIFT.md
@@ -117,6 +117,22 @@ Baseline entries are keyed on the document, the reference class and the target,
not the line number, so editing a document above a known finding does not turn
it back into a new one.
+On a pull request you can instead gate only the drift the change is answerable
+for, with no baseline to maintain:
+
+```bash
+repowise doc-drift --check --since auto --format github
+```
+
+`--since REVSPEC` keeps a finding when the change edits its document, deletes
+or renames the file or directory it names, edits the document its anchor
+points into, or edits a manifest of the kind that declares its command. `auto`
+reads the target branch from the CI's pull-request variables and diffs from the
+merge-base (`origin/main...HEAD`), so a shallow checkout needs `fetch-depth: 0`.
+A bare ref means `REF...HEAD`, and when the range ends at `HEAD` uncommitted and
+untracked changes count too, since the check reads the working tree. Anything
+left out is counted in the summary.
+
## The reverse view
The question "which documents talk about this file?" is worth asking before
diff --git a/docs/layers/REFACTORING.md b/docs/layers/REFACTORING.md
index b42a580ec..7a744e5f3 100644
--- a/docs/layers/REFACTORING.md
+++ b/docs/layers/REFACTORING.md
@@ -17,7 +17,7 @@ repowise health --refactoring-targets --format json
It runs **inside the health pass** (`init` / `update`), reusing data already
computed with no re-parse, **no LLM, no network**, inside the same <30s budget. The
-LLM layer (code generation) is a separate, strictly opt-in step ([below](#opt-in-code-generation)).
+LLM layer (code generation) is a separate, strictly opt-in step ([below](#optional-code-generation)).
<div align="center">
<img src="../../.github/assets/health-loop.svg" alt="repowise code-health loop: markers fan into three signals, the graph and git history locate risk, and refactoring intelligence emits concrete plans an agent executes" width="100%" />
diff --git a/docs/layers/TEST_INTELLIGENCE.md b/docs/layers/TEST_INTELLIGENCE.md
index 9138cf073..c8cdcbb8b 100644
--- a/docs/layers/TEST_INTELLIGENCE.md
+++ b/docs/layers/TEST_INTELLIGENCE.md
@@ -58,7 +58,7 @@ for everything below.
|-----------|-----------------|--------|
| **Per-file aggregate** | This file is 71% covered, merged across every test. | `untested_hotspot`, `coverage_gap`, `coverage_gradient` in [code health](CODE_HEALTH.md), the coverage dashboard |
| **Per-test map** | Test `tests/test_auth.py::test_login` covered lines 40-58 of `src/auth/service.py`. | `repowise impacted-tests`, `get_change_risk`'s `impacted_tests`, `get_risk`'s `tests_to_run` |
-| **Inferred map** (no ingest) | `tests/test_round_trips.py` imports `src/auth/service.py`, so it reaches it. | The fallback under every row above, always labelled `inferred` |
+| **Inferred map** (no ingest) | `tests/test_round_trips.py` imports `src/auth/service.py`, so it reaches it. | The fallback under every row above, always labelled `inferred` <!-- repowise-drift-ignore --> |
The aggregate always gets stored. The map is only built when the report carries
per-test contexts. A report without contexts still ingests fine, it just skips
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 9995fee9e..3b6c4c00f 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -763,6 +763,7 @@ with a close match. It is a suggestion to check, never applied.
| `--fail-on-confidence` | With `--check`, fail on findings at or above this confidence (default: 0.7) |
| `--baseline` | With `--check`, accept the findings recorded in this file; only new ones fail |
| `--write-baseline` | With `--check`, record the current findings to this file and exit 0 |
+| `--since` | With `--check`, gate only drift this change is answerable for: documents it edits, documents naming files it deletes or renames, anchors into documents it edits, and commands whose manifest it edits. A bare ref means `REF...HEAD` plus uncommitted changes; `auto` reads the target branch from CI |
| `--format` | Output: `table` (default), `json`, `markdown`, `github`, `sarif` |
| `--repo` | In workspace mode, target a specific repo (defaults to primary) |
| `--no-workspace` | Force single-repo mode |
@@ -778,6 +779,7 @@ repowise doc-drift --check --format github # annotations + step su
repowise doc-drift --check --format sarif > drift.sarif # code scanning upload
repowise doc-drift --check --write-baseline .doc-drift-baseline.json
repowise doc-drift --check --baseline .doc-drift-baseline.json
+repowise doc-drift --check --since auto # only drift this PR is answerable for
```
`github` prints workflow annotations and, when `$GITHUB_STEP_SUMMARY` is set,
@@ -787,7 +789,8 @@ Without `--check`, exits non-zero when there is no readable index, or when the
index predates drift storage; in both cases `--format json` still emits a
document naming the reason, not an empty finding list that would read as
a clean tree. With `--check`, exit codes are `0` gate passed, `1` gate failed,
-`2` could not evaluate (not a git repository, unreadable baseline).
+`2` could not evaluate (not a git repository, unreadable baseline, a `--since`
+revision that cannot be diffed).
---
diff --git a/docs/reference/COMPUTED_GLOSSARY.md b/docs/reference/COMPUTED_GLOSSARY.md
index fc7699b0f..ae3daea1b 100644
--- a/docs/reference/COMPUTED_GLOSSARY.md
+++ b/docs/reference/COMPUTED_GLOSSARY.md
@@ -13,7 +13,7 @@ workspace overlays, MCP responses, and CLI output.
| --- | --- | --- |
| Traversal and parsing | `packages/core/src/repowise/core/ingestion/traverser.py`, `packages/core/src/repowise/core/ingestion/parser.py`, `packages/core/src/repowise/core/ingestion/models.py` | Files, languages, entry points, symbols, imports, exports, calls, inheritance, parse errors, content hashes |
| Graph construction | `packages/core/src/repowise/core/ingestion/graph.py`, `call_resolver.py`, `heritage_resolver.py`, `framework_edges.py`, `dynamic_hints/` | File and symbol nodes, import/call/heritage/framework/dynamic/co-change edges, centrality, SCCs, communities, execution flows |
-| Git intelligence | `packages/core/src/repowise/core/ingestion/git_indexer.py` | Churn, ownership, hotspots, bus factor, co-change partners, significant commits, temporal scores, rename and merge signals |
+| Git intelligence | `packages/core/src/repowise/core/ingestion/git_indexer/` | Churn, ownership, hotspots, bus factor, co-change partners, significant commits, temporal scores, rename and merge signals |
| Analysis | `packages/core/src/repowise/core/analysis/` | Dead-code findings, decision records, decision staleness, security findings, PR blast radius, execution flows, communities |
| Generation | `packages/core/src/repowise/core/generation/` | Wiki page contexts, page types, source hashes, summaries, freshness, confidence decay, RAG context, job checkpoints, reports, costs |
| Workspace intelligence | `packages/core/src/repowise/core/workspace/` | Workspace repo scan, cross-repo co-changes, package dependencies, API contracts, contract links, workspace CLAUDE.md data |
@@ -303,7 +303,7 @@ workspace overlays, MCP responses, and CLI output.
| Session cost | Cumulative USD for one tracker instance. | `CostTracker.session_cost` | `2.37` |
| Session tokens | Cumulative input plus output tokens. | `CostTracker.session_tokens` | `845000` |
| Cost totals | DB aggregate grouped by operation, model, or day. | `CostTracker.totals()` | `{group: "file_page", calls: 42, cost_usd: 1.12}` |
-| CLI cost estimate | Pre-generation token/cost plan. | `packages/cli/src/repowise/cli/cost_estimator.py` | `{estimated_pages: 82, estimated_cost_usd: 4.60}` |
+| CLI cost estimate | Pre-generation token/cost plan. | `packages/cli/src/repowise/cli/cost_estimator/` | `{estimated_pages: 82, estimated_cost_usd: 4.60}` |
## Workspace Intelligence
diff --git a/docs/start/CI.md b/docs/start/CI.md
index 1f837387b..3919440df 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -58,7 +58,9 @@ git add .doc-drift-baseline.json
Then pass `--baseline .doc-drift-baseline.json` (or the action's
`doc-drift-baseline` input). Entries are keyed on the document, the reference
and its target, so an edit above a finding does not turn it back into a new
-one.
+one. Alternatively, `repowise doc-drift --check --since auto` judges only what
+the change is answerable for (documents it edits, and documents naming files it
+deletes or renames), which needs no baseline but does need `fetch-depth: 0`.
Security has a baseline too, for accepting a finding a change adds on purpose
(a documented test key, say): `repowise security check --write-baseline
diff --git a/packages/cli/src/repowise/cli/ci.py b/packages/cli/src/repowise/cli/ci.py
index 273fbe1c3..176f6cf6e 100644
--- a/packages/cli/src/repowise/cli/ci.py
+++ b/packages/cli/src/repowise/cli/ci.py
@@ -24,6 +24,12 @@ EXIT_CANNOT_EVALUATE = 2
#: Output formats every gating command offers; a command may add more (SARIF).
CI_FORMATS = ("table", "json", "markdown", "github")
+#: Why a diff against the base failed in CI, nearly always.
+SHALLOW_CLONE_HINT = (
+ "A shallow CI clone needs the base branch and enough history for a "
+ "merge-base (fetch-depth: 0, or git fetch --deepen)."
+)
+
def ci_notices(fmt: str) -> Any:
"""Where asides go: stdout for the table, stderr for every machine format."""
@@ -89,9 +95,7 @@ def change_lines(root: str, revspec: str | None) -> tuple[dict[str, set[int]], s
except ValueError as exc:
raise CannotEvaluateError(
"diff_failed",
- f"Could not diff {revspec}: {exc}. A shallow CI clone needs the base "
- "branch and enough history for a merge-base (fetch-depth: 0, or "
- "git fetch --deepen)."
+ f"Could not diff {revspec}: {exc}. {SHALLOW_CLONE_HINT}"
) from exc
except (subprocess.SubprocessError, OSError) as exc:
raise CannotEvaluateError("git_failed", f"Could not run git: {exc}") from exc
diff --git a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
index 95493bd78..669f3c2f7 100644
--- a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
@@ -15,6 +15,7 @@ import click
from repowise.cli.ci import (
CI_FORMATS,
EXIT_GATE_FAILED,
+ SHALLOW_CLONE_HINT,
append_step_summary,
cannot_evaluate,
ci_notices,
@@ -173,6 +174,7 @@ def _emit(
accepted: frozenset[str] = frozenset(),
) -> None:
"""Write *payload* in *fmt*; *gate* and *report* exist only under ``--check``."""
+ scope = payload.get("scope") or {}
from repowise.core.analysis.doc_drift import render
findings = payload["findings"]
@@ -193,6 +195,8 @@ def _emit(
gate=gate,
documents_scanned=report.documents_scanned if report is not None else None,
suppressed=report.suppressed if report is not None else 0,
+ scope_label=scope.get("revspec"),
+ out_of_scope=scope.get("out_of_scope", 0),
)
if fmt == "markdown":
click.echo(markdown)
@@ -229,6 +233,27 @@ def _refuse(code: str, message: str, fmt: str, *, remedy: str, repo: str) -> NoR
raise click.exceptions.Exit(1)
+def _scope_to(root: Path, since: str, findings: list[dict], fmt: str) -> tuple[list, dict]:
+ """Keep the findings the change *since* is answerable for; exit 2 when it cannot diff."""
+ import subprocess
+
+ from repowise.core.analysis.doc_drift.scope import scope_findings, scope_since
+ from repowise.core.ci.base import BaseNotFoundError, default_revspec
+
+ try:
+ revspec = default_revspec(str(root)) if since == "auto" else since
+ except BaseNotFoundError as exc:
+ cannot_evaluate(fmt, "base_not_found", str(exc))
+ try:
+ scope = scope_since(str(root), revspec)
+ except ValueError as exc:
+ cannot_evaluate(fmt, "diff_failed", f"Could not diff {revspec}: {exc}. {SHALLOW_CLONE_HINT}")
+ except (subprocess.SubprocessError, OSError) as exc:
+ cannot_evaluate(fmt, "git_failed", f"Could not run git: {exc}")
+ kept, left_out = scope_findings(findings, scope)
+ return kept, scope.summary(left_out)
+
+
def _run_check(
root: Path,
fmt: str,
@@ -239,6 +264,7 @@ def _run_check(
fail_on: float,
baseline_path: Path | None,
write_baseline_path: Path | None,
+ since: str | None = None,
) -> None:
from repowise.cli.helpers import silence_logs_for_machine_output
from repowise.core.analysis.doc_drift.baseline import (
@@ -261,6 +287,9 @@ def _run_check(
except LiveTreeError as exc:
cannot_evaluate(fmt, "not_a_git_repository", str(exc))
findings = _only_documents(findings, documents)
+ scope = None
+ if since is not None:
+ findings, scope = _scope_to(root, since, findings, fmt)
if write_baseline_path is not None:
try:
@@ -290,6 +319,8 @@ def _run_check(
suppressed=report.suppressed,
gate=gate.to_dict(),
)
+ if scope is not None:
+ payload["scope"] = scope
_emit(fmt, payload, gate=gate, report=report, accepted=baseline or frozenset())
if not gate.passed:
raise click.exceptions.Exit(EXIT_GATE_FAILED)
@@ -347,6 +378,17 @@ def _run_check(
default=None,
help="With --check, record the current findings to this file and exit 0.",
)
+ "--since",
+ metavar="REVSPEC",
+ default=None,
+ help=(
+ "With --check, gate only drift this change is answerable for: documents it "
+ "edits, documents naming files it deletes or renames, anchors into documents "
+ "it edits, and commands whose manifest it edits. A bare ref means REF...HEAD, "
+ "plus uncommitted changes; 'auto' reads the target branch from CI."
+ ),
+)
@click.option("--repo", "repo_alias", default=None, help="In workspace mode, target one repo.")
@click.option("--no-workspace", is_flag=True, default=False, help="Force single-repo mode.")
@format_option(
@@ -362,6 +404,7 @@ def doc_drift_command(
fail_on_confidence: float,
baseline_path: Path | None,
write_baseline_path: Path | None,
+ since: str | None,
repo_alias: str | None,
no_workspace: bool,
fmt: str,
@@ -369,6 +412,10 @@ def doc_drift_command(
"""Show documentation that the repository no longer matches."""
if not check and (baseline_path or write_baseline_path):
raise click.UsageError("--baseline and --write-baseline require --check.")
+ if since is not None and not check:
+ raise click.UsageError("--since requires --check.")
+ if since is not None and write_baseline_path:
+ raise click.UsageError("--write-baseline records every finding; drop --since.")
root = _repo_path(path, repo_alias, no_workspace, fmt)
if check:
@@ -381,6 +428,7 @@ def doc_drift_command(
fail_on=fail_on_confidence,
baseline_path=baseline_path,
write_baseline_path=write_baseline_path,
+ since=since,
)
return
diff --git a/packages/core/src/repowise/core/analysis/change_health/__init__.py b/packages/core/src/repowise/core/analysis/change_health/__init__.py
index 4da22f990..ec9157eea 100644
--- a/packages/core/src/repowise/core/analysis/change_health/__init__.py
+++ b/packages/core/src/repowise/core/analysis/change_health/__init__.py
@@ -13,23 +13,8 @@ The pipeline, in order::
from __future__ import annotations
-from .analyzer import RevisionAnalysis, RevisionHealthAnalyzer
-from .attribution import Attribution, FindingAttributor
-from .identity import change_finding_id, finding_key
-from .matcher import FindingMatcher, MatchedFinding, MatchResult
-from .models import (
- AnalysisFingerprint,
- AttributionBasis,
- ChangeFinding,
- ChangeHealthDelta,
- ChangeKind,
- DeltaStatus,
- FindingKey,
- RevisionId,
- ScopeCounts,
-)
-from .perf_delta import PerfOpportunityView, opportunities_for
-from .service import ChangeHealthDeltaService, DeltaRequest
+from typing import TYPE_CHECKING, Any
+
from .sources import (
FileChange,
GitRevisionSource,
@@ -39,6 +24,52 @@ from .sources import (
filter_changes,
)
+if TYPE_CHECKING:
+ from .analyzer import RevisionAnalysis, RevisionHealthAnalyzer
+ from .attribution import Attribution, FindingAttributor
+ from .identity import change_finding_id, finding_key
+ from .matcher import FindingMatcher, MatchedFinding, MatchResult
+ from .models import (
+ AnalysisFingerprint,
+ AttributionBasis,
+ ChangeFinding,
+ ChangeHealthDelta,
+ ChangeKind,
+ DeltaStatus,
+ FindingKey,
+ RevisionId,
+ ScopeCounts,
+ )
+ from .perf_delta import PerfOpportunityView, opportunities_for
+ from .service import ChangeHealthDeltaService, DeltaRequest
+
+# Bound on first access: the analyzer loads the whole health engine (~0.6s),
+# which a caller wanting only the diff shape in ``sources`` should not pay.
+_LAZY_EXPORTS: dict[str, str] = {
+ "RevisionAnalysis": "analyzer",
+ "RevisionHealthAnalyzer": "analyzer",
+ "Attribution": "attribution",
+ "FindingAttributor": "attribution",
+ "change_finding_id": "identity",
+ "finding_key": "identity",
+ "FindingMatcher": "matcher",
+ "MatchedFinding": "matcher",
+ "MatchResult": "matcher",
+ "AnalysisFingerprint": "models",
+ "AttributionBasis": "models",
+ "ChangeFinding": "models",
+ "ChangeHealthDelta": "models",
+ "ChangeKind": "models",
+ "DeltaStatus": "models",
+ "FindingKey": "models",
+ "RevisionId": "models",
+ "ScopeCounts": "models",
+ "PerfOpportunityView": "perf_delta",
+ "opportunities_for": "perf_delta",
+ "ChangeHealthDeltaService": "service",
+ "DeltaRequest": "service",
+}
+
__all__ = [
"AnalysisFingerprint",
"Attribution",
@@ -69,3 +100,12 @@ __all__ = [
"finding_key",
"opportunities_for",
]
+
+
+def __getattr__(name: str) -> Any:
+ if (module := _LAZY_EXPORTS.get(name)) is not None:
+ from importlib import import_module
+
+ return getattr(import_module(f"{__name__}.{module}"), name)
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
+
diff --git a/packages/core/src/repowise/core/analysis/change_health/sources.py b/packages/core/src/repowise/core/analysis/change_health/sources.py
index 3e0b79d1d..ab73c7564 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -14,8 +14,8 @@ from dataclasses import dataclass, field
from pathlib import Path
from typing import Protocol
-from ..change_risk.features import split_revspec
from ..changed_lines import FileDiff, is_shallow_root, parse_unified_diff
+from ..git_cli import split_revspec
GIT_TIMEOUT_SECONDS = 120
@@ -150,8 +150,10 @@ def _status_word(code: str) -> str:
class GitRevisionSource:
"""Local adapter over a Git checkout."""
- def __init__(self, repo_path: str) -> None:
+ def __init__(self, repo_path: str, *, hunks: bool = True) -> None:
self.repo_path = repo_path
+ # False for callers that read only which paths changed, not the lines.
+ self.hunks = hunks
# -- resolution ---------------------------------------------------------
@@ -226,7 +228,11 @@ class GitRevisionSource:
def _changes(self, diff_args: list[str]) -> list[FileChange]:
name_status = _git([*diff_args, "--name-status", "-z"], self.repo_path)
- diffs = parse_unified_diff(_git([*diff_args, "--unified=0", "--format="], self.repo_path))
+ diffs = (
+ parse_unified_diff(_git([*diff_args, "--unified=0", "--format="], self.repo_path))
+ if self.hunks
+ else {}
+ )
changes: list[FileChange] = []
for code, base_path, head_path in _iter_name_status(name_status):
status = _status_word(code)
diff --git a/packages/core/src/repowise/core/analysis/change_risk/features.py b/packages/core/src/repowise/core/analysis/change_risk/features.py
index 619682c24..a33b7469d 100644
--- a/packages/core/src/repowise/core/analysis/change_risk/features.py
+++ b/packages/core/src/repowise/core/analysis/change_risk/features.py
@@ -17,7 +17,6 @@ offline calibration. Two entry points:
from __future__ import annotations
import math
-import subprocess
from collections.abc import Iterable
from dataclasses import dataclass
from pathlib import Path
@@ -26,6 +25,9 @@ import pathspec
from ...ingestion.git_indexer._constants import is_fix_commit
+# Re-exported: callers across the package import these from here.
+from ..git_cli import GIT_TIMEOUT_SECONDS, _git, split_revspec # noqa: F401
+
#: ``ChangeFeatures.ref`` for a score of the uncommitted change. Not a revspec —
#: it names the unit scored, in the same slot a sha or ``base..head`` occupies.
WORKING_TREE_REF = "working tree"
@@ -56,54 +58,12 @@ class ChangeFeatures:
file_churn: tuple[tuple[str, int], ...] = ()
-# Generous ceiling: even a 200-commit numstat walk finishes in seconds. The
-# point is that a stuck git (lock contention, network filesystem) must fail
-# loud instead of hanging the caller's thread forever.
-GIT_TIMEOUT_SECONDS = 60
-
-
-def split_revspec(revspec: str) -> tuple[str, str, str] | None:
- """Split ``base..head`` / ``base...head`` into ``(base, sep, head)``.
-
- ``None`` for a single revision. An empty side means ``HEAD``, as in git. Three dots
- keep their git meaning (diff from the merge-base), so every reader of a
- range measures the same change.
- """
- sep = "..." if "..." in revspec else ".." if ".." in revspec else None
- if sep is None:
- return None
- base, _, head = revspec.partition(sep)
- return base or "HEAD", sep, head or "HEAD"
-
-
def revspec_head(revspec: str | None) -> str:
"""The revision a change ends at: a range's head, else the revision itself."""
parts = split_revspec(revspec) if revspec else None
return parts[2] if parts else revspec or "HEAD"
-def _git(args: list[str], cwd: str, *, check: bool = True) -> str:
- # stdin=DEVNULL: on MCP stdio transport a child that inherits the JSON-RPC
- # pipe handles can wedge the session (same failure mode _meta.py guards
- # against). check=True so a bad revspec raises instead of yielding empty
- # stdout, which used to score as a zero-feature "low risk" change.
- proc = subprocess.run(
- ["git", *args],
- cwd=cwd,
- capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- stdin=subprocess.DEVNULL,
- timeout=GIT_TIMEOUT_SECONDS,
- )
- if check and proc.returncode != 0:
- raise subprocess.CalledProcessError(
- proc.returncode, proc.args, output=proc.stdout, stderr=proc.stderr
- )
- return proc.stdout
-
-
def _accumulate_numstat(
numstat: str, extensions: tuple[str, ...], exclude_patterns: tuple[str, ...]
) -> tuple[int, int, int, set[str], set[str], list[int], list[tuple[str, int]]]:
diff --git a/packages/core/src/repowise/core/analysis/changed_lines.py b/packages/core/src/repowise/core/analysis/changed_lines.py
index dbf7f40e2..af7e169a7 100644
--- a/packages/core/src/repowise/core/analysis/changed_lines.py
+++ b/packages/core/src/repowise/core/analysis/changed_lines.py
@@ -26,7 +26,7 @@ from collections.abc import Iterable
from dataclasses import dataclass, field
from pathlib import Path
-from .change_risk.features import _git, split_revspec
+from .git_cli import _git, split_revspec
# ``@@ -a,b +c,d @@`` - both sides. ``b``/``d`` default to 1 when omitted; a
# count of 0 means "nothing on that side" (pure insertion / pure deletion).
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/render.py b/packages/core/src/repowise/core/analysis/doc_drift/render.py
index 76da73a50..2b2bfdfed 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/render.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/render.py
@@ -75,11 +75,14 @@ def render_markdown(
gate: GateResult | None,
documents_scanned: int | None = None,
suppressed: int = 0,
+ scope_label: str | None = None,
+ out_of_scope: int = 0,
) -> str:
"""Step-summary / PR-comment markdown: verdict first, then a capped table.
With a gate, only the failing findings are tabulated and a passing run
- stays short. Without one, every finding is.
+ stays short. Without one, every finding is. *scope_label* names the change
+ a predictive run was scoped to; *out_of_scope* counts what it left out.
"""
lines: list[str] = []
if gate is not None:
@@ -114,6 +117,8 @@ def render_markdown(
notes.append(f"{gate.below_threshold} below the threshold")
if suppressed:
notes.append(f"{plural(suppressed, 'reference')} suppressed inline")
+ if scope_label:
+ notes.append(f"scoped to {scope_label}, {out_of_scope} outside the change")
if notes:
lines.append("")
summary = "; ".join(notes)
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/scope.py b/packages/core/src/repowise/core/analysis/doc_drift/scope.py
new file mode 100644
index 000000000..aabf32921
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/doc_drift/scope.py
@@ -0,0 +1,162 @@
+"""Which drift findings a change is answerable for: the predictive gate.
+
+A repository with old drift cannot adopt a whole-tree gate without a baseline,
+and a baseline hides exactly the drift a change introduces when it deletes the
+file an old document names. This scopes the gate to the change instead. A
+finding is in scope when the change:
+
+* edits, adds or renames the document it sits in (``edited``);
+* deletes or renames away the file or directory it names (``removed``);
+* edits or removes the document its anchor points into (``anchor_host``);
+* edits the kind of manifest that declares its command (``manifest``).
+
+The last rule is per kind of manifest, not per file: a finding names a target,
+not the manifest expected to declare it. A change to any ``package.json``
+therefore scopes every ``npm`` command finding.
+
+Pure over :class:`~repowise.core.analysis.change_health.sources.FileChange`
+records and finding dicts, so a PR bot or hosted check run that lists a pull
+request's files through an API reuses it without a checkout.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable, Mapping
+from dataclasses import dataclass
+from typing import Any
+
+from ..change_health.sources import FileChange, GitRevisionSource
+from ..git_cli import _git, split_revspec
+from .constants import MANIFEST_NAMES
+from .extractor import is_checkable_document
+from .resolver import join_relative
+
+#: Command runner (the part of a command target before ``:``) to the manifest
+#: basenames that declare its targets.
+_RUNNER_MANIFESTS: dict[str, frozenset[str]] = {
+ "make": frozenset(n for n in MANIFEST_NAMES if n != "package.json"),
+ "npm": frozenset({"package.json"}),
+}
+
+
+@dataclass(frozen=True)
+class ChangeScope:
+ """The parts of a change the drift gate reads."""
+
+ label: str
+ """What was diffed, for display (``origin/main...HEAD``)."""
+ documents: frozenset[str]
+ """Checkable documents the change adds, edits or renames (head paths)."""
+ changed: frozenset[str]
+ """Every head path the change adds, edits or renames."""
+ removed: frozenset[str]
+ """Paths the change deletes or renames away (base paths)."""
+ manifests: frozenset[str]
+ """Basenames of the manifests the change touches on either side."""
+
+ @classmethod
+ def from_changes(cls, changes: Iterable[FileChange], *, label: str = "") -> ChangeScope:
+ changed: set[str] = set()
+ removed: set[str] = set()
+ for change in changes:
+ if change.head_path and not change.is_deleted:
+ changed.add(change.head_path)
+ if change.base_path and (change.is_deleted or change.is_rename):
+ removed.add(change.base_path)
+ touched = changed | removed
+ return cls(
+ label=label,
+ documents=frozenset(p for p in changed if is_checkable_document(p)),
+ changed=frozenset(changed),
+ removed=frozenset(removed),
+ manifests=frozenset(
+ name for p in touched if (name := p.rsplit("/", 1)[-1]) in MANIFEST_NAMES
+ ),
+ )
+
+ def summary(self, out_of_scope: int) -> dict[str, Any]:
+ """The scope as a report states it, beside the findings it kept."""
+ return {
+ "revspec": self.label,
+ "documents_changed": len(self.documents),
+ "paths_removed": len(self.removed),
+ "out_of_scope": out_of_scope,
+ }
+
+ def reason(self, finding: Mapping[str, Any]) -> str | None:
+ """Why the change is answerable for *finding*, or ``None`` when it is not."""
+ doc = str(finding["file_path"])
+ if doc in self.documents:
+ return "edited"
+ kind = str(finding["kind"])
+ target = str(finding["target"])
+ if kind in ("path", "link"):
+ if any(self._removes(p) for p in _spellings(doc, target)):
+ return "removed"
+ elif kind == "anchor":
+ host = target.partition("#")[0]
+ if host and any(
+ p in self.changed or p in self.removed for p in _spellings(doc, host)
+ ):
+ return "anchor_host"
+ elif kind == "command":
+ runner = target.partition(":")[0]
+ if self.manifests & _RUNNER_MANIFESTS.get(runner, frozenset()):
+ return "manifest"
+ return None
+
+ def _removes(self, path: str) -> bool:
+ """Whether *path*, a file or a directory, is gone because of the change."""
+ path = path.rstrip("/")
+ if not path:
+ return False
+ if path in self.removed:
+ return True
+ prefix = path + "/"
+ return any(r.startswith(prefix) for r in self.removed)
+
+
+def _spellings(doc: str, target: str) -> tuple[str, ...]:
+ """*target* as written and joined relative to *doc*: the resolver's two readings."""
+ relative = join_relative(doc, target)
+ return (target,) if relative == target else (target, relative)
+
+
+def scope_findings(
+ findings: Iterable[Mapping[str, Any]], scope: ChangeScope
+) -> tuple[list[dict], int]:
+ """``(in-scope findings, count left out)``; each kept row gains ``scope_reason``."""
+ kept: list[dict] = []
+ left_out = 0
+ for finding in findings:
+ why = scope.reason(finding)
+ if why is None:
+ left_out += 1
+ continue
+ kept.append({**finding, "scope_reason": why})
+ return kept, left_out
+
+
+def scope_since(root: str, revspec: str) -> ChangeScope:
+ """The scope of *revspec* in the checkout at *root*; ``ValueError`` on a bad diff.
+
+ ``base...head`` diffs from the merge-base, as change risk and changed lines
+ do, and a bare ref means ``ref...HEAD``. When the head is ``HEAD`` the
+ uncommitted and untracked changes count too, because the check reads the
+ working tree.
+ """
+ parts = split_revspec(revspec)
+ if parts is None:
+ revspec = f"{revspec}...HEAD"
+ parts = split_revspec(revspec)
+ source = GitRevisionSource(root, hunks=False)
+ changes = list(source.resolve(revspec).changes)
+ if parts is not None and parts[2] == "HEAD":
+ changes += source.resolve(None).changes
+ changes += [
+ FileChange(head_path=path, base_path=None, status="added")
+ for path in _git(["ls-files", "-z", "--others", "--exclude-standard"], root)
+ .split("\0")
+ if path
+ ]
+ return ChangeScope.from_changes(changes, label=revspec)
diff --git a/packages/core/src/repowise/core/analysis/git_cli.py b/packages/core/src/repowise/core/analysis/git_cli.py
new file mode 100644
index 000000000..59a08e04f
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/git_cli.py
@@ -0,0 +1,51 @@
+"""The two git helpers every change reader shares: split a revspec, run git.
+
+A leaf with no package imports, so a caller that only needs the diff shape
+(changed lines, the drift gate's scope) does not load change risk's baseline
+and, through it, GitPython.
+"""
+
+from __future__ import annotations
+
+import subprocess
+
+# Generous ceiling: even a 200-commit numstat walk finishes in seconds. The
+# point is that a stuck git (lock contention, network filesystem) must fail
+# loud instead of hanging the caller's thread forever.
+GIT_TIMEOUT_SECONDS = 60
+
+
+def split_revspec(revspec: str) -> tuple[str, str, str] | None:
+ """Split ``base..head`` / ``base...head`` into ``(base, sep, head)``.
+
+ ``None`` for a single revision. An empty side means ``HEAD``, as in git. Three dots
+ keep their git meaning (diff from the merge-base), so every reader of a
+ range measures the same change.
+ """
+ sep = "..." if "..." in revspec else ".." if ".." in revspec else None
+ if sep is None:
+ return None
+ base, _, head = revspec.partition(sep)
+ return base or "HEAD", sep, head or "HEAD"
+
+
+def _git(args: list[str], cwd: str, *, check: bool = True) -> str:
+ # stdin=DEVNULL: on MCP stdio transport a child that inherits the JSON-RPC
+ # pipe handles can wedge the session (same failure mode _meta.py guards
+ # against). check=True so a bad revspec raises instead of yielding empty
+ # stdout, which used to score as a zero-feature "low risk" change.
+ proc = subprocess.run(
+ ["git", *args],
+ cwd=cwd,
+ capture_output=True,
+ text=True,
+ encoding="utf-8",
+ errors="replace",
+ stdin=subprocess.DEVNULL,
+ timeout=GIT_TIMEOUT_SECONDS,
+ )
+ if check and proc.returncode != 0:
+ raise subprocess.CalledProcessError(
+ proc.returncode, proc.args, output=proc.stdout, stderr=proc.stderr
+ )
+ return proc.stdout
diff --git a/packages/core/src/repowise/core/analysis/health/README.md b/packages/core/src/repowise/core/analysis/health/README.md
index 064493eb0..5017b75c1 100644
--- a/packages/core/src/repowise/core/analysis/health/README.md
+++ b/packages/core/src/repowise/core/analysis/health/README.md
@@ -192,8 +192,8 @@ parallel path automatically when `len(parsed_files) >= 500`.
## Where to look in the codebase
-- CLI: `packages/cli/src/repowise/cli/commands/health_cmd.py`,
- `status_cmd.py`, `update_cmd.py`.
+- CLI: `packages/cli/src/repowise/cli/commands/health_cmd/`,
+ `status_cmd.py`, `update_cmd/`.
- MCP tools: `packages/server/src/repowise/server/mcp_server/tool_health/`
+ enrichments in `tool_risk.py`, `tool_context.py`, `tool_overview.py`.
- API: `packages/server/src/repowise/server/routers/code_health.py`.
diff --git a/packages/core/src/repowise/core/generation/page_generator/README.md b/packages/core/src/repowise/core/generation/page_generator/README.md
index 463f5d1f9..b34e8872e 100644
--- a/packages/core/src/repowise/core/generation/page_generator/README.md
+++ b/packages/core/src/repowise/core/generation/page_generator/README.md
@@ -68,6 +68,5 @@ from repowise.core.generation.page_generator import PageGenerator, SYSTEM_PROMPT
## Tests
- `tests/unit/generation/test_page_generator.py`
-- `tests/unit/generation/test_page_generator_tiering.py`
- `tests/integration/test_generation_pipeline.py`
"""
diff --git a/plugins/claude-code/DEVELOPER.md b/plugins/claude-code/DEVELOPER.md
index a621d1357..ec6bece85 100644
--- a/plugins/claude-code/DEVELOPER.md
+++ b/plugins/claude-code/DEVELOPER.md
@@ -90,7 +90,7 @@ The plugin bundles the same `repowise-augment` `PostToolUse` hook that
`repowise init` writes to `~/.claude/settings.json`. A user with both installed
would otherwise get duplicate enrichment on a single tool event. `repowise-augment`
guards against this: `_emit_response` claims a short-lived, content-keyed lock
-(`_claim_emission` in `packages/cli/src/repowise/cli/commands/augment_cmd.py`)
+(`_claim_emission` in `packages/cli/src/repowise/cli/commands/augment_cmd/command.py`)
so exactly one of the two firings emits. The guard is fail-open — if anything
goes wrong it emits rather than risk swallowing a real message.
diff --git a/tests/unit/cli/test_doc_drift_check.py b/tests/unit/cli/test_doc_drift_check.py
index 655e9a7cc..86a022000 100644
--- a/tests/unit/cli/test_doc_drift_check.py
+++ b/tests/unit/cli/test_doc_drift_check.py
@@ -221,3 +221,83 @@ def test_end_to_end_on_a_real_working_tree(tmp_path):
(finding,) = payload["findings"]
assert finding["target"] == "src/tools/cli.py"
assert finding["suggestion"] == "src/tools/cli/"
+
+
+def _scoped(monkeypatch, *changes):
+ from repowise.core.analysis.doc_drift import scope as scope_mod
+
+ scope = scope_mod.ChangeScope.from_changes(changes, label="main...HEAD")
+ monkeypatch.setattr(scope_mod, "scope_since", lambda root, revspec: scope)
+
+
+def test_since_gates_only_drift_the_change_is_answerable_for(monkeypatch, tmp_path):
+ from repowise.core.analysis.change_health.sources import FileChange
+
+ _scoped(monkeypatch, FileChange(head_path=None, base_path="src/gone.py", status="deleted"))
+ findings = [_finding(), _finding(file_path="docs/b.md", target="src/old.py")]
+ result = _invoke(
+ monkeypatch, tmp_path, findings, ["--since", "main...HEAD", "--format", "json"]
+ )
+ payload = json.loads(result.output)
+ assert result.exit_code == 1
+ assert [f["file_path"] for f in payload["findings"]] == ["docs/a.md"]
+ assert payload["findings"][0]["scope_reason"] == "removed"
+ assert payload["scope"] == {
+ "revspec": "main...HEAD",
+ "documents_changed": 0,
+ "paths_removed": 1,
+ "out_of_scope": 1,
+ }
+
+
+def test_since_passes_when_the_drift_predates_the_change(monkeypatch, tmp_path):
+ _scoped(monkeypatch)
+ result = _invoke(monkeypatch, tmp_path, [_finding()], ["--since", "main...HEAD"])
+ assert result.exit_code == 0
+ assert "Gate passed" in result.output
+
+
+def test_since_markdown_names_the_scope(monkeypatch, tmp_path):
+ _scoped(monkeypatch)
+ result = _invoke(
+ monkeypatch, tmp_path, [_finding()], ["--since", "main...HEAD", "--format", "markdown"]
+ )
+ assert "scoped to main...HEAD, 1 outside the change" in result.output
+
+
+def test_since_auto_without_a_base_exits_two(monkeypatch, tmp_path):
+ from repowise.core.ci import base
+
+ def _none(root, env=None):
+ raise base.BaseNotFoundError("no base")
+
+ monkeypatch.setattr(base, "default_revspec", _none)
+ result = _invoke(monkeypatch, tmp_path, [_finding()], ["--since", "auto", "--format", "json"])
+ assert result.exit_code == 2
+ assert json.loads(result.output)["error"] == "base_not_found"
+
+
+def test_since_on_a_bad_revision_exits_two(monkeypatch, tmp_path):
+ from repowise.core.analysis.doc_drift import scope as scope_mod
+
+ def _bad(root, revspec):
+ raise ValueError("unknown revision")
+
+ monkeypatch.setattr(scope_mod, "scope_since", _bad)
+ result = _invoke(
+ monkeypatch, tmp_path, [_finding()], ["--since", "nope...HEAD", "--format", "json"]
+ )
+ assert result.exit_code == 2
+ assert json.loads(result.output)["error"] == "diff_failed"
+
+
+def test_since_requires_check_and_refuses_write_baseline(monkeypatch, tmp_path):
+ monkeypatch.setattr(doc_drift_cmd, "_repo_path", lambda *a, **k: tmp_path)
+ runner = CliRunner()
+ alone = runner.invoke(doc_drift_cmd.doc_drift_command, ["--since", "main...HEAD"])
+ assert alone.exit_code == 2
+ both = runner.invoke(
+ doc_drift_cmd.doc_drift_command,
+ ["--check", "--since", "main...HEAD", "--write-baseline", str(tmp_path / "b.json")],
+ )
+ assert both.exit_code == 2
diff --git a/tests/unit/doc_drift/test_scope.py b/tests/unit/doc_drift/test_scope.py
new file mode 100644
index 000000000..547e964b2
--- /dev/null
+++ b/tests/unit/doc_drift/test_scope.py
@@ -0,0 +1,166 @@
+"""The predictive gate's scope: which findings a change is answerable for."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+
+import pytest
+
+from repowise.core.analysis.change_health.sources import FileChange
+from repowise.core.analysis.doc_drift.scope import ChangeScope, scope_findings, scope_since
+
+
+def _change(status, base=None, head=None):
+ return FileChange(head_path=head, base_path=base, status=status)
+
+
+def _finding(file_path="docs/a.md", kind="path", target="src/gone.py"):
+ return {"file_path": file_path, "kind": kind, "target": target, "confidence": 0.9}
+
+
+def _scope(*changes):
+ return ChangeScope.from_changes(changes, label="base...HEAD")
+
+
+def test_an_edited_document_is_in_scope():
+ scope = _scope(_change("modified", "docs/a.md", "docs/a.md"))
+ assert scope.reason(_finding()) == "edited"
+
+
+def test_a_renamed_document_is_in_scope_under_its_new_path():
+ scope = _scope(_change("renamed", "docs/old.md", "docs/a.md"))
+ assert scope.reason(_finding()) == "edited"
+ assert scope.removed == {"docs/old.md"}
+
+
+def test_an_untouched_document_naming_a_deleted_file_is_in_scope():
+ scope = _scope(_change("deleted", "src/gone.py", None))
+ assert scope.reason(_finding()) == "removed"
+
+
+def test_a_file_renamed_away_counts_as_removed():
+ scope = _scope(_change("renamed", "src/gone.py", "src/here.py"))
+ assert scope.reason(_finding()) == "removed"
+
+
+def test_a_directory_emptied_by_the_change_is_removed():
+ scope = _scope(_change("deleted", "src/pkg/mod.py", None))
+ assert scope.reason(_finding(target="src/pkg/")) == "removed"
+ assert scope.reason(_finding(target="src/pk")) is None
+
+
+def test_a_link_is_matched_relative_to_its_document():
+ scope = _scope(_change("deleted", "docs/guide/setup.md", None))
+ finding = _finding(file_path="docs/guide/index.md", kind="link", target="setup.md")
+ assert scope.reason(finding) == "removed"
+
+
+def test_an_anchor_into_an_edited_document_is_in_scope():
+ scope = _scope(_change("modified", "docs/guide.md", "docs/guide.md"))
+ finding = _finding(file_path="docs/a.md", kind="anchor", target="guide.md#setup")
+ assert scope.reason(finding) == "anchor_host"
+
+
+def test_a_command_is_scoped_by_its_runners_manifest():
+ scope = _scope(_change("modified", "web/package.json", "web/package.json"))
+ assert scope.reason(_finding(kind="command", target="npm:test")) == "manifest"
+ assert scope.reason(_finding(kind="command", target="make:build")) is None
+
+
+def test_a_deleted_makefile_scopes_make_commands():
+ scope = _scope(_change("deleted", "Makefile", None))
+ assert scope.reason(_finding(kind="command", target="make:build")) == "manifest"
+
+
+def test_unrelated_drift_is_left_out_and_counted():
+ scope = _scope(_change("modified", "src/other.py", "src/other.py"))
+ kept, left_out = scope_findings([_finding(), _finding(file_path="docs/b.md")], scope)
+ assert kept == []
+ assert left_out == 2
+
+
+def test_kept_rows_carry_their_reason_and_are_copies():
+ scope = _scope(_change("modified", "docs/a.md", "docs/a.md"))
+ original = _finding()
+ (kept,), _ = scope_findings([original], scope)
+ assert kept["scope_reason"] == "edited"
+ assert "scope_reason" not in original
+
+
[email protected](shutil.which("git") is None, reason="git not installed")
+def test_scope_since_reads_deletions_and_renames_from_the_merge_base(tmp_path):
+ def git(*args):
+ subprocess.run(
+ ["git", "-C", str(tmp_path), "-c", "user.email=t@t", "-c", "user.name=t", *args],
+ check=True,
+ capture_output=True,
+ )
+
+ for rel in ("src/gone.py", "src/moved.py", "docs/a.md"):
+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / rel).write_text(f"{rel}\n" * 5, encoding="utf-8")
+ git("init", "-q", "-b", "main")
+ git("add", ".")
+ git("commit", "-qm", "base")
+ git("checkout", "-qb", "change")
+ git("rm", "-q", "src/gone.py")
+ git("mv", "src/moved.py", "src/renamed.py")
+ (tmp_path / "docs/a.md").write_text("edited\n", encoding="utf-8")
+ git("commit", "-qam", "change")
+ # Lands on the base after the fork: three dots must leave it out.
+ git("checkout", "-q", "main")
+ (tmp_path / "docs/b.md").write_text("later\n", encoding="utf-8")
+ git("add", ".")
+ git("commit", "-qm", "later")
+ git("checkout", "-q", "change")
+
+ scope = scope_since(str(tmp_path), "main...HEAD")
+ assert scope.documents == {"docs/a.md"}
+ assert scope.removed == {"src/gone.py", "src/moved.py"}
+ assert scope.label == "main...HEAD"
+
+
[email protected](shutil.which("git") is None, reason="git not installed")
+def test_scope_since_raises_value_error_on_an_unknown_revision(tmp_path):
+ subprocess.run(["git", "-C", str(tmp_path), "init", "-q"], check=True)
+ with pytest.raises(ValueError):
+ scope_since(str(tmp_path), "nope...HEAD")
+
+
+def test_importing_the_scope_leaves_the_health_engine_unloaded():
+ import sys
+
+ code = (
+ "import sys, repowise.core.analysis.doc_drift.scope; "
+ "print('repowise.core.analysis.change_health.analyzer' in sys.modules)"
+ )
+ out = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=True)
+ assert out.stdout.strip() == "False"
+
+
[email protected](shutil.which("git") is None, reason="git not installed")
+def test_a_bare_ref_means_the_change_since_it_including_the_working_tree(tmp_path):
+ def git(*args):
+ subprocess.run(
+ ["git", "-C", str(tmp_path), "-c", "user.email=t@t", "-c", "user.name=t", *args],
+ check=True,
+ capture_output=True,
+ )
+
+ for rel in ("src/committed.py", "src/uncommitted.py", "docs/a.md"):
+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / rel).write_text("x\n", encoding="utf-8")
+ git("init", "-q", "-b", "main")
+ git("add", ".")
+ git("commit", "-qm", "base")
+ git("checkout", "-qb", "change")
+ git("rm", "-q", "src/committed.py")
+ git("commit", "-qm", "delete")
+ (tmp_path / "src/uncommitted.py").unlink()
+ (tmp_path / "docs/new.md").write_text("new\n", encoding="utf-8")
+
+ scope = scope_since(str(tmp_path), "main")
+ assert scope.label == "main...HEAD"
+ assert scope.removed == {"src/committed.py", "src/uncommitted.py"}
+ assert scope.documents == {"docs/new.md"}