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): flag renamed or deleted code symbols named in docs, and suggest the fix on every surface (#2661)

Raghav Chamadiyac8e99d71b401
diff --git a/docs/layers/DOC_DRIFT.md b/docs/layers/DOC_DRIFT.md
index bef6a0d5b..681de97c2 100644
--- a/docs/layers/DOC_DRIFT.md
+++ b/docs/layers/DOC_DRIFT.md
@@ -5,11 +5,15 @@ reference, a command. Repowise already holds the graph those claims are about,
so it checks them and reports the ones the tree refutes.
This is part of the code-health layer, not a separate analysis you run. It
-happens on every `init` and every `update`, needs no model, and costs nothing.
+happens on every `init` and every `update` and needs no model. The four
+file-level kinds take well under a second; the `symbol` kind reads git history
+and, measured on a repository of about 4,800 files and 190 documents, adds
+about 7 seconds to `init` and 1 to 4 seconds to an `update`, which re-resolves
+only the references the update could have changed.
## What it checks
-Four classes of reference, all of them things the repository itself can settle:
+Five classes of reference, all of them things the repository itself can settle:
| Kind | The claim | How it is refuted |
|---|---|---|
@@ -17,11 +21,40 @@ Four classes of reference, all of them things the repository itself can settle:
| `link` | a document links to another document | the target is not there |
| `anchor` | a link points at a heading | the heading was renamed or removed |
| `command` | a document tells you to run something | the manifest no longer declares it |
+| `symbol` | a document names a function, class or method | it was defined when the line was written and is defined nowhere now |
The anchor case is the one people are most surprised by, because it is the one
that rots silently: renaming a heading breaks every link into it, and nothing
in an ordinary toolchain notices.
+### Symbols
+
+Backticks in prose mean "this is literal text", not "this is code", so a
+backticked word the code does not define is usually just a word: `string`,
+`true`, a config key, an invented example. The `symbol` kind therefore never
+flags a token for being absent. It flags one only when git proves it was a
+symbol when the document said it:
+
+1. The token looks like code: `parse_config()`, `ChangeDetector.detect`,
+ `my_func` or `parseConfig`. All-caps constants, plain words and short names
+ are never candidates.
+2. The index holds no symbol by that name, and no file other than a document
+ mentions it as a word. A mention could be a definition the index skipped,
+ so a mentioned name is not treated as a reference at all.
+3. `git blame` finds the commit that last wrote the document line, and at that
+ commit a source file, parsed with Repowise's own parser, defined a symbol
+ with exactly that name. A definition in a test file does not count. A name
+ that only appeared in a comment or a string, or never appeared at all, was
+ never a symbol reference and is not reported.
+
+When the defining file still exists, or git records where it moved, and it now
+defines exactly one new symbol of the same kind whose name is close to the old
+one, the finding suggests the reference with that name.
+
+This kind needs an index and git history. `init` and `update` run it; in CI it
+runs only when asked for with `--kind symbol`. Its git work has fixed limits
+per run, and anything past them is counted as uncheckable (`over-budget`).
+
## What it deliberately does not check
Most sentences in a repository are not checkable, and this analysis does not
@@ -63,6 +96,7 @@ When the tree says where a reference probably went, the finding says so too:
| Renamed in git | git history records the file moving, and the new path exists |
| Similar heading | the linked heading is gone and one declared heading is a close match |
| Similar target | the `make` or `npm run` target is gone and one declared target is a close match |
+| Renamed symbol | the symbol's defining file shows it renamed, and the new name is defined now |
A suggestion is evidence for you to check, not an edit. It never changes a
finding's confidence, and Repowise never rewrites your documents.
@@ -90,7 +124,11 @@ it. Silenced references are counted in the report, never dropped quietly.
`--check` reads the working tree directly. It needs git and nothing else: no
index, no model, a few seconds on a large repository. It exits `1` when a
finding at or above `--fail-on-confidence` (default 0.7) is present, and `2`
-when it cannot evaluate.
+when it cannot evaluate. `--kind symbol` adds symbol references when an index
+exists (it exits `2` without one), and it needs full history
+(`fetch-depth: 0`), since a shallow clone blames every line to its boundary
+commit. A baseline written without `--kind symbol` holds no symbol entries, so
+record it again when you add the kind.
```bash
repowise doc-drift --check --format github
@@ -101,7 +139,17 @@ summary to the job page. `--format sarif` produces a file for GitHub code
scanning, `--format gitlab` a GitLab Code Quality report for the merge request
widget (baselined findings left out), and `--format markdown` is for posting a
comment yourself. In the Code Quality report a finding at or above
-`--fail-on-confidence` is `major` and one below it `minor`. Full history
+`--fail-on-confidence` is `major` and one below it `minor`.
+
+A finding with a likely replacement carries it into every format. The JSON has
+`suggestion`, plus `suggested_line` (the whole document line with every copy of
+the reference replaced) and `suggestion_columns` (each replaced span: 1-based,
+end exclusive, in UTF-16 code units). SARIF carries a `fixes` entry that
+replaces exactly those spans, the markdown summary adds a `suggestion` block
+with the replaced line under each finding, ready to paste into a pull-request
+review, and the Code Quality description ends with "Likely now:" and the
+replacement. Findings read back from an index keep the suggestion but not the
+placed line. Full history
(`fetch-depth: 0`) is optional and only improves the rename suggestions. The
GitHub Action and GitLab template that run it beside the other gates are in
[Repowise in CI](../start/CI.md).
@@ -129,7 +177,8 @@ 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`
+points into, edits a manifest of the kind that declares its command, or edits
+or removes a file that defined its symbol. `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
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index a68cfd4ab..073378184 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -768,20 +768,21 @@ clean run is not a claim that every sentence is true.
Where the analysis can see a likely replacement, a finding carries it: a module
that became a package, a file git recorded as renamed, a heading or build target
-with a close match. It is a suggestion to check, never applied.
+with a close match, a symbol its defining file shows renamed. It is a suggestion
+to check, never applied.
**Options:**
| Flag | Description |
|------|-------------|
| `--min-confidence` | Hide findings below this confidence (default: show everything stored) |
-| `--kind` | Only this reference class: `path`, `link`, `anchor`, `command`. Repeatable |
+| `--kind` | Only this reference class: `path`, `link`, `anchor`, `command`, `symbol`. Repeatable |
| `--document` | Only findings in this document. Repeatable |
-| `--check` | Read the working tree without an index and gate on the result |
+| `--check` | Read the working tree without an index and gate on the result. With `--kind symbol` it checks symbol references, which needs an index (exit 2 without one) |
| `--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 |
+| `--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, commands whose manifest it edits, and symbols whose defining file it edits or removes. A bare ref means `REF...HEAD` plus uncommitted changes; `auto` reads the target branch from CI |
| `--format` | Output: `table` (default), `json`, `markdown`, `github`, `sarif`, `gitlab` (GitLab Code Quality report) |
| `--repo` | In workspace mode, target a specific repo (defaults to primary) |
| `--no-workspace` | Force single-repo mode |
diff --git a/docs/start/CI.md b/docs/start/CI.md
index 04585809b..e677b74a5 100644
--- a/docs/start/CI.md
+++ b/docs/start/CI.md
@@ -18,6 +18,11 @@ resolution, described once below. Each layer's own page has the detail:
[security](../layers/SECURITY.md#in-ci-repowise-security-check),
[change risk](../layers/CHANGE_RISK.md#in-ci).
+Doc drift's `--check` needs no index. `--kind symbol` adds symbol references
+(names of functions and classes a document mentions) and needs an index, so it
+exits `2` without one. It also reads `git blame`: in a shallow clone every line
+blames to the boundary commit, so give that job `fetch-depth: 0`.
+
## What every gate does the same way
**Exit codes.** `0` passed, or had nothing to judge. `1` the change failed the
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 ab93a32b5..d182d95eb 100644
--- a/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/doc_drift_cmd.py
@@ -78,19 +78,43 @@ async def _read(root: Path, *, min_confidence: float | None, kinds: tuple[str, .
return [serialize_doc_drift_row(r) for r in rows]
+async def _index_symbol_names(root: Path) -> frozenset[str] | None:
+ """Every symbol name the index at *root* holds, or ``None`` when none opens.
+
+ Read-only: the schema reconcile is skipped, so a CI read writes nothing.
+ """
+ from sqlalchemy.exc import SQLAlchemyError
+
+ from repowise.core.persistence.crud import get_symbol_names
+
+ async with repo_index_session(root, reconcile=False) as opened:
+ if opened is None:
+ return None
+ session, repo_id = opened
+ try:
+ return await get_symbol_names(session, repo_id)
+ except (SQLAlchemyError, OSError):
+ return None
+
+
def _read_live(
root: Path,
*,
min_confidence: float | None,
kinds: tuple[str, ...],
+ symbol_names: frozenset[str] | None = None,
) -> tuple[Any, list[dict[str, Any]]]:
- """Run the analyzer over the working tree: ``(report, finding dicts)``."""
+ """Run the analyzer over the working tree: ``(report, finding dicts)``.
+
+ The ``symbol`` kind runs only with *symbol_names*, which ``--kind symbol``
+ reads from the index.
+ """
from repowise.core.analysis.doc_drift.live import run_live
from repowise.core.analysis.doc_drift.serialize import serialize_finding
config = {"min_confidence": min_confidence} if min_confidence is not None else None
- report = run_live(root, config=config)
- findings = [serialize_finding(f) for f in report.findings]
+ report = run_live(root, config=config, symbol_names=symbol_names)
+ findings = [serialize_finding(f, live=True) for f in report.findings]
if kinds:
findings = [f for f in findings if f["kind"] in kinds]
return report, findings
@@ -275,11 +299,6 @@ def _run_check(
since: str | None = None,
) -> None:
from repowise.cli.helpers import silence_logs_for_machine_output
- from repowise.core.analysis.doc_drift.baseline import (
- BaselineError,
- read_baseline,
- write_baseline,
- )
from repowise.core.analysis.doc_drift.gate import evaluate_gate
from repowise.core.analysis.doc_drift.live import LiveTreeError
@@ -290,8 +309,11 @@ def _run_check(
f"[yellow]--min-confidence {min_confidence:.2f} is above --fail-on-confidence "
f"{fail_on:.2f}; findings between them are hidden from the gate.[/yellow]"
)
+ symbol_names = _check_symbol_names(root, kinds, fmt)
try:
- report, findings = _read_live(root, min_confidence=min_confidence, kinds=kinds)
+ report, findings = _read_live(
+ root, min_confidence=min_confidence, kinds=kinds, symbol_names=symbol_names
+ )
except LiveTreeError as exc:
cannot_evaluate(fmt, "not_a_git_repository", str(exc))
findings = _only_documents(findings, documents)
@@ -300,25 +322,10 @@ def _run_check(
findings, scope = _scope_to(root, since, findings, fmt)
if write_baseline_path is not None:
- try:
- written = write_baseline(write_baseline_path, findings)
- except OSError as exc:
- cannot_evaluate(
- fmt, "baseline_unwritable", f"cannot write baseline {write_baseline_path}: {exc}"
- )
- ci_notices(fmt).print(
- f"Recorded {len(findings)} finding(s) as {written} baseline entr"
- f"{'y' if written == 1 else 'ies'} in {write_baseline_path}."
- )
+ _write_check_baseline(write_baseline_path, findings, fmt)
return
- baseline = None
- if baseline_path is not None:
- try:
- baseline = read_baseline(baseline_path)
- except BaselineError as exc:
- cannot_evaluate(fmt, "baseline_unreadable", str(exc))
-
+ baseline = _read_check_baseline(baseline_path, fmt)
gate = evaluate_gate(findings, fail_on=fail_on, baseline=baseline)
payload = _payload(root, findings, min_confidence)
payload.update(
@@ -334,6 +341,44 @@ def _run_check(
raise click.exceptions.Exit(EXIT_GATE_FAILED)
+def _check_symbol_names(root: Path, kinds: tuple[str, ...], fmt: str) -> frozenset[str] | None:
+ """The index's symbol names when ``--kind symbol`` asks; exit 2 without an index."""
+ if DriftKind.SYMBOL.value not in kinds:
+ return None
+ names = run_async(_index_symbol_names(root))
+ if names is None:
+ cannot_evaluate(
+ fmt,
+ "no_index",
+ f"--kind symbol needs a Repowise index at {root}; run 'repowise init' there.",
+ )
+ return names
+
+
+def _write_check_baseline(path: Path, findings: list[dict], fmt: str) -> None:
+ from repowise.core.analysis.doc_drift.baseline import write_baseline
+
+ try:
+ written = write_baseline(path, findings)
+ except OSError as exc:
+ cannot_evaluate(fmt, "baseline_unwritable", f"cannot write baseline {path}: {exc}")
+ ci_notices(fmt).print(
+ f"Recorded {len(findings)} finding(s) as {written} baseline entr"
+ f"{'y' if written == 1 else 'ies'} in {path}."
+ )
+
+
+def _read_check_baseline(path: Path | None, fmt: str) -> frozenset[str] | None:
+ from repowise.core.analysis.doc_drift.baseline import BaselineError, read_baseline
+
+ if path is None:
+ return None
+ try:
+ return read_baseline(path)
+ except BaselineError as exc:
+ cannot_evaluate(fmt, "baseline_unreadable", str(exc))
+
+
@click.command("doc-drift")
@click.argument("path", required=False, default=None)
@click.option(
@@ -363,7 +408,10 @@ def _run_check(
"--check",
is_flag=True,
default=False,
- help="Read the working tree without an index and exit 1 when the gate fails.",
+ help=(
+ "Read the working tree without an index and exit 1 when the gate fails. "
+ "With --kind symbol it also checks symbol references, which needs an index."
+ ),
)
@click.option(
"--fail-on-confidence",
@@ -393,7 +441,8 @@ def _run_check(
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, "
+ "it edits, commands whose manifest it edits, and symbols whose defining file "
+ "it edits or removes. A bare ref means REF...HEAD, "
"plus uncommitted changes; 'auto' reads the target branch from CI."
),
)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 0fc4d706a..b2eff1130 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -1494,7 +1494,12 @@ def run_update(
timings=timings,
)
doc_drift_report = _run_doc_drift_partial(
- graph_builder, source_map, repo_path=repo_path, timings=timings
+ graph_builder,
+ source_map,
+ repo_path=repo_path,
+ timings=timings,
+ base_ref=base_ref,
+ file_diffs=file_diffs,
)
# Partial health has consumed the per-file ``BlameIndex``; drop it before
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
index bf3631f04..f41a912ec 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/incremental.py
@@ -257,10 +257,17 @@ def _run_doc_drift_partial(
*,
repo_path: Any | None = None,
timings: PhaseTimings | None = None,
+ base_ref: str | None = None,
+ file_diffs: list[Any] = (),
) -> Any | None:
"""Re-check the repo's markdown against the tree. Delegates to core."""
- from repowise.core.pipeline.incremental import run_doc_drift_partial
+ from repowise.core.pipeline.incremental import DocDriftUpdate, run_doc_drift_partial
return run_doc_drift_partial(
- graph_builder, source_map, repo_path=repo_path, log=console.print, timings=timings
+ graph_builder,
+ source_map,
+ repo_path=repo_path,
+ log=console.print,
+ timings=timings,
+ update=DocDriftUpdate.from_file_diffs(base_ref, file_diffs),
)
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index 1522d58da..31dd097b7 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -217,11 +217,15 @@ def get_db_url_for_repo(repo_path: Path) -> str:
@contextlib.asynccontextmanager
-async def repo_index_session(root: Path) -> AsyncIterator[tuple[AsyncSession, str] | None]:
+async def repo_index_session(
+ root: Path, *, reconcile: bool = True
+) -> AsyncIterator[tuple[AsyncSession, str] | None]:
"""Open the repo-local store, yielding ``(session, repo_id)`` or ``None``.
A scoring or scanning command must never fail because the index is absent,
stale or locked, so every storage error yields ``None`` instead.
+ ``reconcile=False`` skips the schema reconcile, so a caller that only reads
+ writes nothing to the store.
"""
from sqlalchemy.exc import SQLAlchemyError
@@ -239,7 +243,8 @@ async def repo_index_session(root: Path) -> AsyncIterator[tuple[AsyncSession, st
opened: tuple[AsyncSession, str] | None = None
try:
url = get_db_url_for_repo(root)
- await reconcile_schema_best_effort(url)
+ if reconcile:
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
stack.push_async_callback(engine.dispose)
factory = create_session_factory(engine)
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/__init__.py b/packages/core/src/repowise/core/analysis/doc_drift/__init__.py
index 316296150..04c47198d 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/__init__.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/__init__.py
@@ -3,8 +3,8 @@
Documents make assertions about the repository. This package checks the ones
that are checkable, and is explicit about the ones that are not.
-Four reference classes ship: ``path``, ``link``, ``anchor`` and ``command``.
-A fifth, ``symbol``, was measured and rejected --- see
+Five reference classes ship: ``path``, ``link``, ``anchor``, ``command`` and
+``symbol``. The last needs an index and git history; see
:class:`~.models.DriftKind`.
"""
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/analyzer.py b/packages/core/src/repowise/core/analysis/doc_drift/analyzer.py
index 53f29f8ec..a498c94d9 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/analyzer.py
@@ -13,6 +13,7 @@ from __future__ import annotations
import os
from collections.abc import Callable
+from dataclasses import dataclass, field
from datetime import UTC, datetime
from functools import partial
from pathlib import Path
@@ -26,16 +27,31 @@ from .constants import (
MAX_DOC_BYTES,
bucket_confidences,
)
-from .extractor import extract_with_suppressed, is_checkable_document, is_guide_document
+from .extractor import (
+ extract_with_suppressed,
+ is_checkable_document,
+ is_guide_document,
+ symbol_name,
+)
from .models import (
DocDriftFindingData,
DocDriftReport,
+ DocReference,
DriftKind,
DriftVerdict,
ResolvedDocReference,
+ SymbolScope,
)
from .resolver import RepoIndex, Resolution, resolve
-from .suggest import RenameLookup, Suggestion, git_renames, suggest_all
+from .suggest import (
+ NO_SUGGESTION,
+ RenameLookup,
+ Suggestion,
+ apply_suggestion,
+ git_renames,
+ suggest_all,
+)
+from .symbols import SymbolMiss, SymbolOptions, SymbolRecheck, resolve_symbols
logger = structlog.get_logger(__name__)
@@ -47,6 +63,10 @@ _REASONS: dict[str, str] = {
),
"anchor_no_heading": "Link points at #{fragment}, which {doc} no longer declares.",
"command_no_target": "Document shows `{raw}`, but no such target is declared.",
+ "symbol_no_definition": (
+ "Document names `{raw}`, which was defined in code when this line was "
+ "written and is defined nowhere now."
+ ),
}
@@ -63,6 +83,7 @@ class DocDriftAnalyzer:
rename_lookup: RenameLookup | None = None,
on_disk: Callable[[str], bool] | None = None,
opaque_dirs: frozenset[str] | None = None,
+ symbols: SymbolOptions | None = None,
) -> None:
"""
Args:
@@ -88,6 +109,9 @@ class DocDriftAnalyzer:
see :attr:`~.resolver.RepoIndex.on_disk`.
opaque_dirs: directories the tree cannot list (submodules); see
:attr:`~.resolver.RepoIndex.opaque_dirs`.
+ symbols: the index's symbol names and, on an update, what to
+ re-resolve. The ``symbol`` kind runs only with these and a
+ ``repo_root``; see :mod:`~.symbols`.
"""
self._repo_id = repo_id
self._source_map = source_map or {}
@@ -98,6 +122,7 @@ class DocDriftAnalyzer:
self._on_disk = on_disk
self._rename_lookup = rename_lookup
self._opaque_dirs = opaque_dirs
+ self._symbols = symbols if self._repo_root is not None else None
# -- input preparation ------------------------------------------------
@@ -134,6 +159,12 @@ class DocDriftAnalyzer:
out[rel] = text
return out
+ def _enabled(self, cfg: dict) -> set[DriftKind]:
+ enabled = {kind for kind in DriftKind if cfg.get(f"check_{kind.value}", True)}
+ if self._symbols is None:
+ enabled.discard(DriftKind.SYMBOL)
+ return enabled
+
# -- the pass ---------------------------------------------------------
def analyze(
@@ -148,13 +179,11 @@ class DocDriftAnalyzer:
for each :class:`~.models.DriftKind`, all defaulting to on.
"""
cfg = config or {}
- enabled = {
- kind for kind in DriftKind if cfg.get(f"check_{kind.value}", True)
- }
+ step = on_step or (lambda _stage: None)
+ enabled = self._enabled(cfg)
documents = self._documents()
- if on_step:
- on_step("collect")
+ step("collect")
on_disk = self._on_disk
if on_disk is None and self._repo_root is not None:
@@ -166,60 +195,29 @@ class DocDriftAnalyzer:
on_disk=on_disk,
opaque_dirs=self._opaque_dirs,
)
- if on_step:
- on_step("index")
-
- misses: list[Resolution] = []
- resolved: list[ResolvedDocReference] = []
- verdict_counts: dict[str, int] = {v.value: 0 for v in DriftVerdict}
- references_checked = 0
- suppressed = 0
+ step("index")
+ tally = _Tally()
+ candidates = _SymbolCandidates(self._symbols.recheck if self._symbols else None)
for rel, text in documents.items():
- is_guide = is_guide_document(rel)
- refs, silenced = extract_with_suppressed(text, rel)
- suppressed += sum(1 for ref in silenced if ref.kind in enabled)
- for ref in refs:
- if ref.kind not in enabled:
- continue
- references_checked += 1
- res = resolve(index, ref, is_guide=is_guide)
- verdict_counts[res.verdict.value] += 1
- if res.verdict is DriftVerdict.MISSING:
- misses.append(res)
- elif res.resolved_target and res.resolved_target != rel:
- # Retention, not recomputation. Only a resolution naming
- # a real file sets ``resolved_target``, so an ambiguous or
- # uncheckable reference cannot land here as a fact. A
- # document naming itself is dropped: a table of contents
- # answers the reverse question with the file the reader is
- # already in.
- resolved.append(_to_resolved(res))
- if on_step:
- on_step("resolve")
+ refs = tally.extract(text, rel, enabled)
+ if DriftKind.SYMBOL in enabled:
+ candidates.collect(rel, refs)
+ tally.resolve_document(index, rel, refs, enabled)
+ self._resolve_symbols(candidates.refs, tally)
+ step("resolve")
min_conf = float(cfg.get("min_confidence", DEFAULT_MIN_CONFIDENCE))
- shown = [res for res in misses if res.confidence >= min_conf]
- hidden = len(misses) - len(shown)
- # Suggestions only for findings a reader will see: the rename lookup is
- # a git call.
- suggestions = suggest_all(
- shown, index, rename_lookup=self._rename_lookup, on_disk=on_disk
- )
- findings = [
- _to_finding(res, suggestion)
- for res, suggestion in zip(shown, suggestions, strict=True)
- ]
- findings.sort(key=lambda f: (-f.confidence, f.file_path, f.line_number))
+ shown = [pair for pair in tally.misses if pair[0].confidence >= min_conf]
+ findings = self._findings(shown, index, on_disk, documents)
logger.debug(
"doc_drift_complete",
documents=len(documents),
- references=references_checked,
+ references=tally.references_checked,
findings=len(findings),
renderer=index.renderers.summary(),
)
-
return DocDriftReport(
repo_id=self._repo_id,
analyzed_at=datetime.now(UTC),
@@ -227,14 +225,123 @@ class DocDriftAnalyzer:
findings=findings,
confidence_summary=summarize_confidence(findings),
documents_scanned=len(documents),
- references_checked=references_checked,
- verdict_summary=verdict_counts,
+ references_checked=tally.references_checked,
+ verdict_summary=tally.verdicts,
anchor_renderer=index.renderers.summary(),
- hidden_below_threshold=hidden,
- suppressed=suppressed,
+ hidden_below_threshold=len(tally.misses) - len(shown),
+ suppressed=tally.suppressed,
documents=frozenset(documents),
- resolved_references=resolved,
+ resolved_references=tally.resolved,
+ symbol_scope=candidates.scope(),
+ )
+
+ def _resolve_symbols(self, refs: list[DocReference], tally: _Tally) -> None:
+ """The symbol kind, batched over every document's candidates."""
+ if not refs or self._symbols is None or self._repo_root is None:
+ return
+ for outcome in resolve_symbols(
+ refs,
+ root=self._repo_root,
+ symbol_names=self._symbols.names,
+ rename_lookup=self._rename_lookup,
+ ):
+ if outcome is not None: # ``None``: not a symbol reference
+ tally.record(*outcome)
+
+ def _findings(
+ self,
+ shown: list[tuple[Resolution, SymbolMiss | None]],
+ index: RepoIndex,
+ on_disk: Callable[[str], bool] | None,
+ documents: dict[str, str],
+ ) -> list[DocDriftFindingData]:
+ """The findings a reader sees, with suggestions, most confident first."""
+ # Suggestions only for findings a reader will see: the rename lookup is
+ # a git call.
+ suggestions = suggest_all(
+ [res for res, _ in shown], index, rename_lookup=self._rename_lookup, on_disk=on_disk
+ )
+ lines: dict[str, list[str]] = {}
+ findings = []
+ for (res, miss), suggestion in zip(shown, suggestions, strict=True):
+ doc = res.ref.doc_path
+ if doc not in lines:
+ lines[doc] = documents.get(doc, "").split("\n")
+ findings.append(_to_finding(res, suggestion, lines[doc], miss))
+ findings.sort(key=lambda f: (-f.confidence, f.file_path, f.line_number))
+ return findings
+
+
+@dataclass
+class _Tally:
+ """What the pass has counted and kept so far."""
+
+ misses: list[tuple[Resolution, SymbolMiss | None]] = field(default_factory=list)
+ resolved: list[ResolvedDocReference] = field(default_factory=list)
+ verdicts: dict[str, int] = field(default_factory=lambda: {v.value: 0 for v in DriftVerdict})
+ references_checked: int = 0
+ suppressed: int = 0
+
+ def extract(self, text: str, rel: str, enabled: set[DriftKind]) -> list[DocReference]:
+ """*rel*'s references, counting the enabled ones an inline marker silenced."""
+ refs, silenced = extract_with_suppressed(text, rel)
+ # A silenced symbol candidate is not known to be a reference at all.
+ self.suppressed += sum(
+ 1 for ref in silenced if ref.kind in enabled and ref.kind is not DriftKind.SYMBOL
)
+ return refs
+
+ def record(self, res: Resolution, miss: SymbolMiss | None = None) -> None:
+ self.references_checked += 1
+ self.verdicts[res.verdict.value] += 1
+ if res.verdict is DriftVerdict.MISSING:
+ self.misses.append((res, miss))
+
+ def resolve_document(
+ self, index: RepoIndex, rel: str, refs: list[DocReference], enabled: set[DriftKind]
+ ) -> None:
+ """Resolve *rel*'s references of every enabled kind but ``SYMBOL``."""
+ is_guide = is_guide_document(rel)
+ for ref in refs:
+ if ref.kind not in enabled or ref.kind is DriftKind.SYMBOL:
+ continue
+ res = resolve(index, ref, is_guide=is_guide)
+ self.record(res)
+ if res.verdict is not DriftVerdict.MISSING and res.resolved_target not in ("", rel):
+ # Retention, not recomputation. Only a resolution naming a real
+ # file sets ``resolved_target``, so an ambiguous or uncheckable
+ # reference cannot land here as a fact. A document naming itself
+ # is dropped: a table of contents answers the reverse question
+ # with the file the reader is already in.
+ self.resolved.append(_to_resolved(res))
+
+
+class _SymbolCandidates:
+ """The symbol candidates this run re-resolves, and the scope that makes them."""
+
+ def __init__(self, recheck: SymbolRecheck | None) -> None:
+ self.recheck = recheck
+ self.refs: list[DocReference] = []
+ self.whole_docs: set[str] = set()
+ self.single_refs: set[tuple[str, str]] = set()
+
+ def collect(self, doc: str, refs: list[DocReference]) -> None:
+ candidates = [ref for ref in refs if ref.kind is DriftKind.SYMBOL]
+ if self.recheck is None:
+ self.refs += candidates
+ elif self.recheck.whole(doc):
+ self.whole_docs.add(doc)
+ self.refs += candidates
+ else:
+ wanted = [r for r in candidates if self.recheck.wants(doc, symbol_name(r.raw))]
+ self.single_refs.update((doc, r.target) for r in wanted)
+ self.refs += wanted
+
+ def scope(self) -> SymbolScope | None:
+ """``None`` on a full pass, which speaks for every symbol finding."""
+ if self.recheck is None:
+ return None
+ return SymbolScope(frozenset(self.whole_docs), frozenset(self.single_refs))
def _to_resolved(res: Any) -> ResolvedDocReference:
@@ -279,37 +386,64 @@ def _exact_probe(root: Path) -> Callable[[str], bool]:
return probe
-def _to_finding(res: Resolution, suggestion: Suggestion = ("", "")) -> DocDriftFindingData:
+def _to_finding(
+ res: Resolution,
+ suggestion: Suggestion = NO_SUGGESTION,
+ lines: list[str] | None = None,
+ miss: SymbolMiss | None = None,
+) -> DocDriftFindingData:
ref = res.ref
- target, _, fragment = ref.target.partition("#")
- reason = _REASONS[res.origin].format(
- target=target or ref.target,
- fragment=fragment,
- doc=target or ref.doc_path,
- raw=ref.raw,
- )
- evidence = [
- f"{ref.doc_path}:{ref.line} states `{ref.raw}`",
- f"resolution: {res.detail}",
- ]
- if ref.section:
- evidence.append(f"under: {ref.section}")
+ if miss is not None:
+ suggestion = miss.suggestion
+ edit = apply_suggestion(_line_at(lines or [], ref.line), ref, suggestion[0])
return DocDriftFindingData(
kind=ref.kind,
file_path=ref.doc_path,
line_number=ref.line,
target=ref.target,
confidence=res.confidence,
- reason=reason,
+ reason=_reason(res),
origin=res.origin,
- evidence=evidence,
+ evidence=_evidence(res, miss),
raw=ref.raw,
context=ref.context[:300],
suggestion=suggestion[0],
suggestion_basis=suggestion[1],
+ suggested_line=edit[0] if edit else "",
+ suggestion_columns=edit[1] if edit else (),
+ defined_in=miss.defined_in if miss is not None else (),
+ )
+
+
+def _reason(res: Resolution) -> str:
+ ref = res.ref
+ target, _, fragment = ref.target.partition("#")
+ return _REASONS[res.origin].format(
+ target=target or ref.target,
+ fragment=fragment,
+ doc=target or ref.doc_path,
+ raw=ref.raw,
)
+def _evidence(res: Resolution, miss: SymbolMiss | None) -> list[str]:
+ ref = res.ref
+ evidence = [
+ f"{ref.doc_path}:{ref.line} states `{ref.raw}`",
+ f"resolution: {res.detail}",
+ ]
+ if miss is not None:
+ evidence.append(miss.evidence)
+ if ref.section:
+ evidence.append(f"under: {ref.section}")
+ return evidence
+
+
+def _line_at(lines: list[str], number: int) -> str:
+ """The 1-indexed *number*th line, without its carriage return, or ``""``."""
+ return lines[number - 1].rstrip("\r") if 0 < number <= len(lines) else ""
+
+
def summarize_confidence(findings: list[DocDriftFindingData]) -> dict:
"""Bucket *findings* into the house high/medium/low tiers.
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/constants.py b/packages/core/src/repowise/core/analysis/doc_drift/constants.py
index 573c82297..31b50850f 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/constants.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/constants.py
@@ -121,6 +121,7 @@ DriftOrigin = Literal[
"path_no_candidate_in_guide",
"anchor_no_heading",
"command_no_target",
+ "symbol_no_definition",
]
ORIGIN_CONFIDENCE: dict[str, float] = {
@@ -142,6 +143,9 @@ ORIGIN_CONFIDENCE: dict[str, float] = {
# A ``make``/``npm run`` target, written inside an inline code span, that
# the manifest in the tree does not declare.
"command_no_target": 0.85,
+ # A backticked identifier that git proves was a symbol definition when the
+ # line was written, and that no non-document file mentions at all now.
+ "symbol_no_definition": 0.85,
}
#: Every origin in the ``DriftOrigin`` vocabulary, for parity checks.
@@ -154,6 +158,7 @@ SuggestionBasis = Literal[
"git_rename",
"similar_heading",
"similar_target",
+ "symbol_rename",
]
SUGGESTION_BASIS_VALUES: frozenset[str] = frozenset(get_args(SuggestionBasis))
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/extractor.py b/packages/core/src/repowise/core/analysis/doc_drift/extractor.py
index d38380bbd..7c4ec90ff 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/extractor.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/extractor.py
@@ -11,13 +11,13 @@ three ask different questions:
* ``validation`` checks *generated* prose against the single ``ParsedFile`` the
page was written about, and its regex matches identifiers only --- it cannot
express a path, having no ``/`` in its character class. It is a symbol
- checker, and the symbol class is exactly what Phase 1 killed.
+ checker against one file; this detector's symbol class asks git history.
* ``interlinking`` resolves refs to ``page_id``s and strips fences with one
``re.DOTALL`` pass over the whole document, which destroys line positions.
* This detector files **line-level** findings against **user-authored** prose,
checked against the **whole tree**. It needs line numbers (the persistence
key includes one), markdown links, URL fragments and inline commands --- three
- of its four classes are things neither of the others extracts at all.
+ of its five classes are things neither of the others extracts at all.
Folding them together would mean one function with three incompatible regexes
and a mode flag. The honest answer is a third extractor that shares the
@@ -297,30 +297,72 @@ def _from_links(line: str, lineno: int, doc: str) -> Iterator[DocReference]:
if frag and not target:
# Same-document anchor, checkable against this file's own headings.
yield DocReference(
- DriftKind.ANCHOR, raw, f"{doc}#{frag}", doc, lineno, line.strip()
+ DriftKind.ANCHOR, raw, f"{doc}#{frag}", doc, lineno, line.strip(),
+ column=m.start(1),
)
continue
if not target or not _path_shaped(target):
continue
if frag:
yield DocReference(
- DriftKind.ANCHOR, raw, f"{target}#{frag}", doc, lineno, line.strip()
+ DriftKind.ANCHOR, raw, f"{target}#{frag}", doc, lineno, line.strip(),
+ column=m.start(1),
)
- yield DocReference(DriftKind.LINK, raw, target, doc, lineno, line.strip())
+ yield DocReference(
+ DriftKind.LINK, raw, target, doc, lineno, line.strip(), column=m.start(1)
+ )
def _from_inline_code(line: str, lineno: int, doc: str) -> Iterator[DocReference]:
- """Backtick-quoted paths: the PATH class.
+ """Backtick-quoted paths (the PATH class) and symbol candidates (SYMBOL).
- Only paths. A backtick-quoted identifier is NOT emitted as a symbol
- reference; see :class:`~.models.DriftKind` for why that class does not
- exist.
+ A symbol candidate is only identifier-shaped here. Whether it ever named a
+ symbol is decided against git history in :mod:`.symbols`; see
+ :class:`~.models.DriftKind` for why shape alone is not evidence.
"""
for m in _INLINE_CODE_RE.finditer(line):
- raw = m.group(1).strip()
+ body = m.group(1)
+ raw = body.strip()
+ column = m.start(1) + len(body) - len(body.lstrip())
norm = _normalize(raw)
if _path_shaped(norm):
- yield DocReference(DriftKind.PATH, raw, norm, doc, lineno, line.strip())
+ yield DocReference(
+ DriftKind.PATH, raw, norm, doc, lineno, line.strip(), column=column
+ )
+ elif symbol_name(raw):
+ # The qualified token is the target, so ``A.parse`` and ``B.parse``
+ # stay two findings; the lookup name is derived from it.
+ yield DocReference(
+ DriftKind.SYMBOL, raw, raw.removesuffix("()"), doc, lineno, line.strip(),
+ column=column,
+ )
+
+
+# ``name``, ``name()``, ``a.b.c`` or ``A::b``: dotted or ``::`` qualifiers, then
+# the final identifier, then an optional empty call.
+_SYMBOL_TOKEN_RE = re.compile(
+ r"(?:[A-Za-z_][A-Za-z0-9_]*(?:\.|::))*([A-Za-z_][A-Za-z0-9_]*)(\(\))?"
+)
+_INNER_CAPITAL_RE = re.compile(r"[a-z][A-Z]")
+
+
+def symbol_name(token: str) -> str:
+ """The final identifier *token* names when it is shaped like a code symbol, else ``""``.
+
+ It needs a code signal (an underscore, an inner capital, a qualifier or a
+ trailing ``()``), four or more characters, and a lowercase letter, so
+ English words, ``true`` and ALL-CAPS constants never qualify.
+ """
+ m = _SYMBOL_TOKEN_RE.fullmatch(token)
+ if not m:
+ return ""
+ name = m.group(1)
+ if len(name) < 4 or name.upper() == name:
+ return ""
+ qualified = m.start(1) > 0
+ if "_" in name.strip("_") or _INNER_CAPITAL_RE.search(name) or qualified or m.group(2):
+ return name
+ return ""
def _from_commands(line: str, lineno: int, doc: str) -> Iterator[DocReference]:
@@ -335,7 +377,8 @@ def _from_commands(line: str, lineno: int, doc: str) -> Iterator[DocReference]:
for m in _COMMAND_RE.finditer(span.group(1)):
target = f"make:{m.group(2)}" if m.group(1) else f"npm:{m.group(4)}"
yield DocReference(
- DriftKind.COMMAND, m.group(0), target, doc, lineno, line.strip()
+ DriftKind.COMMAND, m.group(0), target, doc, lineno, line.strip(),
+ column=span.start(1) + m.start(0),
)
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/live.py b/packages/core/src/repowise/core/analysis/doc_drift/live.py
index ea9cd4391..609e060c1 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/live.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/live.py
@@ -21,6 +21,7 @@ from .analyzer import DocDriftAnalyzer
from .constants import MANIFEST_NAMES, MAX_DOC_BYTES
from .extractor import is_checkable_document
from .models import DocDriftReport
+from .symbols import SymbolOptions
_GIT_TIMEOUT_SECONDS = 60
_GITLINK_MODE = "160000"
@@ -132,13 +133,19 @@ def collect_live_inputs(root: Path) -> LiveInputs:
)
-def run_live(root: Path, *, config: dict | None = None) -> DocDriftReport:
- """Run the drift pass over the working tree containing *root*, no index needed."""
+def run_live(
+ root: Path, *, config: dict | None = None, symbol_names: frozenset[str] | None = None
+) -> DocDriftReport:
+ """Run the drift pass over the working tree containing *root*, no index needed.
+
+ *symbol_names*, read from an index when one opens, turns on the ``symbol`` kind.
+ """
inputs = collect_live_inputs(Path(root))
analyzer = DocDriftAnalyzer(
source_map=inputs.source_map,
tracked_paths=inputs.tracked_paths,
repo_root=inputs.root,
opaque_dirs=inputs.opaque_dirs,
+ symbols=SymbolOptions(symbol_names) if symbol_names is not None else None,
)
return analyzer.analyze(config)
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/models.py b/packages/core/src/repowise/core/analysis/doc_drift/models.py
index 129b8ebef..716766f0b 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/models.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/models.py
@@ -20,18 +20,16 @@ from enum import StrEnum
class DriftKind(StrEnum):
"""The reference classes this detector ships.
- ``SYMBOL`` is deliberately absent. Phase 1 measured it at a 55-69% flag
- rate across two repositories and killed it: backticks in technical prose
- mean "this is a literal token", not "this is a code symbol". The top
- flagged tokens were ``string``, ``boolean``, ``true``, ``OPENAI_API_KEY``,
- ``PATH`` and ``HEAD``. The extraction premise is wrong, so a better graph
- would not rescue it.
+ ``SYMBOL`` flags only a token git proves was a symbol definition when its
+ line was written and is defined nowhere now (:mod:`.symbols`); backticks
+ alone mean "literal", and flagging on shape was 55-69% noise.
"""
PATH = "path"
LINK = "link"
ANCHOR = "anchor"
COMMAND = "command"
+ SYMBOL = "symbol"
class DriftVerdict(StrEnum):
@@ -77,6 +75,9 @@ class DocReference:
"""The enclosing heading trail, joined by " > ". Used to tell prose that
*describes* the repository from prose that *teaches* the reader to add to
it, which is a confidence tier rather than an exclusion."""
+ column: int = field(default=-1, compare=False)
+ """0-based offset of ``raw`` in the untrimmed line, or -1 when unknown.
+ Outside equality, so one reference repeated on a line still dedupes."""
@dataclass
@@ -107,6 +108,15 @@ class DocDriftFindingData:
never applied: this detector does not rewrite documents."""
suggestion_basis: str = ""
"""How ``suggestion`` was found, from :data:`~.constants.SuggestionBasis`."""
+ suggested_line: str = ""
+ """The whole document line with ``suggestion`` in place of every copy of
+ the reference, or empty. Only a run that read the document has it."""
+ suggestion_columns: tuple[tuple[int, int], ...] = ()
+ """Each replaced span on the line: 1-based start and exclusive end, in
+ UTF-16 code units."""
+ defined_in: tuple[str, ...] = ()
+ """``SYMBOL`` only: the files that defined the name when the line was
+ written, and where they live now. Lets a change that edits one own it."""
@dataclass(frozen=True)
@@ -135,6 +145,18 @@ class ResolvedDocReference:
"""The enclosing heading trail, so a reader can find the passage."""
+@dataclass(frozen=True)
+class SymbolScope:
+ """Which stored ``SYMBOL`` findings a write replaces: every one in
+ ``documents``, and elsewhere only the ``(document, target)`` pairs listed."""
+
+ documents: frozenset[str] = frozenset()
+ references: frozenset[tuple[str, str]] = frozenset()
+
+ def covers(self, document: str, target: str) -> bool:
+ return document in self.documents or (document, target) in self.references
+
+
@dataclass
class DocDriftReport:
"""The drift pass's output for one repository."""
@@ -169,6 +191,10 @@ class DocDriftReport:
("which documents mention this file"). Retained rather than recomputed,
because the resolver already had each one. Scoped by
``authoritative_paths`` exactly as findings are."""
+ symbol_scope: SymbolScope | None = field(default=None)
+ """The ``SYMBOL`` findings this report speaks for; ``None`` means every one
+ in ``authoritative_paths``. An incremental update re-resolves only the
+ references it could have changed, and the write carries the rest forward."""
authoritative_paths: frozenset[str] | None = field(default=None)
"""Document paths this report may speak for; ``None`` means all of them.
Mirrors dead code's field of the same name so an incremental re-check can
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/render.py b/packages/core/src/repowise/core/analysis/doc_drift/render.py
index 0d866e91e..2ccbd1d8c 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/render.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/render.py
@@ -17,7 +17,14 @@ from collections.abc import Mapping, Sequence
from typing import Any
from repowise.core.ci import github, gitlab, sarif
-from repowise.core.ci.markdown import ROW_LIMIT, cell, more_line, plural
+from repowise.core.ci.markdown import (
+ ROW_LIMIT,
+ cell,
+ code,
+ longest_backtick_run,
+ more_line,
+ plural,
+)
from .constants import DETECTION_BASIS, HIGH_CONFIDENCE_THRESHOLD
from .gate import GateResult
@@ -44,6 +51,11 @@ _RULE_TEXT: dict[DriftKind, tuple[str, str]] = {
"Document shows a command target that is not declared",
"A make or npm run target shown in a document is not declared by the manifest.",
),
+ DriftKind.SYMBOL: (
+ "Document names a code symbol that no longer exists",
+ "An identifier that was a symbol definition when the document line was written "
+ "is defined nowhere in the tree now.",
+ ),
}
@@ -58,6 +70,13 @@ def _likely(finding: Mapping[str, Any]) -> str:
return (finding.get("suggestion") or "").strip()
+def _edit(finding: Mapping[str, Any]) -> tuple[str, list[tuple[int, int]]] | None:
+ """``(suggested line, replaced spans)`` when the run placed the suggestion."""
+ line = finding.get("suggested_line") or ""
+ spans = [(int(a), int(b)) for a, b in finding.get("suggestion_columns") or []]
+ return (line, spans) if _likely(finding) and line and spans else None
+
+
def _message(finding: Mapping[str, Any]) -> str:
"""The finding's reason, plus the likely replacement when one was found."""
likely = _likely(finding)
@@ -140,11 +159,37 @@ def render_markdown(
)
if len(ordered) > ROW_LIMIT:
lines += ["", more_line(len(ordered) - ROW_LIMIT, "findings")]
+ lines += _suggestion_blocks(ordered[:ROW_LIMIT])
lines += ["", f"_{DETECTION_BASIS}_"]
return "\n".join(lines) + "\n"
+def _suggestion_blocks(rows: Sequence[Mapping[str, Any]]) -> list[str]:
+ """A review ``suggestion`` block with the whole replaced line, per finding that has one."""
+ out: list[str] = []
+ current = None
+ for f in rows:
+ edit = _edit(f)
+ if edit is None:
+ continue
+ if not out:
+ out += ["", "**Suggested edits**"]
+ if f["file_path"] != current:
+ current = f["file_path"]
+ out += ["", code(current)]
+ fence = "`" * max(3, longest_backtick_run(edit[0]) + 1)
+ out += [
+ "",
+ f"Line {int(f['line_number'])}: likely now {code(_likely(f))}",
+ "",
+ f"{fence}suggestion",
+ edit[0],
+ fence,
+ ]
+ return out
+
+
# ---------------------------------------------------------------------------
# GitHub workflow annotations
# ---------------------------------------------------------------------------
@@ -233,10 +278,21 @@ def render_sarif(
"origin": f["origin"],
"target": f["target"],
}
+ fixes = None
if likely := _likely(f):
properties["suggestion"] = likely
if f.get("suggestion_basis"):
properties["suggestion_basis"] = f["suggestion_basis"]
+ if edit := _edit(f):
+ fixes = [
+ sarif.fix(
+ f"Replace with {likely}",
+ str(f["file_path"]),
+ int(f["line_number"]),
+ edit[1],
+ likely,
+ )
+ ]
results.append(
sarif.result(
str(f["kind"]),
@@ -248,6 +304,7 @@ def render_sarif(
fingerprint_of(f),
properties,
suppressed=fingerprint_of(f) in accepted,
+ fixes=fixes,
)
)
return sarif.run(SARIF_TOOL_NAME, tool_version, _sarif_rules(), results)
@@ -268,6 +325,7 @@ def render_gitlab(
The same line :func:`render_sarif` draws between ``error`` and ``warning``.
*accepted* (the baseline) is applied by :func:`~repowise.core.ci.gitlab.report`.
+ A likely replacement ends the description as ``Likely now:`` and a code span.
"""
return gitlab.report(
SARIF_TOOL_NAME,
@@ -275,7 +333,7 @@ def render_gitlab(
gitlab.issue(
str(f["kind"]),
"major" if float(f["confidence"]) >= fail_on else "minor",
- _message(f),
+ f"{f['reason']} Likely now: {code(_likely(f))}" if _likely(f) else str(f["reason"]),
str(f["file_path"]),
int(f["line_number"]),
fingerprint_of(f),
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/scope.py b/packages/core/src/repowise/core/analysis/doc_drift/scope.py
index aabf32921..0be931b92 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/scope.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/scope.py
@@ -8,7 +8,9 @@ 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``).
+* edits the kind of manifest that declares its command (``manifest``);
+* edits or removes a file that defined its symbol (``definition``), read from
+ the finding's ``defined_in``, which only a run that read the documents has.
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``
@@ -103,6 +105,10 @@ class ChangeScope:
runner = target.partition(":")[0]
if self.manifests & _RUNNER_MANIFESTS.get(runner, frozenset()):
return "manifest"
+ elif kind == "symbol" and any(
+ p in self.changed or p in self.removed for p in finding.get("defined_in", ())
+ ):
+ return "definition"
return None
def _removes(self, path: str) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/serialize.py b/packages/core/src/repowise/core/analysis/doc_drift/serialize.py
index acb522ce9..5cac49ed9 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/serialize.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/serialize.py
@@ -112,6 +112,9 @@ def finding_dict(
evidence: Sequence[str] | None = None,
suggestion: str | None = None,
suggestion_basis: str | None = None,
+ suggested_line: str | None = None,
+ suggestion_columns: Sequence[Sequence[int]] | None = None,
+ defined_in: Sequence[str] | None = None,
) -> dict:
"""One finding as a dict, from primitives either producer can supply.
@@ -127,6 +130,10 @@ def finding_dict(
``suggestion``/``suggestion_basis`` appear only when a suggestion exists,
so a finding without one (most of them) serializes as it always did.
+ ``suggested_line``, ``suggestion_columns`` and ``defined_in`` exist only
+ on a run that read the documents (see :class:`~.models.DocDriftFindingData`);
+ a stored row never has them, so only :func:`serialize_finding` with
+ ``live=True`` passes them.
"""
out = {
"file_path": file_path,
@@ -147,6 +154,11 @@ def finding_dict(
out["suggestion"] = suggestion
if suggestion_basis:
out["suggestion_basis"] = suggestion_basis
+ if suggested_line and suggestion_columns:
+ out["suggested_line"] = suggested_line
+ out["suggestion_columns"] = [[int(a), int(b)] for a, b in suggestion_columns]
+ if defined_in:
+ out["defined_in"] = list(defined_in)
return out
@@ -174,7 +186,7 @@ def reference_dict(
return out
-def serialize_finding(finding: Any, *, evidence: bool = True) -> dict:
+def serialize_finding(finding: Any, *, evidence: bool = True, live: bool = False) -> 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
@@ -193,6 +205,10 @@ def serialize_finding(finding: Any, *, evidence: bool = True) -> dict:
evidence=list(finding.evidence or []) if evidence else None,
suggestion=finding.suggestion,
suggestion_basis=finding.suggestion_basis,
+ # Stored rows lack these, so the parity artifact must too.
+ suggested_line=finding.suggested_line if live else None,
+ suggestion_columns=finding.suggestion_columns if live else None,
+ defined_in=finding.defined_in if live else None,
)
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/suggest.py b/packages/core/src/repowise/core/analysis/doc_drift/suggest.py
index ab7e0c8f6..99da797f5 100644
--- a/packages/core/src/repowise/core/analysis/doc_drift/suggest.py
+++ b/packages/core/src/repowise/core/analysis/doc_drift/suggest.py
@@ -27,7 +27,7 @@ from pathlib import Path
from typing import Literal
from .constants import SuggestionBasis
-from .models import DriftKind
+from .models import DocReference, DriftKind
from .renderer import github_slug
from .resolver import RepoIndex, Resolution, anchor_host, join_relative
@@ -37,7 +37,8 @@ RenameLookup = Callable[[Sequence[str]], Mapping[str, str]]
#: ``(suggestion, basis)``; both empty when no strategy found a unique answer.
Suggestion = tuple[str, SuggestionBasis | Literal[""]]
-_NONE: Suggestion = ("", "")
+#: No suggestion: both parts empty.
+NO_SUGGESTION: Suggestion = ("", "")
_PATH_KINDS = (DriftKind.PATH, DriftKind.LINK)
# difflib's ratio. 0.75 admits a typo or a one-word heading edit and rejects
@@ -95,6 +96,58 @@ def suggest_all(
return out
+def apply_suggestion(
+ line: str, ref: DocReference, suggestion: str
+) -> tuple[str, tuple[tuple[int, int], ...]] | None:
+ """*line* with *suggestion* in place, and each replaced span; ``None`` when it cannot be placed.
+
+ Every standalone occurrence of the reference on the line is replaced, so the
+ line never keeps a stale copy. A path or link suggestion replaces the target
+ inside what was written, so a ``./`` prefix or a ``#fragment`` stays; other
+ kinds replace the reference whole. Spans are 1-based and end-exclusive, in
+ UTF-16 code units.
+ """
+ raw = ref.raw
+ if not suggestion or ref.column < 0 or line[ref.column : ref.column + len(raw)] != raw:
+ return None
+ offset, old = 0, raw
+ if ref.kind in _PATH_KINDS:
+ offset, old = raw.find(ref.target), ref.target
+ if offset < 0:
+ return None
+ starts = [at + offset for at in _occurrences(line, raw)]
+ if ref.column + offset not in starts:
+ return None
+ new_line = line
+ for start in reversed(starts):
+ new_line = f"{new_line[:start]}{suggestion}{new_line[start + len(old):]}"
+ spans = tuple(
+ (_utf16_len(line[:start]) + 1, _utf16_len(line[: start + len(old)]) + 1)
+ for start in starts
+ )
+ return new_line, spans
+
+
+def _occurrences(line: str, raw: str) -> list[int]:
+ """Where *raw* stands alone on *line*, not part of a longer name or path."""
+ found, at = [], line.find(raw)
+ while at >= 0:
+ before = line[at - 1 : at]
+ after = line[at + len(raw) : at + len(raw) + 1]
+ if not _glued(before) and not _glued(after):
+ found.append(at)
+ at = line.find(raw, at + len(raw))
+ return found
+
+
+def _glued(char: str) -> bool:
+ return bool(char) and (char.isalnum() or char in "_./-")
+
+
+def _utf16_len(text: str) -> int:
+ return len(text.encode("utf-16-le")) // 2
+
+
def unique_close_match(word: str, candidates: frozenset[str] | set[str]) -> str:
"""The single close match for *word*, or ``""`` when none or a near tie."""
matches = get_close_matches(word, sorted(candidates), n=2, cutoff=_CLOSE_CUTOFF)
@@ -138,7 +191,7 @@ def _local(res: Resolution, idx: RepoIndex, dir_tails: _DirTails) -> Suggestion:
return _similar_heading(res, idx)
if kind is DriftKind.COMMAND:
return _similar_target(res, idx)
- return _NONE
+ return NO_SUGGESTION
def _package_split(res: Resolution, idx: RepoIndex, dir_tails: _DirTails) -> Suggestion:
@@ -147,7 +200,7 @@ def _package_split(res: Resolution, idx: RepoIndex, dir_tails: _DirTails) -> Sug
base = target.rsplit("/", 1)[-1]
dot = base.rfind(".")
if dot <= 0:
- return _NONE
+ return NO_SUGGESTION
forms = _forms(doc, target[: len(target) - len(base) + dot])
for stem, relative in forms:
if stem in idx.dirs:
@@ -162,7 +215,7 @@ def _package_split(res: Resolution, idx: RepoIndex, dir_tails: _DirTails) -> Sug
found = [d for d in dir_tails().get("/".join(segments[-2:]), ()) if d.startswith(top)]
if len(found) == 1:
return f"{_written(doc, found[0], relative)}/", "package_split"
- return _NONE
+ return NO_SUGGESTION
def _similar_heading(res: Resolution, idx: RepoIndex) -> Suggestion:
@@ -171,7 +224,7 @@ def _similar_heading(res: Resolution, idx: RepoIndex) -> Suggestion:
anchors = idx.doc_anchors(anchor_host(idx, ref) or ref.doc_path)
match = unique_close_match(github_slug(fragment), anchors)
if not match:
- return _NONE
+ return NO_SUGGESTION
return f"{ref.raw.partition('#')[0]}#{match}", "similar_heading"
@@ -181,7 +234,7 @@ def _similar_target(res: Resolution, idx: RepoIndex) -> Suggestion:
candidates = idx.make_targets if runner == "make" else idx.npm_scripts
match = unique_close_match(name, candidates)
if not match or not ref.raw.endswith(name):
- return _NONE
+ return NO_SUGGESTION
# The runner stays as written: ``pnpm run x`` is not rewritten to ``npm``.
return f"{ref.raw[: len(ref.raw) - len(name)]}{match}", "similar_target"
@@ -191,8 +244,10 @@ def _similar_target(res: Resolution, idx: RepoIndex) -> Suggestion:
# ---------------------------------------------------------------------------
-def _git_out(root: Path, *args: str) -> str:
- """stdout of one short git call, or ``""`` on any failure.
+def git_run(
+ root: Path, *args: str, stdin: bytes | None = None, timeout: float = _GIT_TIMEOUT_SECONDS
+) -> tuple[int, bytes] | None:
+ """``(exit code, stdout)`` of one short git call, or ``None`` when it did not finish.
Never fetches: in a blobless CI clone, rename detection would otherwise
pull blobs over the network.
@@ -202,17 +257,23 @@ def _git_out(root: Path, *args: str) -> str:
proc = subprocess.run(
["git", "-C", str(root), "-c", "core.quotePath=false", *args],
capture_output=True,
- text=True,
- encoding="utf-8",
- errors="replace",
- stdin=subprocess.DEVNULL,
+ input=stdin,
+ stdin=None if stdin is not None else subprocess.DEVNULL,
env=env,
- timeout=_GIT_TIMEOUT_SECONDS,
+ timeout=timeout,
check=False,
)
except (OSError, subprocess.SubprocessError, ValueError):
+ return None
+ return proc.returncode, proc.stdout
+
+
+def _git_out(root: Path, *args: str) -> str:
+ """stdout of one short git call, or ``""`` on any failure."""
+ ran = git_run(root, *args)
+ if ran is None or ran[0] != 0:
return ""
- return proc.stdout if proc.returncode == 0 else ""
+ return ran[1].decode("utf-8", errors="replace")
def _pathspec_safe(path: str) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/doc_drift/symbols.py b/packages/core/src/repowise/core/analysis/doc_drift/symbols.py
new file mode 100644
index 000000000..ada04df34
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/doc_drift/symbols.py
@@ -0,0 +1,542 @@
+"""Symbol references: a backticked identifier that named code when it was written.
+
+Shape is not evidence. Backticks mean "literal", so a token the index lacks is
+usually a word, a key or an example. A candidate becomes a finding only on
+proof from git:
+
+1. The index knows no symbol by that name, and no tracked file other than a
+ document mentions it as a word. A mention may be a definition the index
+ skipped, so a mentioned name is not treated as a reference at all.
+2. ``git blame`` names the commit that last wrote the document line.
+3. At that commit a non-test source file, parsed with the repository's own
+ parser, defines a symbol with exactly that name. Otherwise the token was
+ never a symbol reference and is dropped, not reported.
+
+The suggestion follows the defining file to HEAD and keeps the one same-kind
+symbol added since whose name is close to the old one.
+
+Process count does not grow with the number of names: one working-tree grep,
+one blame per document (line ranges chunked), one grep over every blame commit
+and one ``cat-file --batch`` for every file read. Every limit is a count, so a
+run is deterministic; work past a limit is uncheckable as ``over-budget``.
+"""
+
+from __future__ import annotations
+
+import re
+import time
+from collections.abc import Collection, Iterable, Mapping, Sequence
+from dataclasses import dataclass
+from difflib import SequenceMatcher
+from pathlib import Path
+from typing import Any
+
+from repowise.core.ingestion.change_detector import ChangeDetector
+from repowise.core.ingestion.languages.registry import REGISTRY
+from repowise.core.ingestion.models import ParsedFile
+from repowise.core.test_paths import is_test_related_path
+
+from .constants import MARKDOWN_SUFFIXES
+from .extractor import symbol_name
+from .models import DocReference, DriftVerdict
+from .resolver import Resolution
+from .suggest import NO_SUGGESTION, RenameLookup, Suggestion, git_renames, git_run
+
+_MAX_NAMES = 2000
+_MAX_DOCUMENTS = 300
+_MAX_COMMITS = 200
+#: A name more source files than this mention at its commit is too common to confirm.
+_MAX_FILES_PER_NAME = 25
+_MAX_PARSES = 400
+_MAX_RENAME_PATHS = 50
+_LINES_PER_BLAME = 400
+_GIT_TIMEOUT_SECONDS = 60
+#: A safety net only; the count limits above decide every normal run.
+_SAFETY_SECONDS = 300.0
+_RENAME_RATIO = 0.8
+
+_SHA_RE = re.compile(r"[0-9a-f]{40}(?:[0-9a-f]{24})?")
+_WORD_RE = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
+_SOURCE_EXTS = REGISTRY.extensions_for(REGISTRY.code_languages())
+
+_OVER_BUDGET = "over-budget"
+
+
+@dataclass(frozen=True)
+class SymbolMiss:
+ """What a ``MISSING`` symbol reference carries beyond its resolution."""
+
+ evidence: str
+ """Where and at which commit the name was defined."""
+ defined_in: tuple[str, ...]
+ """The defining files at that commit, and where they live now."""
+ suggestion: Suggestion = NO_SUGGESTION
+
+
+#: Per reference: ``None`` when it is not a symbol reference, else the verdict
+#: and, for ``MISSING``, what it carries.
+_Outcome = tuple[Resolution, SymbolMiss | None] | None
+_Definition = tuple[str, ParsedFile]
+
+
+@dataclass(frozen=True)
+class SymbolRecheck:
+ """Which symbol references an incremental update re-resolves.
+
+ A reference's verdict can only change when its document changes, or when
+ its name enters or leaves a non-document file. Every other reference's
+ stored finding is carried forward by the write.
+ """
+
+ documents: frozenset[str]
+ names: frozenset[str] | None
+ """Identifiers the update added to or removed from a non-document file;
+ ``None`` when the diff could not be read, which rechecks every document."""
+
+ def whole(self, doc: str) -> bool:
+ """Whether every reference in *doc* is re-resolved."""
+ return self.names is None or doc in self.documents
+
+ def wants(self, doc: str, name: str) -> bool:
+ return self.whole(doc) or name in (self.names or ())
+
+
+@dataclass(frozen=True)
+class SymbolOptions:
+ """What the ``symbol`` kind needs from the caller running the pass."""
+
+ names: Collection[str]
+ """Every symbol name the index holds."""
+ recheck: SymbolRecheck | None = None
+ """On an incremental update, which references to re-resolve; ``None``
+ re-resolves every one."""
+
+
+def symbol_recheck(
+ root: Path, base_ref: str | None, changed_paths: Iterable[str]
+) -> SymbolRecheck:
+ """The :class:`SymbolRecheck` for an update from *base_ref* to the working tree."""
+ documents = frozenset(p for p in changed_paths if _is_document(p))
+ if not base_ref:
+ return SymbolRecheck(documents, None)
+ ran = git_run(
+ root, "diff", "-U0", "--no-color", "--no-ext-diff", "-M", base_ref, "--",
+ timeout=_GIT_TIMEOUT_SECONDS,
+ )
+ if ran is None or ran[0] != 0:
+ return SymbolRecheck(documents, None)
+ diff = ran[1].decode("utf-8", errors="replace")
+ return SymbolRecheck(documents, frozenset(_names_entering_or_leaving(diff)))
+
+
+def _names_entering_or_leaving(diff: str) -> set[str]:
+ """Identifiers a ``-U0`` diff adds to or removes from some non-document file.
+
+ Per file, a name on both removed and added lines is still in that file, so
+ only the names on one side can have entered or left it.
+ """
+ names: set[str] = set()
+ for block in diff.split("\ndiff --git "):
+ header, _, body = block.partition("\n")
+ if _is_document(header.rsplit(" b/", 1)[-1]):
+ continue
+ sides: dict[str, set[str]] = {"+": set(), "-": set()}
+ for line in body.splitlines():
+ if line[:1] in sides and not line.startswith(("+++", "---")):
+ sides[line[0]].update(_WORD_RE.findall(line[1:]))
+ names |= sides["+"] ^ sides["-"]
+ return names
+
+
+def graph_symbol_names(graph: Any) -> frozenset[str]:
+ """Every symbol name an ingestion graph holds, as the index's ``wiki_symbols`` does."""
+ return frozenset(
+ data["name"]
+ for _, data in graph.nodes(data=True)
+ if data.get("node_type") == "symbol"
+ and data.get("name")
+ and data["name"] != "__module__"
+ )
+
+
+def rewrite_symbol(raw: str, name: str, new: str) -> str:
+ """*raw* with its final identifier *name* replaced by *new*, qualifier and ``()`` kept."""
+ tail = "()" if raw.endswith("()") else ""
+ head = raw[: len(raw) - len(tail) - len(name)]
+ return f"{head}{new}{tail}"
+
+
+def _is_document(path: str) -> bool:
+ dot = path.rfind(".")
+ return dot > path.rfind("/") and path[dot:].lower() in MARKDOWN_SUFFIXES
+
+
+def _is_source(path: str) -> bool:
+ dot = path.rfind(".")
+ return dot > path.rfind("/") + 1 and path[dot:].lower() in _SOURCE_EXTS
+
+
+class _Budget:
+ def __init__(self) -> None:
+ self.parses = 0
+ self.deadline = time.monotonic() + _SAFETY_SECONDS
+
+ def parse(self, n: int) -> bool:
+ """Accept *n* more parses when they fit; count them only then."""
+ if self.parses + n > _MAX_PARSES:
+ return False
+ self.parses += n
+ return True
+
+ def timed_out(self) -> bool:
+ return time.monotonic() > self.deadline
+
+
+def resolve_symbols(
+ refs: Sequence[DocReference],
+ *,
+ root: Path,
+ symbol_names: Collection[str],
+ rename_lookup: RenameLookup | None = None,
+) -> list[_Outcome]:
+ """One outcome per ``SYMBOL`` reference in *refs*, aligned with it."""
+ run = _Run(refs, root)
+ pending = run.index_filter(symbol_names)
+ by_doc = run.unmentioned(pending)
+ by_commit = run.blame(by_doc)
+ missing = run.definitions(by_commit)
+ run.assemble(missing, rename_lookup)
+ return run.out
+
+
+class _Run:
+ """One pass over the symbol references, as named steps.
+
+ Each step records the references it settles in :attr:`out` and hands the
+ rest on; a step given nothing does nothing.
+ """
+
+ def __init__(self, refs: Sequence[DocReference], root: Path) -> None:
+ self.refs = refs
+ self.root = root
+ self.out: list[_Outcome] = [None] * len(refs)
+ self.names = {i: symbol_name(ref.raw) for i, ref in enumerate(refs)}
+ self.budget = _Budget()
+ self.detector = ChangeDetector(root)
+
+ def settle(self, idxs: Iterable[int], verdict: DriftVerdict, detail: str) -> None:
+ for i in idxs:
+ self.out[i] = (Resolution(self.refs[i], verdict, detail), None)
+
+ def index_filter(self, symbol_names: Collection[str]) -> list[int]:
+ """Resolve what the index names; the rest, within the name limit, are pending."""
+ pending: list[int] = []
+ wanted: set[str] = set()
+ for i, name in self.names.items():
+ if name in symbol_names:
+ self.settle([i], DriftVerdict.RESOLVED, "indexed-symbol")
+ elif name in wanted or len(wanted) < _MAX_NAMES:
+ wanted.add(name)
+ pending.append(i)
+ else:
+ self.settle([i], DriftVerdict.UNCHECKABLE, _OVER_BUDGET)
+ return pending
+
+ def unmentioned(self, pending: Sequence[int]) -> dict[str, list[int]]:
+ """Pending references whose name no non-document file mentions, by document."""
+ if not pending:
+ return {}
+ mentioned = _head_mentions(self.root, sorted({self.names[i] for i in pending}))
+ if mentioned is None:
+ self.settle(pending, DriftVerdict.UNCHECKABLE, "git-failed")
+ return {}
+ by_doc: dict[str, list[int]] = {}
+ for i in pending:
+ if self.names[i] not in mentioned: # a mentioned name is not a reference
+ by_doc.setdefault(self.refs[i].doc_path, []).append(i)
+ return by_doc
+
+ def blame(self, by_doc: Mapping[str, list[int]]) -> dict[str, list[int]]:
+ """References grouped by the commit that last wrote their line."""
+ by_commit: dict[str, list[int]] = {}
+ for n, (doc, idxs) in enumerate(sorted(by_doc.items())):
+ if n >= _MAX_DOCUMENTS or self.budget.timed_out():
+ self.settle(idxs, DriftVerdict.UNCHECKABLE, _OVER_BUDGET)
+ continue
+ shas = _blame(self.root, doc, sorted({self.refs[i].line for i in idxs}))
+ if shas is None:
+ self.settle(idxs, DriftVerdict.UNCHECKABLE, "git-failed")
+ continue
+ for i in idxs:
+ sha = shas.get(self.refs[i].line, "")
+ if sha.strip("0"):
+ by_commit.setdefault(sha, []).append(i)
+ else:
+ self.settle([i], DriftVerdict.UNCHECKABLE, "uncommitted")
+ for sha in sorted(by_commit)[_MAX_COMMITS:]:
+ self.settle(by_commit.pop(sha), DriftVerdict.UNCHECKABLE, _OVER_BUDGET)
+ return by_commit
+
+ def definitions(
+ self, by_commit: Mapping[str, list[int]]
+ ) -> dict[int, tuple[str, list[_Definition]]]:
+ """References whose name a source file defined at their commit."""
+ if not by_commit:
+ return {}
+ names = {sha: {self.names[i] for i in idxs} for sha, idxs in by_commit.items()}
+ found = _definitions(self.root, self.detector, names, self.budget)
+ if found is None:
+ all_idxs = [i for idxs in by_commit.values() for i in idxs]
+ self.settle(all_idxs, DriftVerdict.UNCHECKABLE, "git-failed")
+ return {}
+ missing: dict[int, tuple[str, list[_Definition]]] = {}
+ for sha, idxs in by_commit.items():
+ for i in idxs:
+ defs = found.get((sha, self.names[i]))
+ if defs is None:
+ self.settle([i], DriftVerdict.UNCHECKABLE, _OVER_BUDGET)
+ elif defs:
+ missing[i] = (sha, defs)
+ # ``[]``: never a definition, so not a symbol reference.
+ return missing
+
+ def assemble(
+ self,
+ missing: Mapping[int, tuple[str, list[_Definition]]],
+ rename_lookup: RenameLookup | None,
+ ) -> None:
+ """Record each missing reference with its evidence and any rename suggestion."""
+ renamed = _renamed_paths(self.root, missing.values(), rename_lookup)
+ for i, (sha, defs) in sorted(missing.items()):
+ paths = sorted({path for path, _ in defs})
+ new = _renamed_symbol(self.detector, self.names[i], defs, renamed, self.budget)
+ suggestion: Suggestion = NO_SUGGESTION
+ if new:
+ suggestion = (rewrite_symbol(self.refs[i].raw, self.names[i], new), "symbol_rename")
+ miss = SymbolMiss(
+ evidence=f"defined in {', '.join(paths)} at {sha[:12]}",
+ defined_in=tuple(sorted({*paths, *(renamed[p] for p in paths if p in renamed)})),
+ suggestion=suggestion,
+ )
+ res = Resolution(
+ self.refs[i], DriftVerdict.MISSING, "no-definition", "symbol_no_definition"
+ )
+ self.out[i] = (res, miss)
+
+
+# ---------------------------------------------------------------------------
+# git
+# ---------------------------------------------------------------------------
+
+
+def _grep(root: Path, revs: Sequence[str], names: Sequence[str]) -> list[tuple[str, str]] | None:
+ """``(location, line)`` for every line mentioning one of *names* as a word.
+
+ *revs* empty greps the working tree, tracked and untracked; ``None`` when
+ the grep failed, so a failure never reads as "absent".
+ """
+ # One alternation on one line: git tries each ``-f`` line as a separate
+ # pattern, so a line per name costs a pass per name.
+ alternation = "|".join(re.escape(n) for n in names)
+ pattern = f"(^|[^A-Za-z0-9_])({alternation})([^A-Za-z0-9_]|$)\n".encode()
+ where = list(revs) or ["--untracked"]
+ ran = git_run(
+ root, "grep", "-E", "-I", "-z", "-f", "-", *where,
+ stdin=pattern, timeout=_GIT_TIMEOUT_SECONDS,
+ )
+ if ran is None or ran[0] not in (0, 1):
+ return None
+ lines = ran[1].decode("utf-8", errors="replace").splitlines()
+ return [(loc, text) for loc, sep, text in (ln.partition("\0") for ln in lines) if sep]
+
+
+def _head_mentions(root: Path, names: Sequence[str]) -> set[str] | None:
+ """Which of *names* any non-document file in the working tree mentions."""
+ found = _grep(root, (), names)
+ if found is None:
+ return None
+ wanted = set(names)
+ mentioned: set[str] = set()
+ for path, text in found:
+ if not _is_document(path):
+ mentioned |= wanted.intersection(_WORD_RE.findall(text))
+ return mentioned
+
+
+def _commit_mentions(
+ root: Path, shas: Sequence[str], names: Sequence[str]
+) -> dict[tuple[str, str], set[str]] | None:
+ """``{(commit, name): non-test source paths mentioning it}`` over every commit."""
+ found = _grep(root, shas, names)
+ if found is None:
+ return None
+ wanted = set(names)
+ out: dict[tuple[str, str], set[str]] = {}
+ for location, text in found:
+ sha, _, path = location.partition(":")
+ if not _is_source(path) or is_test_related_path(path):
+ continue
+ for name in wanted.intersection(_WORD_RE.findall(text)):
+ out.setdefault((sha, name), set()).add(path)
+ return out
+
+
+def _blame(root: Path, doc: str, lines: Sequence[int]) -> dict[int, str] | None:
+ """The commit that last wrote each of *lines* of *doc*."""
+ shas: dict[int, str] = {}
+ for start in range(0, len(lines), _LINES_PER_BLAME):
+ chunk = lines[start : start + _LINES_PER_BLAME]
+ ranges = [arg for n in chunk for arg in ("-L", f"{n},{n}")]
+ ran = git_run(
+ root, "blame", "--porcelain", "-w", *ranges, "--", doc, timeout=_GIT_TIMEOUT_SECONDS
+ )
+ if ran is None or ran[0] != 0:
+ return None
+ for line in ran[1].decode("utf-8", errors="replace").splitlines():
+ parts = line.split(" ")
+ if len(parts) in (3, 4) and _SHA_RE.fullmatch(parts[0]) and parts[2].isdigit():
+ shas[int(parts[2])] = parts[0]
+ return shas
+
+
+def _definitions(
+ root: Path,
+ detector: ChangeDetector,
+ names: Mapping[str, set[str]],
+ budget: _Budget,
+) -> dict[tuple[str, str], list[_Definition]] | None:
+ """``{(commit, name): definitions}`` confirmed by parsing; ``None`` when git failed.
+
+ *names* maps each commit to the names wanted there. ``[]`` means no non-test
+ source file defined the name at that commit; a key left out could not be
+ confirmed within the limits.
+ """
+ mentions = _commit_mentions(root, sorted(names), sorted(set().union(*names.values())))
+ if mentions is None:
+ return None
+ accepted = _accept(names, mentions, budget)
+ files = sorted({(sha, p) for (sha, _), paths in accepted.items() for p in paths})
+ parsed = _parse_at(root, detector, files)
+ if parsed is None:
+ return None
+ defined = {key: {s.name for s in pf.symbols} for key, pf in parsed.items()}
+ return {
+ (sha, name): [(p, parsed[(sha, p)]) for p in paths if name in defined.get((sha, p), ())]
+ for (sha, name), paths in accepted.items()
+ }
+
+
+def _accept(
+ names: Mapping[str, set[str]],
+ mentions: Mapping[tuple[str, str], set[str]],
+ budget: _Budget,
+) -> dict[tuple[str, str], list[str]]:
+ """The files to parse per ``(commit, name)``, within the per-name and parse limits."""
+ accepted: dict[tuple[str, str], list[str]] = {}
+ files: set[tuple[str, str]] = set()
+ for sha in sorted(names):
+ for name in sorted(names[sha]):
+ paths = sorted(mentions.get((sha, name), ()))
+ fresh = [p for p in paths if (sha, p) not in files]
+ if len(paths) > _MAX_FILES_PER_NAME or not budget.parse(len(fresh)):
+ continue
+ files.update((sha, p) for p in fresh)
+ accepted[(sha, name)] = paths
+ return accepted
+
+
+def _parse_at(
+ root: Path, detector: ChangeDetector, files: Sequence[tuple[str, str]]
+) -> dict[tuple[str, str], ParsedFile] | None:
+ """Each ``(commit, path)`` parsed, from one ``cat-file --batch``."""
+ if not files:
+ return {}
+ request = "".join(f"{sha}:./{path}\n" for sha, path in files).encode("utf-8")
+ ran = git_run(root, "cat-file", "--batch", stdin=request, timeout=_GIT_TIMEOUT_SECONDS)
+ if ran is None or ran[0] != 0:
+ return None
+ data, pos, out = ran[1], 0, {}
+ # Each object is ``<oid> blob <size>\n<bytes>\n``, or one ``missing`` line.
+ for key in files:
+ end = data.find(b"\n", pos)
+ header = data[pos:end].split(b" ")
+ pos = end + 1
+ if len(header) != 3 or header[1] != b"blob":
+ continue
+ size = int(header[2])
+ parsed = detector.parse_bytes(data[pos : pos + size], key[1])
+ pos += size + 1
+ if parsed is not None:
+ out[key] = parsed
+ return out
+
+
+# ---------------------------------------------------------------------------
+# suggestions
+# ---------------------------------------------------------------------------
+
+
+def _renamed_paths(
+ root: Path,
+ missing: Iterable[tuple[str, list[_Definition]]],
+ rename_lookup: RenameLookup | None,
+) -> dict[str, str]:
+ """Where each defining file lives now: itself when still on disk, else its git rename."""
+ paths = sorted({path for _, defs in missing for path, _ in defs})[:_MAX_RENAME_PATHS]
+ where = {p: p for p in paths if (root / p).is_file()}
+ gone = [p for p in paths if p not in where]
+ if gone:
+ lookup = rename_lookup or (lambda wanted: git_renames(root, wanted))
+ try:
+ renames = lookup(gone)
+ except Exception: # a failed lookup costs a suggestion, never the pass
+ renames = {}
+ where.update({p: new for p, new in renames.items() if (root / new).is_file()})
+ return where
+
+
+def _renamed_symbol(
+ detector: ChangeDetector,
+ name: str,
+ defs: Sequence[_Definition],
+ renamed: Mapping[str, str],
+ budget: _Budget,
+) -> str:
+ """The one same-kind symbol added since, closest to *name*, else ``""``.
+
+ Scored on the name alone, so where a symbol sits in the file cannot tip it,
+ and a tie between two names is no suggestion.
+ """
+ found: set[str] = set()
+ for path, old in defs:
+ new = _parse_now(detector, renamed.get(path), budget)
+ if new is None:
+ continue
+ best = _closest_added(name, old, new)
+ if len(best) > 1:
+ return ""
+ found.update(best)
+ return found.pop() if len(found) == 1 else ""
+
+
+def _parse_now(detector: ChangeDetector, path: str | None, budget: _Budget) -> ParsedFile | None:
+ """*path* as it is on disk now, parsed within the parse limit."""
+ if not path or not budget.parse(1):
+ return None
+ try:
+ return detector.parse_bytes((detector.repo_path / path).read_bytes(), path)
+ except OSError:
+ return None
+
+
+def _closest_added(name: str, old: ParsedFile, new: ParsedFile) -> list[str]:
+ """Same-kind names *new* added over *old* that tie for closest to *name* at the ratio."""
+ kinds = {s.kind for s in old.symbols if s.name == name}
+ before = {s.name for s in old.symbols}
+ scores = {
+ s.name: SequenceMatcher(None, name.lower(), s.name.lower()).ratio()
+ for s in new.symbols
+ if s.kind in kinds and s.name not in before
+ }
+ top = max(scores.values(), default=0.0)
+ return [n for n, ratio in scores.items() if ratio == top and ratio >= _RENAME_RATIO]
diff --git a/packages/core/src/repowise/core/ci/markdown.py b/packages/core/src/repowise/core/ci/markdown.py
index d1e768fdd..484b2ea61 100644
--- a/packages/core/src/repowise/core/ci/markdown.py
+++ b/packages/core/src/repowise/core/ci/markdown.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import re
from collections.abc import Sequence
from typing import Any
@@ -17,6 +18,18 @@ def cell(value: Any) -> str:
return text
+def longest_backtick_run(text: str) -> int:
+ """Length of the longest run of backticks in *text*, for choosing a fence."""
+ return max((len(run) for run in re.findall(r"`+", text)), default=0)
+
+
+def code(text: str) -> str:
+ """*text* as an inline code span that no backtick inside it can close early."""
+ fence = "`" * (longest_backtick_run(text) + 1)
+ pad = " " if text.startswith("`") or text.endswith("`") else ""
+ return f"{fence}{pad}{text}{pad}{fence}"
+
+
def plural(n: int, word: str, many: str | None = None) -> str:
"""``"1 file"`` / ``"3 files"``."""
return f"{n} {word if n == 1 else many or word + 's'}"
diff --git a/packages/core/src/repowise/core/ci/sarif.py b/packages/core/src/repowise/core/ci/sarif.py
index 852b2e64c..d33991b18 100644
--- a/packages/core/src/repowise/core/ci/sarif.py
+++ b/packages/core/src/repowise/core/ci/sarif.py
@@ -34,19 +34,16 @@ def result(
properties: Mapping[str, Any] | None = None,
*,
suppressed: bool = False,
+ fixes: Sequence[Mapping[str, Any]] | None = None,
) -> dict:
"""One result, located relative to ``%SRCROOT%`` with a percent-encoded URI.
*line* ``None`` locates the result on the file alone, for a finding whose
line belongs to another revision. *suppressed* marks one accepted outside
the log (a baseline), so code scanning shows it closed rather than open.
+ *fixes* are :func:`fix` objects proposing an edit.
"""
- location: dict[str, Any] = {
- "artifactLocation": {
- "uri": quote(path.replace("\\", "/").lstrip("/"), safe="/"),
- "uriBaseId": "%SRCROOT%",
- }
- }
+ location: dict[str, Any] = {"artifactLocation": _artifact(path)}
if line is not None:
location["region"] = {"startLine": max(1, int(line))}
out: dict[str, Any] = {
@@ -58,11 +55,48 @@ def result(
}
if suppressed:
out["suppressions"] = [{"kind": "external"}]
+ if fixes:
+ out["fixes"] = [dict(f) for f in fixes]
if properties:
out["properties"] = dict(properties)
return out
+def _artifact(path: str) -> dict:
+ return {
+ "uri": quote(path.replace("\\", "/").lstrip("/"), safe="/"),
+ "uriBaseId": "%SRCROOT%",
+ }
+
+
+def fix(
+ description: str, path: str, line: int, spans: Sequence[tuple[int, int]], text: str
+) -> dict:
+ """One ``fix`` replacing each ``(start, end)`` column span of one line with *text*.
+
+ Columns are 1-based with an exclusive end, in UTF-16 code units, the
+ ``columnKind`` :func:`run` declares.
+ """
+ replacements = [
+ {
+ "deletedRegion": {
+ "startLine": int(line),
+ "startColumn": int(start),
+ "endLine": int(line),
+ "endColumn": int(end),
+ },
+ "insertedContent": {"text": text},
+ }
+ for start, end in spans
+ ]
+ return {
+ "description": {"text": description},
+ "artifactChanges": [
+ {"artifactLocation": _artifact(path), "replacements": replacements}
+ ],
+ }
+
+
def run(
tool_name: str,
version: str,
@@ -90,6 +124,7 @@ def run(
"rules": [dict(r) for r in rules],
}
},
+ "columnKind": "utf16CodeUnits",
"results": indexed,
}
],
diff --git a/packages/core/src/repowise/core/ingestion/change_detector.py b/packages/core/src/repowise/core/ingestion/change_detector.py
index aee8c52c1..268f33c05 100644
--- a/packages/core/src/repowise/core/ingestion/change_detector.py
+++ b/packages/core/src/repowise/core/ingestion/change_detector.py
@@ -517,7 +517,7 @@ class ChangeDetector:
"""Parse a git blob (old file version from git history)."""
try:
source = blob.data_stream.read()
- return self._parse_bytes(source, path)
+ return self.parse_bytes(source, path)
except Exception as exc:
log.warning("Failed to parse blob", path=path, error=str(exc))
return None
@@ -525,12 +525,13 @@ class ChangeDetector:
def _parse_path(self, abs_path: Path, rel_path: str) -> ParsedFile | None:
"""Parse a file from the working tree."""
try:
- return self._parse_bytes(abs_path.read_bytes(), rel_path)
+ return self.parse_bytes(abs_path.read_bytes(), rel_path)
except Exception as exc:
log.warning("Failed to parse file", path=rel_path, error=str(exc))
return None
- def _parse_bytes(self, source: bytes, path: str) -> ParsedFile | None:
+ def parse_bytes(self, source: bytes, path: str) -> ParsedFile | None:
+ """Parse one file's *source* as *path* with the repository's parser, or ``None``."""
from datetime import datetime
from .parser import parse_file
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 dedb52a87..c3ab83e48 100644
--- a/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/__init__.py
@@ -51,6 +51,7 @@ from .doc_drift import (
doc_drift_references_stored,
get_doc_drift_findings,
get_doc_drift_references,
+ get_symbol_names,
is_new_doc_drift_row,
replace_doc_drift_findings,
replace_doc_drift_guarded,
@@ -162,6 +163,7 @@ __all__ = [
"get_refactoring_suggestions",
"get_refactoring_summary",
"get_scored_file_paths",
+ "get_symbol_names",
"get_test_coverage_summary",
"is_new_doc_drift_row",
"list_evidence_for_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 6592957f0..d4d8ea5fd 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
@@ -8,13 +8,13 @@ from dataclasses import dataclass
from datetime import UTC, datetime
from typing import Any
-from sqlalchemy import delete, func, select
+from sqlalchemy import delete, func, select, tuple_
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 ...models import DocDriftFinding, DocDriftReference, WikiSymbol
from .._shared import _BATCH_SIZE
#: Width of the two ``String(1024)`` columns. ``target`` is lifted verbatim
@@ -69,14 +69,36 @@ _REFERENCES_TABLE = _DriftTable(
)
+@dataclass(frozen=True)
+class _WriteScope:
+ """What one drift write may speak for, and how it stamps the rows it inserts."""
+
+ documents: frozenset[str] | None
+ """Document paths this write may speak for; ``None`` means repo-wide."""
+ stamp: Callable[[dict], None] | None = None
+ carried: tuple[str, Any] | None = None
+ """``(kind, SymbolScope)``: rows of that kind are replaced only where the
+ :class:`~repowise.core.analysis.doc_drift.models.SymbolScope` covers them
+ and kept everywhere else, for a run that re-derived one kind in less than
+ the rest."""
+
+ def admits(self, table: _DriftTable, item: Any, kwargs: dict) -> bool:
+ """Whether this write may insert *item*."""
+ if self.documents is not None and table.path_of(item) not in self.documents:
+ # Outside the scope it would be inserted and never deleted by the
+ # next scoped run, so it would outlive its own evidence.
+ return False
+ if self.carried is None or kwargs["kind"] != self.carried[0]:
+ return True
+ return self.carried[1].covers(table.path_of(item), item.target)
+
+
async def _replace_scoped(
session: AsyncSession,
table: _DriftTable,
repository_id: str,
items: list[Any],
- *,
- scoped: frozenset[str] | None,
- stamp: Callable[[dict], None] | None = None,
+ write: _WriteScope,
) -> int:
"""Delete-then-insert one drift table, converging on re-run.
@@ -84,50 +106,84 @@ async def _replace_scoped(
speak for the same set of documents, or one describes a run the other
never made.
- ``scoped`` names the document paths this write may speak for; ``None``
- means repo-wide. Idempotency rests on the unique constraint, and on the
- DELETE and INSERT scopes being identical so no surviving row can collide.
- The dedup closes the last gap: two items in one batch sharing a site,
- which would otherwise raise after the DELETE had run.
+ Idempotency rests on the unique constraint, and on the DELETE and INSERT
+ scopes being identical so no surviving row can collide. The dedup closes
+ the last gap: two items in one batch sharing a site, which would otherwise
+ raise after the DELETE had run.
"""
model = table.model
- if scoped is None:
- await session.execute(delete(model).where(model.repository_id == repository_id))
- else:
- # Chunked so a large scope stays under SQLite's parameter limit.
- paths = sorted(scoped)
- for i in range(0, len(paths), _IN_CLAUSE_CHUNK):
- chunk = paths[i : i + _IN_CLAUSE_CHUNK]
- await session.execute(
- delete(model).where(
- model.repository_id == repository_id,
- table.path_column.in_(chunk),
- )
- )
+ base = [model.repository_id == repository_id]
+ if write.carried is not None:
+ base.append(model.kind != write.carried[0])
+ await _delete_carried(session, table, repository_id, write)
+ await _delete_in(session, table, base, write.documents)
+ rows = _rows_to_insert(table, repository_id, items, write)
+ for i in range(0, len(rows), _BATCH_SIZE):
+ session.add_all(model(**r) for r in rows[i : i + _BATCH_SIZE])
+ await session.flush()
+ return len(rows)
+
+
+def _rows_to_insert(
+ table: _DriftTable, repository_id: str, items: list[Any], write: _WriteScope
+) -> list[dict]:
rows: list[dict] = []
seen: set[tuple] = set()
for item in items or []:
- if scoped is not None and table.path_of(item) not in scoped:
- # Outside the scope it would be inserted and never deleted by the
- # next scoped run, so it would outlive its own evidence.
- continue
kwargs = table.row_kwargs(item, repository_id)
+ if not write.admits(table, item, kwargs):
+ continue
# Keyed on the truncated values, so two targets differing only past the
# column width collapse here rather than colliding in the database.
key = tuple(kwargs[field] for field in table.key_fields)
if key in seen:
continue
seen.add(key)
- if stamp is not None:
- stamp(kwargs)
+ if write.stamp is not None:
+ write.stamp(kwargs)
rows.append(kwargs)
+ return rows
- for i in range(0, len(rows), _BATCH_SIZE):
- session.add_all(model(**r) for r in rows[i : i + _BATCH_SIZE])
- await session.flush()
- return len(rows)
+async def _delete_carried(
+ session: AsyncSession, table: _DriftTable, repository_id: str, write: _WriteScope
+) -> None:
+ """Delete the carried kind's rows where the write's symbol scope covers them."""
+ kind, cover = write.carried # type: ignore[misc]
+ model = table.model
+ of_kind = [model.repository_id == repository_id, model.kind == kind]
+ scoped = write.documents
+ documents = cover.documents if scoped is None else cover.documents & scoped
+ await _delete_in(session, table, of_kind, documents)
+ pairs = sorted(
+ (doc, target[:_PATH_COLUMN_WIDTH])
+ for doc, target in cover.references
+ if scoped is None or doc in scoped
+ )
+ # Two parameters per pair, so half the usual chunk.
+ step = _IN_CLAUSE_CHUNK // 2
+ for i in range(0, len(pairs), step):
+ await session.execute(
+ delete(model).where(
+ *of_kind, tuple_(table.path_column, model.target).in_(pairs[i : i + step])
+ )
+ )
+
+
+async def _delete_in(
+ session: AsyncSession, table: _DriftTable, where: list, paths: frozenset[str] | None
+) -> None:
+ """Delete *where* rows, narrowed to *paths* when given (``None``: every path)."""
+ model = table.model
+ if paths is None:
+ await session.execute(delete(model).where(*where))
+ return
+ # Chunked so a large scope stays under SQLite's parameter limit.
+ ordered = sorted(paths)
+ for i in range(0, len(ordered), _IN_CLAUSE_CHUNK):
+ chunk = ordered[i : i + _IN_CLAUSE_CHUNK]
+ await session.execute(delete(model).where(*where, table.path_column.in_(chunk)))
def _row_kwargs(finding: Any, repository_id: str) -> dict:
@@ -157,6 +213,7 @@ async def replace_doc_drift_findings(
findings: list[Any],
*,
scope: frozenset[str] | set[str] | None = None,
+ symbol_scope: Any | None = None,
) -> int:
"""Replace this repository's drift findings, converging on re-run.
@@ -170,9 +227,14 @@ async def replace_doc_drift_findings(
on (document, kind, target) so an edit that moves a line keeps its age.
Ceiling: a renamed document's findings start a new age, as the key holds
the path; carrying them needs the rename map the incremental pass has.
+ ``symbol_scope``, a :class:`~repowise.core.analysis.doc_drift.models.SymbolScope`
+ when given, narrows the ``symbol`` rows replaced to what it covers; stored
+ symbol findings elsewhere carry forward untouched.
+
Returns the number of rows inserted.
"""
scoped = frozenset(scope) if scope is not None else None
+ carried = ("symbol", symbol_scope) if symbol_scope is not None else None
written_at = datetime.now(UTC)
prior = await _first_seen_before(session, repository_id, scoped)
@@ -185,7 +247,11 @@ async def replace_doc_drift_findings(
row["first_seen_at"] = prior.get(_age_key(row), written_at)
return await _replace_scoped(
- session, _FINDINGS_TABLE, repository_id, findings, scoped=scoped, stamp=stamp
+ session,
+ _FINDINGS_TABLE,
+ repository_id,
+ findings,
+ _WriteScope(scoped, stamp, carried),
)
@@ -284,7 +350,7 @@ async def replace_doc_drift_references(
_REFERENCES_TABLE,
repository_id,
references,
- scoped=frozenset(scope) if scope is not None else None,
+ _WriteScope(frozenset(scope) if scope is not None else None),
)
@@ -313,6 +379,7 @@ async def replace_doc_drift_guarded(
repository_id,
report.findings,
scope=report.authoritative_paths,
+ symbol_scope=getattr(report, "symbol_scope", None),
)
await replace_doc_drift_references(
session,
@@ -323,6 +390,16 @@ async def replace_doc_drift_guarded(
return written
+async def get_symbol_names(session: AsyncSession, repository_id: str) -> frozenset[str]:
+ """Every symbol name the index holds: the set the ``symbol`` drift kind resolves against."""
+ stmt = (
+ select(WikiSymbol.name)
+ .where(WikiSymbol.repository_id == repository_id)
+ .distinct()
+ )
+ return frozenset((await session.execute(stmt)).scalars())
+
+
async def get_doc_drift_findings(
session: AsyncSession,
repository_id: str,
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index 8df3eb643..8f72791bf 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -20,7 +20,8 @@ best-effort step that already degrades gracefully.
from __future__ import annotations
import asyncio
-from collections.abc import Callable
+from collections.abc import Callable, Iterable
+from dataclasses import dataclass
from functools import partial
from pathlib import Path
from typing import Any
@@ -872,6 +873,23 @@ def run_partial_analysis(
return partial_health_report, dead_code_report
+@dataclass(frozen=True)
+class DocDriftUpdate:
+ """What an update tells the drift pass about the change it is applying."""
+
+ base_ref: str | None = None
+ """The commit the update diffs from, to the working tree."""
+ changed_paths: tuple[str, ...] = ()
+ """Every path the update adds, edits, deletes or renames (both sides)."""
+ symbol_names: frozenset[str] | None = None
+ """The index's symbol names; ``None`` reads them from the graph."""
+
+ @classmethod
+ def from_file_diffs(cls, base_ref: str | None, file_diffs: Iterable[Any]) -> DocDriftUpdate:
+ paths = tuple(p for fd in file_diffs for p in (fd.path, fd.old_path) if p)
+ return cls(base_ref=base_ref, changed_paths=paths)
+
+
def run_doc_drift_partial(
graph_builder: Any,
source_map: dict[str, bytes] | None,
@@ -879,6 +897,7 @@ def run_doc_drift_partial(
repo_path: Any | None = None,
log: LogFn | None = None,
timings: PhaseTimings | None = None,
+ update: DocDriftUpdate | None = None,
) -> Any | None:
"""Re-check the repository's own markdown on the incremental path.
@@ -886,6 +905,11 @@ def run_doc_drift_partial(
:func:`run_partial_analysis`'s tuple, mirroring the full path where drift is
its own phase. Returns ``None`` when the pass could not run, which the
caller must treat as "write nothing".
+
+ The cheap kinds are re-derived for every document. Symbol references are
+ re-resolved only where *update* could have changed them (see
+ :class:`~repowise.core.analysis.doc_drift.symbols.SymbolRecheck`); the rest
+ carry forward in the store.
"""
log = log or _noop_log
if not source_map:
@@ -902,10 +926,12 @@ def run_doc_drift_partial(
if not tracked_paths:
return None
+ root = Path(repo_path) if repo_path else None
report = DocDriftAnalyzer(
source_map=source_map,
tracked_paths=tracked_paths,
- repo_root=Path(repo_path) if repo_path else None,
+ repo_root=root,
+ symbols=_drift_symbol_options(graph_builder, root, update or DocDriftUpdate()),
).analyze()
report.authoritative_paths = report.documents
if report.total_findings:
@@ -916,6 +942,22 @@ def run_doc_drift_partial(
return None
+def _drift_symbol_options(graph_builder: Any, root: Path | None, update: DocDriftUpdate) -> Any:
+ """The drift pass's symbol options for *update*; ``None`` without a working tree."""
+ from repowise.core.analysis.doc_drift.symbols import (
+ SymbolOptions,
+ graph_symbol_names,
+ symbol_recheck,
+ )
+
+ if root is None:
+ return None
+ names = update.symbol_names
+ if names is None:
+ names = graph_symbol_names(graph_builder.graph())
+ return SymbolOptions(names, symbol_recheck(root, update.base_ref, update.changed_paths))
+
+
async def refresh_knowledge_graph(
repo_path: Any,
parsed_files: list,
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index d967068aa..3233223e2 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -545,6 +545,7 @@ async def run_pipeline(
_run_doc_drift_analysis(
source_map,
file_infos=file_infos,
+ graph_builder=graph_builder,
repo_path=repo_path,
progress=progress,
),
diff --git a/packages/core/src/repowise/core/pipeline/phases/analysis.py b/packages/core/src/repowise/core/pipeline/phases/analysis.py
index bc57ecad0..8e1edab24 100644
--- a/packages/core/src/repowise/core/pipeline/phases/analysis.py
+++ b/packages/core/src/repowise/core/pipeline/phases/analysis.py
@@ -112,6 +112,7 @@ async def _run_doc_drift_analysis(
source_map: dict[str, bytes] | None,
*,
file_infos: list[Any] | None = None,
+ graph_builder: Any | None = None,
repo_id: str = "",
repo_path: Path | None = None,
progress: ProgressCallback | None,
@@ -125,6 +126,7 @@ async def _run_doc_drift_analysis(
"""
try:
from repowise.core.analysis.doc_drift import DocDriftAnalyzer
+ from repowise.core.analysis.doc_drift.symbols import SymbolOptions, graph_symbol_names
# analyze() drives three stages: collect, index, resolve.
if progress:
@@ -141,6 +143,9 @@ async def _run_doc_drift_analysis(
source_map=source_map,
tracked_paths=tracked_paths,
repo_root=repo_path,
+ symbols=(
+ SymbolOptions(graph_symbol_names(graph_builder.graph())) if graph_builder else None
+ ),
)
def _step(_stage: str) -> None:
diff --git a/packages/core/src/repowise/core/workspace/update.py b/packages/core/src/repowise/core/workspace/update.py
index 474ecf7e5..b1e24419b 100644
--- a/packages/core/src/repowise/core/workspace/update.py
+++ b/packages/core/src/repowise/core/workspace/update.py
@@ -381,6 +381,7 @@ async def _incremental_repo_update(
"""
from ..ingestion.change_detector import ChangeDetector, merge_file_diffs
from ..pipeline.incremental import (
+ DocDriftUpdate,
persist_incremental_index,
rebuild_graph_and_git,
run_doc_drift_partial,
@@ -489,7 +490,11 @@ async def _incremental_repo_update(
log=_log.info,
)
doc_drift_report = run_doc_drift_partial(
- graph_builder, source_map, repo_path=repo_path, log=_log.info
+ graph_builder,
+ source_map,
+ repo_path=repo_path,
+ log=_log.info,
+ update=DocDriftUpdate.from_file_diffs(base_ref, file_diffs),
)
# Partial health has consumed the per-file ``BlameIndex``; drop it before
diff --git a/packages/types/src/doc-drift.ts b/packages/types/src/doc-drift.ts
index f65f20034..558a9092b 100644
--- a/packages/types/src/doc-drift.ts
+++ b/packages/types/src/doc-drift.ts
@@ -35,11 +35,11 @@ export type DocDriftUnavailable =
/**
* 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".
+ * `symbol` flags only an identifier git proves was a symbol definition when
+ * the document line was written and is defined nowhere now. It needs an index,
+ * so an index-free run reports the other four.
*/
-export type DocDriftKind = "path" | "link" | "anchor" | "command";
+export type DocDriftKind = "path" | "link" | "anchor" | "command" | "symbol";
/**
* The one set of confidence boundaries, mirroring the engine.
@@ -80,6 +80,7 @@ export const DOC_DRIFT_KIND_LABELS: Record<DocDriftKind, string> = {
link: "Link",
anchor: "Heading link",
command: "Command",
+ symbol: "Symbol",
};
/** Label for one reference class, falling back to the raw slug. */
@@ -98,6 +99,7 @@ export const SUGGESTION_BASIS_LABELS: Readonly<Record<string, string>> = {
git_rename: "Renamed in git",
similar_heading: "Similar heading",
similar_target: "Similar target",
+ symbol_rename: "Renamed symbol",
};
export interface DocDriftFinding {
diff --git a/packages/ui/src/doc-drift/doc-drift-lede.tsx b/packages/ui/src/doc-drift/doc-drift-lede.tsx
index c783b8f0c..f27ecbe68 100644
--- a/packages/ui/src/doc-drift/doc-drift-lede.tsx
+++ b/packages/ui/src/doc-drift/doc-drift-lede.tsx
@@ -97,8 +97,8 @@ export function DocDriftLede({
<>
<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.
+ names a file, a heading, a command or a code symbol that the repository
+ has since moved or removed.
</p>
<p className="mt-2.5">{summary.findings_basis}</p>
</>
diff --git a/packages/ui/src/health/ai-prompts/doc-drift-prompt.ts b/packages/ui/src/health/ai-prompts/doc-drift-prompt.ts
index 51ca20e3f..cb4a1f098 100644
--- a/packages/ui/src/health/ai-prompts/doc-drift-prompt.ts
+++ b/packages/ui/src/health/ai-prompts/doc-drift-prompt.ts
@@ -47,7 +47,7 @@ const MAX_DOC_DRIFT_FINDINGS = 20;
const CONSTRAINTS = [
"**Edit the document, not the code.** Each entry names a document that makes a claim the repository no longer satisfies. The fix is almost always to correct the prose, the path or the link — not to recreate the file it names.",
- "**Find out what replaced the target before you touch the line.** A path that no longer resolves usually moved or was renamed; point the document at the new location rather than deleting the sentence around it.",
+ "**Find out what replaced the target before you touch the line.** A path that no longer resolves usually moved or was renamed, and a symbol that is defined nowhere now was usually renamed or folded into another; point the document at what replaced it rather than deleting the sentence around it.",
"**Some findings are correct as written.** A guide that teaches the reader to add a file names one that was never meant to exist, and an example path inside a tutorial is not drift. If a line is doing its job, leave it and say so.",
"**Do not touch a changelog or release note.** Those describe the repository as it was at a release; a reference that no longer resolves is the document doing its job.",
"**Keep the surrounding prose true.** Fixing a link that sits inside a sentence about how something works means checking that the sentence is still accurate, not just that the path resolves.",
@@ -122,6 +122,6 @@ export function buildDocDriftAiPrompt({
...closingSections(CONSTRAINTS, EXPECTED),
flavor === "claude-code-mcp"
? "For each target, call `get_context([\"<target>\"])` to find where it lives now — repowise already indexed the tree, so use it instead of globbing for a renamed path. `get_why(...)` on a target that is genuinely gone will often name the change that removed it, which is what the document should now say."
- : "For each target, search the repository for the file or heading it names before editing — most of these moved rather than disappeared, and the document should point at where they went.",
+ : "For each target, search the repository for the file, heading or symbol it names before editing: most of these moved rather than disappeared, and the document should point at where they went.",
]);
}
diff --git a/packages/vscode/README.md b/packages/vscode/README.md
index 0fae59619..657df56ed 100644
--- a/packages/vscode/README.md
+++ b/packages/vscode/README.md
@@ -107,7 +107,7 @@ The quickest way to tune Repowise is **Repowise: Open Settings**, a friendly pan
| `repowise.changeIntel.cochangeNudge` | `true` | The quiet "usually change together" status-bar hint |
| `repowise.changeIntel.cochangeMinScore` | `4` | How strong the history has to be before a related file is suggested |
| `repowise.diagnostics.enabled` | `false` | Also publish high-severity findings to the Problems panel |
-| `repowise.docDrift.diagnostics.enabled` | `true` | Flag lines in visible markdown files whose paths, links, anchors or commands no longer exist |
+| `repowise.docDrift.diagnostics.enabled` | `true` | Flag lines in visible markdown files whose paths, links, anchors, commands or code symbols no longer exist |
## Privacy
diff --git a/packages/vscode/package.json b/packages/vscode/package.json
index 177131567..0b46cff3b 100644
--- a/packages/vscode/package.json
+++ b/packages/vscode/package.json
@@ -101,7 +101,7 @@
"repowise.docDrift.diagnostics.enabled": {
"type": "boolean",
"default": true,
- "description": "Show documentation-drift findings (paths, links, anchors and commands a markdown file names that the tree no longer has) for visible markdown files in the Problems panel. On by default: findings are sparse and each names the line to edit."
+ "description": "Show documentation-drift findings (paths, links, anchors, commands and code symbols a markdown file names that the tree no longer has) for visible markdown files in the Problems panel. On by default: findings are sparse and each names the line to edit."
},
"repowise.docDrift.diagnostics.minConfidence": {
"type": "number",
diff --git a/packages/vscode/webview/src/views/settings/App.tsx b/packages/vscode/webview/src/views/settings/App.tsx
index 39049114b..669872dac 100644
--- a/packages/vscode/webview/src/views/settings/App.tsx
+++ b/packages/vscode/webview/src/views/settings/App.tsx
@@ -91,7 +91,7 @@ const GROUPS: Group[] = [
key: "docDrift.diagnostics.enabled",
label: "Documentation drift",
description:
- "Flag paths, links, anchors, and commands in visible markdown files that the tree no longer has.",
+ "Flag paths, links, anchors, commands, and code symbols in visible markdown files that the tree no longer has.",
kind: "toggle",
},
{
diff --git a/tests/unit/cli/test_doc_drift_check.py b/tests/unit/cli/test_doc_drift_check.py
index d38db864a..5440f8f36 100644
--- a/tests/unit/cli/test_doc_drift_check.py
+++ b/tests/unit/cli/test_doc_drift_check.py
@@ -324,3 +324,76 @@ def test_since_requires_check_and_refuses_write_baseline(monkeypatch, tmp_path):
["--check", "--since", "main...HEAD", "--write-baseline", str(tmp_path / "b.json")],
)
assert both.exit_code == 2
+
+
+def _symbol_history(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,
+ )
+
+ (tmp_path / "src").mkdir()
+ (tmp_path / "docs").mkdir()
+ (tmp_path / "src" / "app.py").write_text("def parse_config():\n pass\n", encoding="utf-8")
+ (tmp_path / "docs" / "guide.md").write_text("Call `parse_config()`.\n", encoding="utf-8")
+ git("init", "-q")
+ git("add", ".")
+ git("commit", "-qm", "init")
+ (tmp_path / "src" / "app.py").write_text(
+ "def parse_conf():\n pass\n", encoding="utf-8"
+ )
+ git("commit", "-qam", "rename")
+
+
[email protected](shutil.which("git") is None, reason="git not installed")
+def test_check_runs_no_symbol_pass_unless_asked(monkeypatch, tmp_path):
+ _symbol_history(tmp_path)
+
+ async def _names(root): # an index exists, but nobody asked for symbols
+ raise AssertionError("the index must not be read")
+
+ monkeypatch.setattr(doc_drift_cmd, "_index_symbol_names", _names)
+ result = CliRunner().invoke(
+ doc_drift_cmd.doc_drift_command,
+ ["--check", "--no-workspace", "--format", "json", str(tmp_path)],
+ )
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.output)
+ assert payload["findings"] == []
+ assert payload["references_checked"] == 0
+
+
[email protected](shutil.which("git") is None, reason="git not installed")
+def test_kind_symbol_without_an_index_cannot_evaluate(tmp_path):
+ _symbol_history(tmp_path)
+ result = CliRunner().invoke(
+ doc_drift_cmd.doc_drift_command,
+ ["--check", "--kind", "symbol", "--no-workspace", "--format", "json", str(tmp_path)],
+ )
+ assert result.exit_code == 2, result.output
+ assert json.loads(result.output)["error"] == "no_index"
+
+
[email protected](shutil.which("git") is None, reason="git not installed")
+def test_kind_symbol_with_an_index_reports_a_renamed_symbol(monkeypatch, tmp_path):
+ _symbol_history(tmp_path)
+
+ async def _names(root):
+ return frozenset({"parse_conf"})
+
+ monkeypatch.setattr(doc_drift_cmd, "_index_symbol_names", _names)
+ result = CliRunner().invoke(
+ doc_drift_cmd.doc_drift_command,
+ ["--check", "--kind", "symbol", "--no-workspace", "--format", "json", str(tmp_path)],
+ )
+ assert result.exit_code == 1, result.output
+ (finding,) = json.loads(result.output)["findings"]
+ assert finding["kind"] == "symbol"
+ assert finding["target"] == "parse_config"
+ assert finding["suggestion"] == "parse_conf()"
+ assert finding["suggestion_basis"] == "symbol_rename"
+ assert finding["suggested_line"] == "Call `parse_conf()`."
+ assert finding["suggestion_columns"] == [[7, 21]]
+ assert finding["defined_in"] == ["src/app.py"]
diff --git a/tests/unit/doc_drift/test_extractor.py b/tests/unit/doc_drift/test_extractor.py
index d27cdfe38..056d2a21c 100644
--- a/tests/unit/doc_drift/test_extractor.py
+++ b/tests/unit/doc_drift/test_extractor.py
@@ -102,14 +102,14 @@ def test_npm_run_commands_are_extracted():
# ---------------------------------------------------------------------------
-def test_backticked_identifiers_are_not_extracted():
- """Phase 1 killed the symbol class at a 55-69% flag rate.
+def test_only_code_shaped_identifiers_become_symbol_candidates():
+ """Backticks mean "literal": a word or a constant is never a candidate.
- Backticks in technical prose mean "literal token", not "code symbol". The
- top flagged tokens were `string`, `boolean`, `true`, `OPENAI_API_KEY`.
+ Candidacy is shape only; git history decides whether one was a symbol.
"""
text = "Set `OPENAI_API_KEY`, pass a `string`, and call `resolve_target`."
- assert extract(text, "docs/x.md") == []
+ refs = extract(text, "docs/x.md")
+ assert [(r.kind, r.target) for r in refs] == [(DriftKind.SYMBOL, "resolve_target")]
# ---------------------------------------------------------------------------
diff --git a/tests/unit/doc_drift/test_render.py b/tests/unit/doc_drift/test_render.py
index b2ecfeaee..bb2a7b0e2 100644
--- a/tests/unit/doc_drift/test_render.py
+++ b/tests/unit/doc_drift/test_render.py
@@ -148,7 +148,7 @@ def test_sarif_required_fields():
assert driver["name"] == "repowise-doc-drift"
assert driver["version"] == "1.2.3"
assert driver["informationUri"] == "https://repowise.dev"
- assert [r["id"] for r in driver["rules"]] == ["path", "link", "anchor", "command"]
+ assert [r["id"] for r in driver["rules"]] == ["path", "link", "anchor", "command", "symbol"]
assert all(DETECTION_BASIS in r["fullDescription"]["text"] for r in driver["rules"])
by_rule = {r["ruleId"]: r for r in run["results"]}
@@ -206,7 +206,7 @@ def test_gitlab_severity_follows_the_gate_and_drops_the_baseline():
"location": {"path": "docs/a.md", "lines": {"begin": 3}},
},
{
- "description": "Document names a.py, which no longer exists. Likely now: pkg/a/.",
+ "description": "Document names a.py, which no longer exists. Likely now: `pkg/a/`",
"check_name": "repowise-doc-drift/path",
"fingerprint": derive_doc_drift_fingerprint("docs/a.md", "path", "a.py"),
"severity": "major",
@@ -223,3 +223,94 @@ def test_gitlab_is_deterministic_and_unique():
assert one == render_gitlab(list(reversed(findings)))
fps = [i["fingerprint"] for i in one]
assert len(set(fps)) == 3 and fps[1] == fps[0] + ":2"
+
+
+# -- placed suggestions -----------------------------------------------------
+
+
+def _placed(**kw) -> dict:
+ out = _f("a.py", suggestion="pkg/a/", **kw)
+ out["suggested_line"] = "See `pkg/a/` here."
+ out["suggestion_columns"] = [[6, 10]]
+ return out
+
+
+def _symbol(suggestion: str, line: str, spans: list) -> dict:
+ out = _f("Loader.parse_config", kind="symbol", suggestion=suggestion)
+ out["suggestion_basis"] = "symbol_rename"
+ out["suggested_line"] = line
+ out["suggestion_columns"] = spans
+ return out
+
+
+def test_sarif_declares_utf16_columns():
+ (run,) = render_sarif([_placed()], tool_version="x")["runs"]
+ assert run["columnKind"] == "utf16CodeUnits"
+
+
+def test_sarif_carries_a_fix_on_the_exact_span():
+ (result,) = render_sarif([_placed()], tool_version="x")["runs"][0]["results"]
+ (fix,) = result["fixes"]
+ (change,) = fix["artifactChanges"]
+ assert change["artifactLocation"] == {"uri": "docs/a.md", "uriBaseId": "%SRCROOT%"}
+ (replacement,) = change["replacements"]
+ assert replacement == {
+ "deletedRegion": {"startLine": 3, "startColumn": 6, "endLine": 3, "endColumn": 10},
+ "insertedContent": {"text": "pkg/a/"},
+ }
+ assert fix["description"]["text"] == "Replace with pkg/a/"
+
+
+def test_sarif_replaces_every_copy_of_a_repeated_token():
+ finding = _symbol(
+ "Loader.parse_conf()", "`Loader.parse_conf()` and `Loader.parse_conf()`", [[2, 23], [30, 51]]
+ )
+ (result,) = render_sarif([finding], tool_version="x")["runs"][0]["results"]
+ regions = [r["deletedRegion"] for r in result["fixes"][0]["artifactChanges"][0]["replacements"]]
+ assert [(r["startColumn"], r["endColumn"]) for r in regions] == [(2, 23), (30, 51)]
+
+
+def test_sarif_has_no_fix_without_a_placed_suggestion():
+ (result,) = render_sarif([_f("a.py", suggestion="pkg/a/")], tool_version="x")["runs"][0][
+ "results"
+ ]
+ assert "fixes" not in result
+
+
+def test_markdown_puts_a_suggestion_block_with_the_whole_line_under_its_document():
+ md = render_markdown([_placed(), _f("b.py", line=9)], gate=None)
+ assert "**Suggested edits**" in md
+ block = md.split("**Suggested edits**", 1)[1]
+ assert "`docs/a.md`" in block
+ assert "Line 3: likely now `pkg/a/`" in block
+ assert "```suggestion\nSee `pkg/a/` here.\n```" in block
+ assert "Line 9" not in block
+
+
+def test_markdown_suggestion_block_for_a_symbol():
+ finding = _symbol("Loader.parse_conf()", "Call `Loader.parse_conf()` first.", [[7, 28]])
+ md = render_markdown([finding], gate=None)
+ assert "Line 3: likely now `Loader.parse_conf()`" in md
+ assert "```suggestion\nCall `Loader.parse_conf()` first.\n```" in md
+ assert "| Loader.parse_config | symbol |" in md
+
+
+def test_markdown_fence_outgrows_backticks_in_the_line():
+ finding = _placed()
+ finding["suggested_line"] = "Run ```pkg/a/``` now."
+ md = render_markdown([finding], gate=None)
+ assert "````suggestion\nRun ```pkg/a/``` now.\n````" in md
+
+
+def test_a_backtick_in_a_suggestion_never_breaks_the_code_span():
+ finding = _placed()
+ finding["suggestion"] = "make `x`"
+ md = render_markdown([finding], gate=None)
+ assert "likely now `` make `x` ``" in md
+ (issue,) = render_gitlab([finding])
+ assert issue["description"].endswith("Likely now: `` make `x` ``")
+
+
+def test_gitlab_description_ends_with_the_suggestion():
+ (issue,) = render_gitlab([_placed()])
+ assert issue["description"].endswith("Likely now: `pkg/a/`")
diff --git a/tests/unit/doc_drift/test_scope.py b/tests/unit/doc_drift/test_scope.py
index 547e964b2..ddd459ac2 100644
--- a/tests/unit/doc_drift/test_scope.py
+++ b/tests/unit/doc_drift/test_scope.py
@@ -164,3 +164,12 @@ def test_a_bare_ref_means_the_change_since_it_including_the_working_tree(tmp_pat
assert scope.label == "main...HEAD"
assert scope.removed == {"src/committed.py", "src/uncommitted.py"}
assert scope.documents == {"docs/new.md"}
+
+
+def test_a_symbol_finding_is_owned_by_a_change_to_its_defining_file():
+ finding = {**_finding(kind="symbol", target="Loader.parse_config"), "defined_in": ["src/app.py"]}
+ assert _scope(_change("modified", "src/app.py", "src/app.py")).reason(finding) == "definition"
+ assert _scope(_change("deleted", "src/app.py", None)).reason(finding) == "definition"
+ assert _scope(_change("modified", "src/other.py", "src/other.py")).reason(finding) is None
+ # A stored finding has no ``defined_in``: only an edit to its document owns it.
+ assert _scope(_change("modified", "src/app.py", "src/app.py")).reason(_finding(kind="symbol")) is None
diff --git a/tests/unit/doc_drift/test_suggest.py b/tests/unit/doc_drift/test_suggest.py
index 68f687390..9a7286d90 100644
--- a/tests/unit/doc_drift/test_suggest.py
+++ b/tests/unit/doc_drift/test_suggest.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import shutil
import subprocess
+from dataclasses import replace
from pathlib import Path
import pytest
@@ -12,6 +13,7 @@ from repowise.core.analysis.doc_drift import DocDriftAnalyzer
from repowise.core.analysis.doc_drift.models import DocReference, DriftKind, DriftVerdict
from repowise.core.analysis.doc_drift.resolver import RepoIndex, resolve
from repowise.core.analysis.doc_drift.suggest import (
+ apply_suggestion,
git_renames,
suggest_all,
unique_close_match,
@@ -315,3 +317,49 @@ def test_git_renames_stops_at_an_outright_deletion(tmp_path: Path):
def test_git_renames_outside_a_repository_is_empty(tmp_path: Path):
assert git_renames(tmp_path, ["a.py"]) == {}
assert git_renames(tmp_path, []) == {}
+
+
+# ---------------------------------------------------------------------------
+# apply_suggestion
+# ---------------------------------------------------------------------------
+
+
+def _placed_ref(kind, raw, target, line):
+ column = line.index(raw)
+ return DocReference(kind, raw, target, "docs/guide.md", 1, line.strip(), column=column)
+
+
+def test_path_suggestion_replaces_the_target_inside_what_was_written():
+ line = "See [x](./src/old.py#top) now"
+ ref = _placed_ref(DriftKind.LINK, "./src/old.py#top", "src/old.py", line)
+ new_line, columns = apply_suggestion(line, ref, "src/new/")
+ assert new_line == "See [x](./src/new/#top) now"
+ assert columns == ((11, 21),)
+
+
+def test_anchor_suggestion_replaces_the_whole_reference():
+ line = "See [x](g.md#old)"
+ ref = _placed_ref(DriftKind.ANCHOR, "g.md#old", "docs/g.md#old", line)
+ assert apply_suggestion(line, ref, "g.md#new") == ("See [x](g.md#new)", ((9, 17),))
+
+
+def test_columns_count_utf16_units_before_the_span():
+ line = "\U0001f680 `make biuld`"
+ ref = _placed_ref(DriftKind.COMMAND, "make biuld", "make:biuld", line)
+ _, columns = apply_suggestion(line, ref, "make build")
+ # The emoji is one code point but two UTF-16 units.
+ assert columns == ((5, 15),)
+
+
+def test_a_reference_not_at_its_column_is_not_placed():
+ ref = DocReference(DriftKind.PATH, "a.py", "a.py", "d.md", 1, "", column=3)
+ assert apply_suggestion("nothing here", ref, "b.py") is None
+ assert apply_suggestion("x `a.py`", replace(ref, column=-1), "b.py") is None
+
+
+def test_every_standalone_copy_on_the_line_is_replaced():
+ line = "`load_rows()`, then `load_rows()`, not `preload_rows()`"
+ ref = _placed_ref(DriftKind.SYMBOL, "load_rows()", "load_rows", line)
+ new_line, columns = apply_suggestion(line, ref, "load_records()")
+ assert new_line == "`load_records()`, then `load_records()`, not `preload_rows()`"
+ assert columns == ((2, 13), (22, 33))
diff --git a/tests/unit/doc_drift/test_symbols.py b/tests/unit/doc_drift/test_symbols.py
new file mode 100644
index 000000000..0a684d1e5
--- /dev/null
+++ b/tests/unit/doc_drift/test_symbols.py
@@ -0,0 +1,371 @@
+"""Symbol references: flagged only when git proves the name was a definition."""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+from repowise.core.analysis.doc_drift import DocDriftAnalyzer
+from repowise.core.analysis.doc_drift import symbols as symbols_mod
+from repowise.core.analysis.doc_drift.extractor import extract, symbol_name
+from repowise.core.analysis.doc_drift.models import DriftKind, DriftVerdict, SymbolScope
+from repowise.core.analysis.doc_drift.suggest import NO_SUGGESTION
+from repowise.core.analysis.doc_drift.symbols import (
+ SymbolOptions,
+ SymbolRecheck,
+ resolve_symbols,
+ rewrite_symbol,
+ symbol_recheck,
+)
+
+git_required = pytest.mark.skipif(shutil.which("git") is None, reason="git not installed")
+
+
+# ---------------------------------------------------------------------------
+# Candidate shape
+# ---------------------------------------------------------------------------
+
+
+ ("token", "name"),
+ [
+ ("parse_config()", "parse_config"),
+ ("ChangeDetector.detect", "detect"),
+ ("my_func", "my_func"),
+ ("parseConfig", "parseConfig"),
+ ("Graph::addNode", "addNode"),
+ ("load()", "load"),
+ ],
+)
+def test_code_shaped_tokens_are_candidates(token: str, name: str):
+ assert symbol_name(token) == name
+
+
+ "token",
+ ["string", "true", "PATH", "HEAD", "foo", "MAX_DOC_BYTES", "Config", "a.b", "run it", "x()"],
+)
+def test_words_constants_and_short_names_are_not(token: str):
+ assert symbol_name(token) == ""
+
+
+def test_paths_and_commands_are_never_symbol_candidates():
+ text = "See `src/app_main.py`, `config.yaml` and run `make build_all`."
+ assert [r.kind for r in extract(text, "docs/x.md")] == [
+ DriftKind.PATH,
+ DriftKind.PATH,
+ DriftKind.COMMAND,
+ ]
+
+
+def test_target_is_the_qualified_token_without_the_call():
+ (ref,) = extract("Use `Loader.parse_config()`.", "docs/x.md")
+ assert (ref.raw, ref.target) == ("Loader.parse_config()", "Loader.parse_config")
+
+
+def test_same_name_under_two_qualifiers_stays_two_references():
+ refs = extract("`Foo.parse_row` and `Bar.parse_row`", "docs/x.md")
+ assert [r.target for r in refs] == ["Foo.parse_row", "Bar.parse_row"]
+
+
+def test_candidate_records_its_column_on_the_untrimmed_line():
+ line = " - call `parse_config()` first"
+ (ref,) = extract(line, "docs/x.md")
+ assert line[ref.column : ref.column + len(ref.raw)] == "parse_config()"
+
+
+def test_rewrite_keeps_qualifier_and_call():
+ assert rewrite_symbol("Loader.parse_config()", "parse_config", "parse_conf") == (
+ "Loader.parse_conf()"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Resolution against a real history
+# ---------------------------------------------------------------------------
+
+_APP_BEFORE = '''"""App module."""
+
+
+class Loader:
+ def parse_config(self, path):
+ return path
+
+
+def load_items():
+ return []
+
+
+def keep_me():
+ return 1
+
+
+# fetch_widget is only mentioned here, never defined.
+LABEL = "fetch_widget"
+'''
+
+_APP_AFTER = '''"""App module."""
+
+
+class Loader:
+ def parse_conf(self, path):
+ return path
+
+
+def keep_me():
+ return 1
+
+
+def helper_fn():
+ return 2
+'''
+
+_TEST_HELPER = "def make_fixture_repo():\n return None\n"
+
+_DOC = """# Guide
+
+Call `Loader.parse_config()` first, and `Loader.parse_config()` again.
+Then `load_items()`.
+Also `keep_me()`.
+Never `my_func`.
+And `fetch_widget` too.
+Finally `helper_fn()`.
+Test with `make_fixture_repo()`.
+"""
+
+
+def _git(root: Path, *args: str) -> str:
+ return subprocess.run(
+ ["git", "-C", str(root), "-c", "user.name=t", "-c", "user.email=t@t", *args],
+ check=True,
+ capture_output=True,
+ text=True,
+ ).stdout.strip()
+
+
+def history(tmp_path: Path) -> Path:
+ for rel, text in {
+ "src/app.py": _APP_BEFORE,
+ "tests/test_helpers.py": _TEST_HELPER,
+ "docs/guide.md": _DOC,
+ }.items():
+ (tmp_path / rel).parent.mkdir(parents=True, exist_ok=True)
+ (tmp_path / rel).write_text(text, encoding="utf-8")
+ _git(tmp_path, "init", "-q")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-qm", "write")
+ (tmp_path / "src/app.py").write_text(_APP_AFTER, encoding="utf-8")
+ (tmp_path / "tests/test_helpers.py").unlink()
+ _git(tmp_path, "commit", "-qam", "rename and delete")
+ return tmp_path
+
+
+#: What an index built at HEAD would hold; ``helper_fn`` is missing, as a lagging
+#: or narrower index would be.
+_INDEXED = frozenset({"parse_conf", "keep_me"})
+
+
+def _outcomes(root: Path) -> dict[str, object]:
+ refs = [r for r in extract(_DOC, "docs/guide.md") if r.kind is DriftKind.SYMBOL]
+ outcomes = resolve_symbols(refs, root=root, symbol_names=_INDEXED)
+ return {ref.target: outcome for ref, outcome in zip(refs, outcomes, strict=True)}
+
+
+@git_required
+def test_renamed_symbol_is_missing_with_the_rename_suggested(history: Path):
+ res, miss = _outcomes(history)["Loader.parse_config"]
+ assert res.verdict is DriftVerdict.MISSING
+ assert (res.origin, res.detail) == ("symbol_no_definition", "no-definition")
+ assert miss.evidence.startswith("defined in src/app.py at ")
+ assert miss.defined_in == ("src/app.py",)
+ assert miss.suggestion == ("Loader.parse_conf()", "symbol_rename")
+
+
+@git_required
+def test_deleted_symbol_is_missing_without_a_suggestion(history: Path):
+ res, miss = _outcomes(history)["load_items"]
+ assert res.verdict is DriftVerdict.MISSING
+ assert miss.suggestion == NO_SUGGESTION
+
+
+@git_required
+def test_names_that_never_named_a_symbol_are_not_references(history: Path):
+ outcomes = _outcomes(history)
+ assert outcomes["my_func"] is None
+ # Only a comment and a string at the commit: the parser finds no definition.
+ assert outcomes["fetch_widget"] is None
+ # Defined only in a test file at the commit.
+ assert outcomes["make_fixture_repo"] is None
+ # Still mentioned in a non-document file, though the index lacks it.
+ assert outcomes["helper_fn"] is None
+
+
+@git_required
+def test_indexed_symbol_resolves(history: Path):
+ res, miss = _outcomes(history)["keep_me"]
+ assert res.verdict is DriftVerdict.RESOLVED
+ assert miss is None
+
+
+@git_required
+def test_work_past_a_limit_is_over_budget(history: Path, monkeypatch):
+ monkeypatch.setattr(symbols_mod, "_MAX_DOCUMENTS", 0)
+ res, _ = _outcomes(history)["load_items"]
+ assert (res.verdict, res.detail) == (DriftVerdict.UNCHECKABLE, "over-budget")
+
+
+@git_required
+def test_suggestion_follows_a_moved_defining_file(history: Path):
+ (history / "src/core").mkdir()
+ _git(history, "mv", "src/app.py", "src/core/app.py")
+ _git(history, "commit", "-qm", "move")
+ res, miss = _outcomes(history)["Loader.parse_config"]
+ assert res.verdict is DriftVerdict.MISSING
+ assert miss.suggestion == ("Loader.parse_conf()", "symbol_rename")
+ assert miss.defined_in == ("src/app.py", "src/core/app.py")
+
+
+@git_required
+def test_two_equally_close_new_names_are_no_suggestion(history: Path):
+ app = history / "src/app.py"
+ app.write_text(
+ _APP_AFTER.replace("def parse_conf(", "def parse_confa(")
+ + "\n\nclass Other:\n def parse_confb(self):\n return 0\n",
+ encoding="utf-8",
+ )
+ _git(history, "commit", "-qam", "two candidates")
+ _res, miss = _outcomes(history)["Loader.parse_config"]
+ assert miss.suggestion == NO_SUGGESTION
+
+
+@git_required
+def test_uncommitted_doc_line_is_uncheckable(history: Path):
+ doc = history / "docs/guide.md"
+ doc.write_text(_DOC + "New `load_items` line.\n", encoding="utf-8")
+ refs = [
+ r
+ for r in extract(doc.read_text(encoding="utf-8"), "docs/guide.md")
+ if r.kind is DriftKind.SYMBOL and r.line == 10
+ ]
+ ((res, _),) = resolve_symbols(refs, root=history, symbol_names=_INDEXED)
+ assert (res.verdict, res.detail) == (DriftVerdict.UNCHECKABLE, "uncommitted")
+
+
+# ---------------------------------------------------------------------------
+# Incremental recheck
+# ---------------------------------------------------------------------------
+
+
+@git_required
+def test_recheck_reads_names_from_changed_lines_of_non_documents(history: Path):
+ base = _git(history, "rev-list", "--max-parents=0", "HEAD")
+ recheck = symbol_recheck(history, base, ["src/app.py"])
+ assert {"load_items", "parse_config", "parse_conf"} <= recheck.names
+ # A name only a document changed is not a trigger.
+ assert "Guide" not in recheck.names
+ assert recheck.wants("docs/guide.md", "load_items")
+ assert not recheck.wants("docs/other.md", "unrelated_name")
+
+
+def test_recheck_always_wants_a_changed_document():
+ recheck = SymbolRecheck(frozenset({"docs/a.md"}), frozenset())
+ assert recheck.whole("docs/a.md")
+ assert not recheck.wants("docs/b.md", "x_y")
+ assert SymbolRecheck(frozenset(), None).whole("docs/b.md")
+
+
+@git_required
+def test_an_untouched_document_is_not_reresolved(history: Path):
+ analyzer = DocDriftAnalyzer(
+ source_map={"docs/guide.md": _DOC.encode()},
+ tracked_paths={"docs/guide.md", "src/app.py"},
+ repo_root=history,
+ symbols=SymbolOptions(_INDEXED, SymbolRecheck(frozenset(), frozenset({"unrelated_name"}))),
+ )
+ report = analyzer.analyze()
+ assert report.symbol_scope == SymbolScope()
+ assert not [f for f in report.findings if f.kind is DriftKind.SYMBOL]
+
+
+@git_required
+def test_a_removed_line_name_rechecks_only_that_reference(history: Path):
+ analyzer = DocDriftAnalyzer(
+ source_map={"docs/guide.md": _DOC.encode()},
+ tracked_paths={"docs/guide.md", "src/app.py"},
+ repo_root=history,
+ symbols=SymbolOptions(_INDEXED, SymbolRecheck(frozenset(), frozenset({"load_items"}))),
+ )
+ report = analyzer.analyze()
+ assert report.symbol_scope == SymbolScope(references=frozenset({("docs/guide.md", "load_items")}))
+ assert {f.target for f in report.findings if f.kind is DriftKind.SYMBOL} == {"load_items"}
+
+
+@git_required
+def test_a_changed_document_is_rechecked_whole(history: Path):
+ analyzer = DocDriftAnalyzer(
+ source_map={"docs/guide.md": _DOC.encode()},
+ tracked_paths={"docs/guide.md", "src/app.py"},
+ repo_root=history,
+ symbols=SymbolOptions(_INDEXED, SymbolRecheck(frozenset({"docs/guide.md"}), frozenset())),
+ )
+ report = analyzer.analyze()
+ assert report.symbol_scope == SymbolScope(documents=frozenset({"docs/guide.md"}))
+ assert len([f for f in report.findings if f.kind is DriftKind.SYMBOL]) == 2
+
+
+# ---------------------------------------------------------------------------
+# Through the analyzer
+# ---------------------------------------------------------------------------
+
+
+@git_required
+def test_analyzer_places_the_suggestion_on_every_copy(history: Path):
+ analyzer = DocDriftAnalyzer(
+ source_map={"docs/guide.md": _DOC.encode()},
+ tracked_paths={"docs/guide.md", "src/app.py"},
+ repo_root=history,
+ symbols=SymbolOptions(_INDEXED),
+ )
+ report = analyzer.analyze()
+ symbols = {f.target: f for f in report.findings if f.kind is DriftKind.SYMBOL}
+ assert set(symbols) == {"Loader.parse_config", "load_items"}
+ renamed = symbols["Loader.parse_config"]
+ assert renamed.suggestion == "Loader.parse_conf()"
+ assert renamed.suggested_line == (
+ "Call `Loader.parse_conf()` first, and `Loader.parse_conf()` again."
+ )
+ # 1-based, end-exclusive: both copies of ``Loader.parse_config()``.
+ assert renamed.suggestion_columns == ((7, 28), (42, 63))
+ assert any(line.startswith("defined in src/app.py at ") for line in renamed.evidence)
+ assert symbols["load_items"].suggested_line == ""
+ # Mentioned or never-defined candidates are not references at all.
+ assert report.verdict_summary == {
+ "resolved": 1,
+ "missing": 2,
+ "ambiguous": 0,
+ "uncheckable": 0,
+ }
+ assert report.symbol_scope is None
+
+
+def test_without_symbol_names_the_symbol_kind_does_not_run(tmp_path: Path):
+ analyzer = DocDriftAnalyzer(
+ source_map={"docs/guide.md": _DOC.encode()},
+ tracked_paths={"docs/guide.md"},
+ repo_root=tmp_path,
+ )
+ report = analyzer.analyze()
+ assert report.references_checked == 0
+ assert report.findings == []
+
+
+def test_a_call_only_candidate_looks_up_its_name(tmp_path: Path):
+ """``load()`` is a candidate only for its ``()``; the lookup must still find ``load``."""
+ (ref,) = extract("Call `load()`.", "docs/x.md")
+ assert ref.target == "load"
+ ((res, _),) = resolve_symbols([ref], root=tmp_path, symbol_names={"load"})
+ assert res.verdict is DriftVerdict.RESOLVED
diff --git a/tests/unit/persistence/test_doc_drift_crud.py b/tests/unit/persistence/test_doc_drift_crud.py
index 729bb5a06..f0f479988 100644
--- a/tests/unit/persistence/test_doc_drift_crud.py
+++ b/tests/unit/persistence/test_doc_drift_crud.py
@@ -8,7 +8,7 @@ from __future__ import annotations
from sqlalchemy import select
-from repowise.core.analysis.doc_drift.models import DocDriftFindingData, DriftKind
+from repowise.core.analysis.doc_drift.models import DocDriftFindingData, DriftKind, SymbolScope
from repowise.core.persistence.crud import (
doc_drift_last_written,
get_doc_drift_findings,
@@ -334,3 +334,63 @@ async def test_a_snapshot_records_the_stored_drift_count(async_session):
await replace_doc_drift_findings(async_session, repo.id, [_finding(), _finding(line=2)])
counted = await save_health_snapshot(async_session, repo.id, **kwargs)
assert counted.doc_drift_count == 2
+
+
+async def test_symbol_findings_of_untouched_documents_carry_forward(async_session):
+ """An update re-resolves symbols in some documents; the rest keep theirs."""
+ repo = await insert_repo(async_session)
+ kept = _finding("docs/a.md", 3, "old_helper", DriftKind.SYMBOL)
+ fixed = _finding("docs/b.md", 4, "gone_helper", DriftKind.SYMBOL)
+ await replace_doc_drift_findings(
+ async_session, repo.id, [kept, fixed, _finding("docs/a.md", 9)]
+ )
+ await async_session.commit()
+
+ # Both documents re-read (cheap kinds re-derived); symbols only in b.md.
+ await replace_doc_drift_findings(
+ async_session,
+ repo.id,
+ [_finding("docs/a.md", 9)],
+ scope={"docs/a.md", "docs/b.md"},
+ symbol_scope=SymbolScope(documents=frozenset({"docs/b.md"})),
+ )
+ await async_session.commit()
+ rows = {(r.file_path, r.kind, r.target) for r in await _rows(async_session, repo.id)}
+ assert rows == {("docs/a.md", "symbol", "old_helper"), ("docs/a.md", "path", "src/gone.py")}
+
+
+async def test_a_rechecked_reference_is_replaced_and_its_neighbours_kept(async_session):
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_findings(
+ async_session,
+ repo.id,
+ [
+ _finding("docs/a.md", 3, "old_helper", DriftKind.SYMBOL),
+ _finding("docs/a.md", 5, "other_helper", DriftKind.SYMBOL),
+ ],
+ )
+ await async_session.commit()
+
+ # Only ``old_helper`` was re-resolved, and it now resolves.
+ await replace_doc_drift_findings(
+ async_session,
+ repo.id,
+ [],
+ scope={"docs/a.md"},
+ symbol_scope=SymbolScope(references=frozenset({("docs/a.md", "old_helper")})),
+ )
+ await async_session.commit()
+ rows = {r.target for r in await _rows(async_session, repo.id)}
+ assert rows == {"other_helper"}
+
+
+async def test_a_symbol_finding_outside_the_symbol_scope_is_not_inserted(async_session):
+ repo = await insert_repo(async_session)
+ await replace_doc_drift_findings(
+ async_session,
+ repo.id,
+ [_finding("docs/a.md", 3, "old_helper", DriftKind.SYMBOL)],
+ symbol_scope=SymbolScope(),
+ )
+ await async_session.commit()
+ assert await _rows(async_session, repo.id) == []
diff --git a/tests/unit/pipeline/test_doc_drift_incremental.py b/tests/unit/pipeline/test_doc_drift_incremental.py
index bf966f932..314d7b788 100644
--- a/tests/unit/pipeline/test_doc_drift_incremental.py
+++ b/tests/unit/pipeline/test_doc_drift_incremental.py
@@ -14,7 +14,14 @@ import pytest
from repowise.core.analysis.doc_drift import DocDriftAnalyzer
from repowise.core.pipeline import PhaseTimings
-from repowise.core.pipeline.incremental import run_doc_drift_partial
+from repowise.core.pipeline.incremental import DocDriftUpdate, run_doc_drift_partial
+
+
+def _partial(*args: Any, **kwargs: Any) -> Any:
+ """The pass with the index's symbol names given, as the stub has no graph."""
+ return run_doc_drift_partial(
+ *args, update=DocDriftUpdate(symbol_names=frozenset()), **kwargs
+ )
class _Builder:
@@ -30,7 +37,7 @@ def _sources(doc: bytes) -> dict[str, bytes]:
def test_a_document_naming_a_live_file_is_not_a_finding() -> None:
- report = run_doc_drift_partial(
+ report = _partial(
_Builder({"docs/guide.md", "src/real.py"}),
_sources(b"# Guide\n\nSee `src/real.py` for details.\n"),
)
@@ -39,7 +46,7 @@ def test_a_document_naming_a_live_file_is_not_a_finding() -> None:
def test_a_document_naming_a_missing_file_is_a_finding() -> None:
- report = run_doc_drift_partial(
+ report = _partial(
_Builder({"docs/guide.md", "src/real.py"}),
_sources(b"# Guide\n\nSee `src/gone.py` for details.\n"),
)
@@ -54,7 +61,7 @@ def test_the_write_is_scoped_to_the_documents_actually_read() -> None:
not open, and nothing would write them back: ``prune_deleted_file_rows``
correctly judges the file live and leaves it alone.
"""
- report = run_doc_drift_partial(
+ report = _partial(
_Builder({"docs/guide.md", "docs/unread.md", "src/real.py"}),
_sources(b"# Guide\n\nSee `src/gone.py`.\n"),
)
@@ -69,7 +76,7 @@ def test_tracked_paths_come_from_the_traversal_not_the_source_map() -> None:
``source_map`` omits it; resolving against that narrower set would report a
live path as missing, which is a fabricated finding rather than drift.
"""
- report = run_doc_drift_partial(
+ report = _partial(
# ``src/unparsed.py`` is tracked but absent from source_map.
_Builder({"docs/guide.md", "src/real.py", "src/unparsed.py"}),
_sources(b"# Guide\n\nSee `src/unparsed.py`.\n"),
@@ -84,8 +91,8 @@ def test_a_builder_without_a_traversal_skips_rather_than_falling_back() -> None:
The fallback would narrow the tree and fabricate findings, and the report
would look perfectly valid on the way to a scoped delete.
"""
- assert run_doc_drift_partial(_Builder(None), _sources(b"See `src/gone.py`.\n")) is None
- assert run_doc_drift_partial(_Builder(set()), _sources(b"See `src/gone.py`.\n")) is None
+ assert _partial(_Builder(None), _sources(b"See `src/gone.py`.\n")) is None
+ assert _partial(_Builder(set()), _sources(b"See `src/gone.py`.\n")) is None
@pytest.mark.parametrize("empty", [None, {}])
@@ -96,12 +103,12 @@ def test_an_empty_source_map_returns_none_rather_than_an_empty_report(empty: Any
ingestion degraded would look like a clean pass. Returning ``None`` keeps
"the pass did not run" distinguishable from "the pass found nothing".
"""
- assert run_doc_drift_partial(_Builder({"docs/guide.md"}), empty) is None
+ assert _partial(_Builder({"docs/guide.md"}), empty) is None
def test_a_clean_run_still_returns_a_report_so_stale_rows_are_cleared() -> None:
"""Zero findings is a result, not a reason to skip the write."""
- report = run_doc_drift_partial(
+ report = _partial(
_Builder({"docs/guide.md", "src/real.py"}),
_sources(b"# Guide\n\nNothing to see.\n"),
)
@@ -120,7 +127,7 @@ def test_an_analyzer_failure_degrades_to_none(monkeypatch: pytest.MonkeyPatch) -
monkeypatch.setattr(dd, "DocDriftAnalyzer", _boom)
messages: list[str] = []
assert (
- run_doc_drift_partial(
+ _partial(
_Builder({"docs/guide.md"}),
_sources(b"See `src/gone.py`.\n"),
log=messages.append,
@@ -133,7 +140,7 @@ def test_an_analyzer_failure_degrades_to_none(monkeypatch: pytest.MonkeyPatch) -
def test_the_pass_records_its_own_timing_row() -> None:
"""Visible as ``analysis.doc_drift`` rather than absorbed into rebuild."""
timings = PhaseTimings()
- run_doc_drift_partial(
+ _partial(
_Builder({"docs/guide.md", "src/real.py"}),
_sources(b"# Guide\n"),
timings=timings,
@@ -151,7 +158,7 @@ def test_the_incremental_pass_agrees_with_the_full_one() -> None:
tracked = {"docs/guide.md", "src/real.py"}
full = DocDriftAnalyzer(source_map=sources, tracked_paths=tracked).analyze()
- partial = run_doc_drift_partial(_Builder(tracked), sources)
+ partial = _partial(_Builder(tracked), sources)
assert partial is not None
assert [(f.file_path, f.target) for f in partial.findings] == [