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.

fix(health): score --score files against the index's clone partners (#4499)

Raghav Chamadiya848fcfc9bdb6
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 55b36f075..cd7addca0 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -881,7 +881,7 @@ coverage gradient, function/ownership/churn/change-entropy organizational risk,
| `--counts` | `everything` or `code_shape` (drops the git-derived half, which rises as a file is worked on: is the code itself improving?). | `everything` |
| `--refactoring-targets` | Stored queue: per file, graph-aware plans (Extract Class / Helper / Method, Move Method, Split File) as ordered steps, Break Cycle advisory; MCP and web UI order. Needs `repowise init`; [REFACTORING.md](../layers/REFACTORING.md). | off |
| `--recompute` | Analyze the working tree in-process (slow on large repos; needed without an index); see notes. | off |
-| `--score <path>` | Score on-disk files pre-update or PR; repeatable. Bytes give structure, the index the rest (history, coverage, test pairing, dependents), as the next update would; no index: code shape. JSON: `files`, `score_change`. | |
+| `--score <path>` | Score on-disk files pre-update or PR; repeatable. Bytes give structure, the index the rest (history, coverage, test pairing, dependents, clone partners), as the next update would, so an unedited file scores what the index stores; no index: code shape. JSON: `files`, `score_change`, `clone_source`. | |
| `--against <rev>` | With `--score`: before, after, change, nloc-weighted average at `<rev>`. | |
| `--generate-code <selector>` | Patch for one `path::symbol` target; the only LLM flag (needs a provider). | |
| `--plan <id>` | Stored plan as an agent prompt; JSON: recipe (preconditions, steps, postconditions). Reads the index. | |
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/command.py b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
index 8a9f685e6..2073cbd81 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
@@ -685,7 +685,7 @@ def _render_files_table(metrics_sorted: list[Any], short_history: set[str]) -> N
score_color = BAND_TERMINAL_COLOR[band_for(m.score)]
table.add_row(
m.file_path,
- f"[{score_color}]{m.score:.1f}[/{score_color}]"
+ f"[{score_color}]{m.score:.2f}[/{score_color}]"
+ ("*" if m.file_path in short_history else ""),
str(m.max_ccn),
str(m.max_nesting),
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/live_score.py b/packages/cli/src/repowise/cli/commands/health_cmd/live_score.py
index b6602f904..b8ac6a3fb 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/live_score.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/live_score.py
@@ -1,8 +1,9 @@
"""``repowise health --score``: score files as they are on disk, before a PR exists.
Structure comes from parsing the bytes; history, coverage, test pairing, blame
-findings and dependents come from the index (``IndexInputs``), so a file scores
-about as the next ``repowise update`` would, with no update run.
+findings, dependents and clone partners come from the index (``IndexInputs``),
+so a file scores as the next ``repowise update`` would, with no update run: an
+unedited file scores what the index stores.
"""
from __future__ import annotations
@@ -89,7 +90,7 @@ def _index_inputs(repo_path: Path) -> IndexInputs:
if opened is None:
return IndexInputs()
session, repo_id = opened
- return await load_index_inputs(session, repo_id)
+ return await load_index_inputs(session, repo_id, repo_path / ".repowise")
try:
return run_async(_do())
@@ -133,6 +134,11 @@ def render_live(scores: LiveScores, fmt: str) -> None:
f"{change.head:.2f} ({change.head - change.base:+.2f}; structure deduction "
f"{change.structure_delta:+.2f})"
)
+ if scores.indexed and scores.head.clone_source == "analyzed_files":
+ console.print(
+ "[dim]The index's clone state is unavailable (run `repowise update`): "
+ "duplication counts only clones among the scored files.[/dim]"
+ )
if not scores.indexed:
console.print(
"[dim]No index history: history, coverage and test pairing are left out "
@@ -151,6 +157,7 @@ def live_payload(scores: LiveScores) -> dict[str, Any]:
"basis": "live",
"analyzer_version": HEALTH_ANALYZER_VERSION,
"history_source": "index" if scores.indexed else "none",
+ "clone_source": scores.head.clone_source,
"against": scores.against,
"files": [
{**row.as_dict(), "head_history": _history(scores.head, row.path)}
diff --git a/packages/core/src/repowise/core/analysis/change_health/analyzer.py b/packages/core/src/repowise/core/analysis/change_health/analyzer.py
index cc781b89d..53cac0ba4 100644
--- a/packages/core/src/repowise/core/analysis/change_health/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/change_health/analyzer.py
@@ -127,6 +127,9 @@ class RevisionAnalysis:
symbols: dict[str, list[Symbol]] = field(default_factory=dict)
#: Per-file scores and deductions, by path.
metrics: dict[str, HealthFileMetricData] = field(default_factory=dict)
+ #: Where clones came from: "index" (partners outside *sources* counted),
+ #: "analyzed_files" (only among *sources*), None when duplication was off.
+ clone_source: str | None = None
def findings_for(self, paths: set[str]) -> list[HealthFindingData]:
return [f for f in self.findings if f.file_path in paths]
@@ -161,7 +164,8 @@ class RevisionHealthAnalyzer:
a file across a centrality gate without any change to its code.
*index* adds what the index knows (history, coverage, test pairing,
- blame findings); without it a score is the code-shape reading.
+ blame findings, clone partners); without it a score is the code-shape
+ reading.
*caches* serves parses and walks seen before; the result is the same
with or without it.
@@ -186,6 +190,7 @@ class RevisionHealthAnalyzer:
result.dependents = analyzer.file_dependents()
result.symbols = {pf.file_info.path: pf.symbols for pf in parsed}
result.metrics = {m.file_path: m for m in report.metrics}
+ result.clone_source = analyzer.clone_source
return result
# -- internals ----------------------------------------------------------
@@ -263,6 +268,7 @@ def _index_kwargs(index: IndexInputs) -> dict[str, Any]:
"coverage_map": index.coverage,
"tested_files": index.tested_files,
"stored_blame_findings": index.blame_findings,
+ "clone_index_dir": index.clone_index_dir,
}
diff --git a/packages/core/src/repowise/core/analysis/change_health/index_inputs.py b/packages/core/src/repowise/core/analysis/change_health/index_inputs.py
index dd984c927..2669822ee 100644
--- a/packages/core/src/repowise/core/analysis/change_health/index_inputs.py
+++ b/packages/core/src/repowise/core/analysis/change_health/index_inputs.py
@@ -8,6 +8,7 @@ with them reads as the next ``repowise update`` would score it.
from __future__ import annotations
from dataclasses import dataclass, field
+from pathlib import Path
from typing import Any
from sqlalchemy import select
@@ -20,20 +21,26 @@ from .index_context import index_dependents
@dataclass(frozen=True)
class IndexInputs:
- """The index's history, coverage, test pairing, blame findings and dependents."""
+ """The index's history, coverage, test pairing, blame findings, dependents
+ and clone state."""
git_meta: dict[str, dict] = field(default_factory=dict)
coverage: dict[str, dict[str, Any]] = field(default_factory=dict)
tested_files: frozenset[str] = frozenset()
blame_findings: dict[str, list[Any]] = field(default_factory=dict)
dependents: dict[str, int] | None = None
+ #: The index's ``.repowise``, whose clone pair state lets a file's clones
+ #: with files the pass does not read still count.
+ clone_index_dir: Path | None = None
@property
def has_history(self) -> bool:
return bool(self.git_meta)
-async def load_index_inputs(session: AsyncSession, repository_id: str) -> IndexInputs:
+async def load_index_inputs(
+ session: AsyncSession, repository_id: str, clone_index_dir: Path | None = None
+) -> IndexInputs:
"""Every stored input a file's score reads beyond its own bytes."""
from ...persistence.crud import get_all_git_metadata, load_coverage_map
@@ -50,6 +57,7 @@ async def load_index_inputs(session: AsyncSession, repository_id: str) -> IndexI
tested_files=frozenset(tested.scalars().all()),
blame_findings=await _blame_findings(session, repository_id),
dependents=await index_dependents(session, repository_id),
+ clone_index_dir=clone_index_dir,
)
diff --git a/packages/core/src/repowise/core/analysis/health/duplication/detector.py b/packages/core/src/repowise/core/analysis/health/duplication/detector.py
index 3ed2c13e1..a42d05be5 100644
--- a/packages/core/src/repowise/core/analysis/health/duplication/detector.py
+++ b/packages/core/src/repowise/core/analysis/health/duplication/detector.py
@@ -320,6 +320,51 @@ def detect_clones(
)
+def clones_against_index(
+ parsed_files: Iterable[Any],
+ git_meta_map: dict[str, dict[str, Any]] | None,
+ cache_dir: Path,
+ *,
+ window_tokens: int = DEFAULT_WINDOW_TOKENS,
+ min_lines: int = DEFAULT_MIN_LINES,
+ limits: DuplicationLimits | None = None,
+ source_reader: Any | None = None,
+) -> DuplicationReport | None:
+ """Clone pairs for *parsed_files* against every file the index holds, read-only.
+
+ The same splice ``repowise update`` runs with these files as the changed
+ ones, so a file scores as the next update would score it, with its clone
+ partners as the index last read them. Nothing in *cache_dir* is written.
+ ``None`` when the index's pair state cannot be spliced (missing, from
+ another analyzer version, truncated, or too many files moved).
+ """
+ from ..engine import HEALTH_ANALYZER_VERSION
+ from .pair_index import load_pair_index
+ from .token_cache import DuplicationTokenCache
+
+ lim = limits or DuplicationLimits()
+ index = load_pair_index(cache_dir, window_tokens, lim)
+ if index is None:
+ return None
+ cache = DuplicationTokenCache(cache_dir, window_tokens, HEALTH_ANALYZER_VERSION)
+ cache.load()
+ parsed_list = list(parsed_files)
+ return _detect_clones_incremental(
+ parsed_list,
+ git_meta_map or {},
+ {pf.file_info.path for pf in parsed_list},
+ window_tokens,
+ min_lines,
+ lim,
+ DuplicationDiagnostics(),
+ cache,
+ index,
+ cache_dir,
+ source_reader,
+ persist=False,
+ )
+
+
# ---------------------------------------------------------------------------
# Stage 1 — windowing
# ---------------------------------------------------------------------------
@@ -561,6 +606,8 @@ def _detect_clones_incremental(
index: Any,
cache_dir: Path,
read_source: Any | None = None,
+ *,
+ persist: bool = True,
) -> DuplicationReport | None:
"""Splice the persisted raw-pair multiset instead of recomputing it.
@@ -579,6 +626,10 @@ def _detect_clones_incremental(
safely (truncated/timed-out runs, missing cache entries, too many
changes, accounting mismatch); the caller falls back to the full
pipeline.
+
+ *persist* false is the read-only form (:func:`clones_against_index`):
+ *parsed_files* are the only files read, every other file the index holds
+ is taken as unchanged rather than deleted, and nothing is written back.
"""
from collections import Counter
@@ -587,14 +638,15 @@ def _detect_clones_incremental(
current = {pf.file_info.path: pf for pf in parsed_files}
old_files: dict[str, str] = index.files
+ present = set(current) if persist else set(current) | set(old_files)
# Files the previous run considered but gated out are not "new";
# unchanged ones stay gated (same bytes, same gates), changed ones
# arrive via changed_files and re-evaluate the gates live.
new_paths = set(current) - set(old_files) - index.nonsurvivors
- deleted = set(old_files) - set(current)
+ deleted = set(old_files) - present
changed = (changed_files & set(current)) | new_paths
moved = len(changed) + len(deleted)
- if moved > max(_CHANGED_COUNT_FLOOR, _MAX_CHANGED_FRACTION * len(current)):
+ if moved > max(_CHANGED_COUNT_FLOOR, _MAX_CHANGED_FRACTION * len(present)):
return None
# Paths whose OLD windows leave the state (modified or deleted).
affected_old = (changed | deleted) & set(old_files)
@@ -699,8 +751,18 @@ def _detect_clones_incremental(
# 7. Splice the multiset. A negative count means the persisted state
# disagrees with the recomputed old contribution — fall back.
paths_table: list[str] = index.paths
+ if not persist:
+ # Read-only wants only the read files' pairs. A pair between two other
+ # files is spliced independently of these, so leaving it out changes
+ # nothing kept and skips counting the whole repository's pairs.
+ read = {i for i, path in enumerate(paths_table) if path in current}
+ rows = [r for r in index.pairs if r[0] in read or r[1] in read]
+ old_contrib = [p for p in old_contrib if p.file_a in current or p.file_b in current]
+ new_contrib = [p for p in new_contrib if p.file_a in current or p.file_b in current]
+ else:
+ rows = index.pairs
pair_counter: Counter[_PairKey] = Counter()
- for pid_a, pid_b, a_sl, a_el, b_sl, b_el, count in index.pairs:
+ for pid_a, pid_b, a_sl, a_el, b_sl, b_el, count in rows:
pair_counter[(paths_table[pid_a], paths_table[pid_b], a_sl, a_el, b_sl, b_el)] += count
pair_counter.subtract(Counter(_pair_key(p) for p in old_contrib))
if -pair_counter: # truthy when any count went negative
@@ -725,6 +787,16 @@ def _detect_clones_incremental(
if count > 0
]
+ if not persist:
+ final = _finalize_pairs(_merge_adjacent_pairs(raw_pairs), min_lines, meta_map)
+ pairs_by_file, duplication_pct = _aggregate(final, per_file_nloc)
+ return DuplicationReport(
+ pairs=final,
+ duplication_pct=duplication_pct,
+ pairs_by_file=pairs_by_file,
+ diagnostics={**diag.as_log_fields(), "incremental": True, "read_only": True},
+ )
+
# 8. Persist the spliced state and the retained token cache before
# finalizing, mirroring the full path's ordering.
from .pair_index import DuplicationPairIndex, limits_fingerprint, save_pair_index
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index b3dea17fb..afcbea2f8 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -50,7 +50,7 @@ from .coverage_actions import paired_test_index
from .crossfn_perf import CrossFunctionPerfStage
from .dataflow import FileDataflowCache
from .duplication import ClonePair, DuplicationReport
-from .duplication.detector import clone_ranges, union_line_count
+from .duplication.detector import clone_ranges, clones_against_index, union_line_count
from .duplication.isolation import detect_clones_with_isolation as detect_clones
from .file_evaluator import FileEvaluator, _read_source_lines, _RunConfig
from .file_evaluator import _mark_deepest_block as _mark_deepest_block
@@ -560,6 +560,7 @@ class HealthAnalyzer:
tested_files: set[str] | frozenset[str] | None = None,
walk_cache: HealthWalkCache | None = None,
package_roots: set[str] | None = None,
+ clone_index_dir: Any | None = None,
) -> None:
self.graph = graph
self.git_meta_map = git_meta_map or {}
@@ -610,6 +611,13 @@ class HealthAnalyzer:
# without a blame index (a re-score from stored git metadata) so the
# pass does not delete what it cannot recompute.
self.stored_blame_findings = stored_blame_findings or {}
+ # An index's ``.repowise`` for a pass over a few files: their clones
+ # are spliced against the index's pair state (read-only) so partners
+ # this pass never reads still count. ``clone_source`` says where the
+ # last pass's clones came from: "index", "analyzed_files" (only among
+ # the files it read), or None when duplication did not run.
+ self.clone_index_dir = clone_index_dir
+ self.clone_source: str | None = None
# Dependents counts to gate centrality on instead of this graph's. A
# revision comparison passes the other side's, so a file crossing a
# centrality gate inside a partial graph is not read as a code change.
@@ -807,9 +815,16 @@ class HealthAnalyzer:
"""
from repowise.core.pipeline.phase_timing import timed
+ self.clone_source = None
# An empty splice set: no file whose clone list a biomarker reads changed.
if "dry_violation" in run.disabled or changed == set():
return DuplicationReport()
+ if self.clone_index_dir is not None:
+ report = self._clones_against_index()
+ if report is not None:
+ self.clone_source = "index"
+ return report
+ self.clone_source = "analyzed_files"
try:
with timed(timings, "analysis.health.duplication"):
report = detect_clones(
@@ -825,6 +840,22 @@ class HealthAnalyzer:
log.debug("health_duplication_failed", error=str(exc))
return DuplicationReport()
+ def _clones_against_index(self) -> DuplicationReport | None:
+ # A missing, stale or truncated clone state is ``None`` without raising,
+ # so anything raised here is a defect: say so at warning rather than let
+ # the files-only fallback pass for the expected no-index case.
+ try:
+ report = clones_against_index(
+ self.parsed_files,
+ self.git_meta_map,
+ Path(self.clone_index_dir),
+ source_reader=self.read_source,
+ )
+ except Exception as exc:
+ log.warning("health_index_clones_failed", error=repr(exc))
+ return None
+ return report
+
def _target_files(self, changed_set: set[str] | None) -> list[Any]:
"""The parsed files this pass scores: only the changed ones on an incremental run."""
return [
diff --git a/tests/unit/change_health/test_live_score_clones.py b/tests/unit/change_health/test_live_score_clones.py
new file mode 100644
index 000000000..3d84ba6b4
--- /dev/null
+++ b/tests/unit/change_health/test_live_score_clones.py
@@ -0,0 +1,107 @@
+"""``health --score`` on an unedited file equals the score the index stores.
+
+The live pass reads only the scored file, so its clone partners come from the
+index's clone state; without that, cross-file duplication went uncounted and
+the live score read higher than the stored one.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.cli.commands.health_cmd import live_score
+from repowise.core.analysis.change_health.analyzer import RevisionAnalysis, RevisionHealthAnalyzer
+from repowise.core.analysis.change_health.index_inputs import IndexInputs
+from repowise.core.analysis.health.engine import HealthAnalyzer
+from repowise.core.analysis.health.source_reader import MappingSourceReader
+
+from .conftest import python_complex
+
+_SOURCE = "app/a.py"
+_FILES = {
+ _SOURCE: python_complex("run", 14),
+ "app/b.py": python_complex("run", 14),
+ "app/c.py": python_complex("other", 3),
+}
+
+
+def _full_pass(repo: Path) -> dict[str, float]:
+ """The index's pass over every file, which writes its clone state."""
+ sources = {path: (repo / path).read_bytes() for path in _FILES}
+ revision = RevisionHealthAnalyzer(repo_root=str(repo))
+ parsed, usable = revision._parse(sources, RevisionAnalysis(), None)
+ report = HealthAnalyzer(
+ revision._graph(parsed, usable),
+ parsed_files=parsed,
+ repo_root=str(repo),
+ source_reader=MappingSourceReader(usable),
+ duplication_cache_dir=repo / ".repowise",
+ ).analyze()
+ assert any(
+ f.biomarker_type == "dry_violation" and f.file_path == _SOURCE for f in report.findings
+ )
+ return {m.file_path: m.score for m in report.metrics}
+
+
+def test_score_of_an_unedited_file_equals_the_stored_score(make_repo, monkeypatch):
+ repo = make_repo()
+ repo.commit("seed", _FILES)
+ stored = _full_pass(Path(repo.path))
+ inputs = IndexInputs(clone_index_dir=Path(repo.path) / ".repowise")
+ monkeypatch.setattr(live_score, "_index_inputs", lambda _path: inputs)
+
+ scores = live_score.score_live(Path(repo.path), [_SOURCE], "HEAD")
+
+ row = scores.rows[0]
+ assert scores.head.clone_source == "index"
+ assert row.head_score == stored[_SOURCE]
+ assert row.base_score == stored[_SOURCE]
+
+
+def test_without_the_index_clone_state_the_payload_says_so(make_repo, monkeypatch):
+ repo = make_repo()
+ repo.commit("seed", _FILES)
+ monkeypatch.setattr(live_score, "_index_inputs", lambda _path: IndexInputs())
+
+ scores = live_score.score_live(Path(repo.path), [_SOURCE], None)
+
+ assert scores.head.clone_source == "analyzed_files"
+ assert live_score.live_payload(scores)["clone_source"] == "analyzed_files"
+
+
+def test_with_duplication_disabled_no_clone_source_is_claimed(make_repo, monkeypatch):
+ repo = make_repo()
+ repo.commit("seed", _FILES)
+ rules = Path(repo.path) / ".repowise" / "health-rules.json"
+ rules.parent.mkdir()
+ rules.write_text('{"disabled_biomarkers": ["dry_violation"]}', encoding="utf-8")
+ monkeypatch.setattr(live_score, "_index_inputs", lambda _path: IndexInputs())
+
+ scores = live_score.score_live(Path(repo.path), [_SOURCE], None)
+
+ assert scores.head.clone_source is None
+
+
+def test_a_failing_index_splice_is_logged_as_a_warning(make_repo, monkeypatch):
+ from structlog.testing import capture_logs
+
+ from repowise.core.analysis.health import engine
+
+ repo = make_repo()
+ repo.commit("seed", _FILES)
+ _full_pass(Path(repo.path))
+
+ def broken(*_args, **_kwargs):
+ raise KeyError("app/b.py")
+
+ monkeypatch.setattr(engine, "clones_against_index", broken)
+ inputs = IndexInputs(clone_index_dir=Path(repo.path) / ".repowise")
+ monkeypatch.setattr(live_score, "_index_inputs", lambda _path: inputs)
+
+ with capture_logs() as logs:
+ scores = live_score.score_live(Path(repo.path), [_SOURCE], None)
+
+ assert scores.head.clone_source == "analyzed_files"
+ assert any(
+ e["event"] == "health_index_clones_failed" and e["log_level"] == "warning" for e in logs
+ )
diff --git a/tests/unit/cli/test_health_cmd_short_history.py b/tests/unit/cli/test_health_cmd_short_history.py
index 6c06f6671..bbb50d552 100644
--- a/tests/unit/cli/test_health_cmd_short_history.py
+++ b/tests/unit/cli/test_health_cmd_short_history.py
@@ -32,5 +32,5 @@ def test_table_marks_the_score_and_explains_the_mark() -> None:
console.file = io.StringIO()
health_module._render_files_table([_metric("src/old.py")], {"src/new.py"})
plain = console.file.getvalue()
- assert "7.0*" in marked and "Short history" in marked
+ assert "7.00*" in marked and "Short history" in marked
assert "*" not in plain and "Short history" not in plain
diff --git a/tests/unit/health/test_duplication_incremental.py b/tests/unit/health/test_duplication_incremental.py
index fd29877a8..406a77de9 100644
--- a/tests/unit/health/test_duplication_incremental.py
+++ b/tests/unit/health/test_duplication_incremental.py
@@ -433,3 +433,46 @@ def test_incremental_does_not_pair_across_languages(tmp_path: Path):
cross = {(p.file_a, p.file_b) for p in report.pairs if p.file_a != p.file_b}
assert cross == set()
assert _key(report) == _key(_full(parsed))
+
+
+def _against_index(parsed, cache_dir):
+ from repowise.core.analysis.health.duplication.detector import clones_against_index
+
+ return clones_against_index(
+ parsed, None, cache_dir, window_tokens=WINDOW, min_lines=MIN_LINES, limits=LIMITS
+ )
+
+
+def _file_view(report, path):
+ pairs = sorted(
+ (p.file_a, p.file_b, p.a_start_line, p.a_end_line, p.b_start_line, p.b_end_line)
+ for p in report.pairs_by_file.get(path, [])
+ )
+ return pairs, report.duplication_pct.get(path)
+
+
+def test_against_index_reads_one_file_and_finds_partners_it_never_read(tmp_path: Path):
+ cache_dir = _seed(tmp_path, {"a.py": _BODY, "b.py": _BODY, "c.py": _OTHER})
+ stored = {p.name: p.read_bytes() for p in cache_dir.iterdir()}
+ one = [_pf(tmp_path, "a.py")]
+
+ report = _against_index(one, cache_dir)
+ assert report is not None
+ assert _file_view(report, "a.py") == _file_view(_full(_parsed(tmp_path)), "a.py")
+ assert _file_view(report, "a.py")[0] # b.py was never read, yet pairs with a.py
+ # Read-only: the index's clone state is left as it was.
+ assert {p.name: p.read_bytes() for p in cache_dir.iterdir()} == stored
+
+
+def test_against_index_rescores_an_edited_file(tmp_path: Path):
+ cache_dir = _seed(tmp_path, {"a.py": _BODY, "b.py": _BODY, "c.py": _OTHER})
+ (tmp_path / "a.py").write_text(_OTHER.replace("other", "mutated"))
+
+ report = _against_index([_pf(tmp_path, "a.py")], cache_dir)
+ assert report is not None
+ assert _file_view(report, "a.py") == _file_view(_full(_parsed(tmp_path)), "a.py")
+
+
+def test_against_index_without_one_is_none(tmp_path: Path):
+ _write(tmp_path, {"a.py": _BODY})
+ assert _against_index([_pf(tmp_path, "a.py")], tmp_path / ".repowise") is None