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(cli): repowise health --score scores files from disk, --against compares a revision (#4139)

Raghav Chamadiyaf47fce47f2fa
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index a098cc6c2..37acd974d 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1130,6 +1130,8 @@ When a listed finding or plan sits on a language its layer serves as a preview,
| `--counts` | `everything` (default) or `code_shape`. `code_shape` drops the git-derived half of the deduction, which rises as a file is worked on — the reading that answers whether the code itself is improving. |
| `--refactoring-targets` | Print the refactoring queue the index stored: one opportunity per file with its structured, graph-aware plans (Extract Class / Helper / Method, Move Method, Split File) as ordered steps and Break Cycle as advisory evidence, in the same order MCP and the web UI serve. Reads the index, so it needs `repowise init` first. See [REFACTORING.md](../layers/REFACTORING.md) |
| `--recompute` | Analyze the working tree in-process instead of reading the stored analysis. A whole-repo `table` run writes the result back to the index (scores, findings, a trend snapshot); `json`, `md` and `--file`/`--module` runs never write. Slow on a large repo; the only option outside an indexed one. With `--refactoring-targets`, `--scope` and `--counts` apply only here. |
+| `--score <path>` | Score these files as they are on disk now (repeatable), before an update or a PR. Structure comes from the bytes; history, coverage, test pairing and dependents from the index, so a file reads as the next update would score it. With no index, the code-shape reading. `--format json` gives `files` and `score_change`. |
+| `--against <rev>` | With `--score`: also score the files at this revision and print before, after and the change, plus the average weighted by nloc at `<rev>`. |
| `--generate-code <selector>` | Generate an actual refactoring patch for one target. The only `health` flag that calls an LLM; needs a configured provider. |
| `--plan <id>` | Print one stored refactoring plan as the prompt an agent applies; with `--format json`, its recipe (preconditions, steps, postconditions). Reads the index. |
| `--trend` | Print the last 10 health snapshots + any active alerts (declining / predicted decline) |
@@ -1147,6 +1149,7 @@ repowise health --refactoring-targets # the stored queue, as MCP
repowise health --generate-code packages/server/app.py::handler # LLM patch for one target
repowise health --trend # snapshot history + alerts
repowise health --counts code_shape # ignore the git-derived half
+repowise health --score src/app.py --against origin/main # live score, before and after
repowise coverage add coverage.lcov # ingest coverage, then:
repowise health --recompute # fold it into the scores now (or wait for the next update)
repowise health --format json | jq .kpis # machine-readable
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 cab5f5260..5dc36b6ec 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/command.py
@@ -44,6 +44,7 @@ from repowise.core.analysis.health.signals import HISTORY_MIN_COMMITS
from repowise.core.persistence.crud.analysis.health import open_finding_count
from .codegen import _generate_refactoring_code
+from .live_score import analyzer_config
from .persist import (
_load_fix_first,
_load_persisted_coverage_map,
@@ -178,6 +179,19 @@ FIX_FIRST_ROWS = 3
default=False,
help="Print a ready-to-paste health badge (Markdown) for this repo's README.",
)
+ "--score",
+ "score_paths",
+ multiple=True,
+ type=click.Path(),
+ help="Score these files as they are on disk now (repeatable), with history "
+ "and coverage from the index. No update needed.",
+)
+ "--against",
+ default=None,
+ help="With --score: also score the files at this revision and show the change.",
+)
@click.option(
"--verbose",
"-v",
@@ -200,6 +214,8 @@ def health_command(
counts: str,
trend_view: bool,
badge_view: bool,
+ score_paths: tuple[str, ...],
+ against: str | None,
verbose: bool,
) -> None:
"""Code-health scores from markers (CCN, nesting, brain-method).
@@ -229,6 +245,11 @@ def health_command(
repo_path = _resolve_repo_path(path, no_workspace, repo_alias, status)
status.print(f"[bold]repowise health[/bold] — {repo_path}")
+ if score_paths:
+ _render_score_view(repo_path, score_paths, against, opts, badge_view)
+ return
+ if against is not None:
+ raise click.UsageError("--against needs --score <paths>.")
if _render_stored_view(repo_path, status, opts):
return
@@ -267,6 +288,18 @@ def _withheld(finding: Any, excluded: frozenset[str]) -> bool:
return not is_served("health", finding.biomarker_type, finding.file_path, excluded)
+def _render_score_view(
+ repo_path: Path, paths: tuple[str, ...], against: str | None, opts: _Options, badge: bool
+) -> None:
+ """``--score``: the files as they are on disk, beside *against* when given."""
+ from .live_score import render_live, repo_paths, score_live
+
+ clashing = opts.view_flags() + (["--badge"] if badge else [])
+ if clashing:
+ raise click.UsageError(f"--score does not combine with {', '.join(clashing)}.")
+ render_live(score_live(repo_path, repo_paths(repo_path, paths), against), opts.fmt)
+
+
@dataclass(frozen=True)
class _Options:
"""The options that pick a view and narrow the report."""
@@ -289,6 +322,20 @@ class _Options:
parse_scope(self.scope) != DEFAULT_SCOPE or parse_counts(self.counts) != DEFAULT_COUNTS
)
+ def view_flags(self) -> list[str]:
+ """The view and narrowing flags that were passed, by their CLI names."""
+ flags = {
+ "--file": self.file_filter,
+ "--module": self.module_filter,
+ "--refactoring-targets": self.refactoring_targets,
+ "--plan": self.plan_id,
+ "--recompute": self.recompute,
+ "--generate-code": self.generate_code,
+ "--trend": self.trend_view,
+ "--scope/--counts": self.controls_set,
+ }
+ return [name for name, value in flags.items() if value]
+
def keeps(self, file_path: str) -> bool:
"""Whether ``--file`` and ``--module`` keep a row on *file_path*."""
if self.file_filter and file_path != self.file_filter:
@@ -611,8 +658,6 @@ def _recompute_report(repo_path: Path, *, persist: bool) -> tuple[Any, set[str],
"""
from repowise.core.analysis.communities import file_community_labels
from repowise.core.analysis.health import HealthAnalyzer
- from repowise.core.analysis.health.config import HealthConfig
-
graph_builder, parsed_files = _parse_tree(repo_path)
git_meta_map: dict = {}
try:
@@ -634,14 +679,9 @@ def _recompute_report(repo_path: Path, *, persist: bool) -> tuple[Any, set[str],
duplication_cache_dir=Path(repo_path) / ".repowise",
repo_root=repo_path,
)
- # Any .repowise/health-rules.json the user keeps in the repo.
- health_cfg = HealthConfig.load(repo_path)
- analyzer_cfg = (
- health_cfg.to_analyzer_config([pf.file_info.path for pf in parsed_files])
- if (health_cfg.disabled_biomarkers or health_cfg.rules)
- else None
+ report = analyzer.analyze(
+ analyzer_config(repo_path, [pf.file_info.path for pf in parsed_files])
)
- report = analyzer.analyze(analyzer_cfg)
if persist:
_persist_health(repo_path, report=report)
hotspots = {p for p, m in git_meta_map.items() if m.get("is_hotspot")}
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
new file mode 100644
index 000000000..adb819aa8
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/live_score.py
@@ -0,0 +1,182 @@
+"""``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.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import click
+from rich.table import Table
+
+from repowise.cli.helpers import console, repo_index_session, run_async
+from repowise.core.analysis.change_health.analyzer import RevisionAnalysis, RevisionHealthAnalyzer
+from repowise.core.analysis.change_health.file_scores import (
+ FileScoreDelta,
+ file_score_deltas,
+ score_change,
+)
+from repowise.core.analysis.change_health.index_inputs import IndexInputs, load_index_inputs
+from repowise.core.analysis.change_health.sources import GitRevisionSource
+
+
+@dataclass(frozen=True)
+class LiveScores:
+ rows: list[FileScoreDelta]
+ head: RevisionAnalysis
+ against: str | None
+ #: False with no index: history and coverage are then left out.
+ indexed: bool
+
+
+def repo_paths(repo_path: Path, raw: tuple[str, ...]) -> list[str]:
+ """Repo-relative POSIX paths for what the user typed, from any directory."""
+ root = repo_path.resolve()
+ out: list[str] = []
+ outside: list[str] = []
+ for item in raw:
+ candidate = Path(item)
+ absolute = candidate if candidate.is_absolute() else Path.cwd() / candidate
+ try:
+ out.append(absolute.resolve().relative_to(root).as_posix())
+ except ValueError:
+ outside.append(item)
+ if outside:
+ raise click.UsageError(f"--score paths outside {root}: {', '.join(outside)}")
+ return list(dict.fromkeys(out))
+
+
+def score_live(repo_path: Path, paths: list[str], against: str | None) -> LiveScores:
+ """Score *paths* from disk, and at *against* too when given."""
+ inputs = _index_inputs(repo_path)
+ analyzer = RevisionHealthAnalyzer(
+ repo_root=str(repo_path), config=analyzer_config(repo_path, paths)
+ )
+ source = GitRevisionSource(str(repo_path), hunks=False)
+ head = _analyze(analyzer, source.read_working_tree(paths), paths, inputs)
+ base_metrics: dict[str, Any] = {}
+ if against is not None:
+ try:
+ sha = source.commit_sha(against)
+ except ValueError as exc:
+ raise click.ClickException(str(exc)) from exc
+ base_metrics = _analyze(analyzer, source.read(sha, paths), paths, inputs).metrics
+ rows = file_score_deltas(base_metrics, head.metrics, paths, {}, full=True)
+ return LiveScores(rows=rows, head=head, against=against, indexed=inputs.has_history)
+
+
+def analyzer_config(repo_path: Path, paths: list[str]) -> dict | None:
+ """The repo's ``.repowise/health-rules.json`` as analyzer config, or ``None``."""
+ from repowise.core.analysis.health.config import HealthConfig
+
+ health_cfg = HealthConfig.load(repo_path)
+ if not (health_cfg.disabled_biomarkers or health_cfg.rules):
+ return None
+ return health_cfg.to_analyzer_config(paths)
+
+
+def _index_inputs(repo_path: Path) -> IndexInputs:
+ from sqlalchemy.exc import SQLAlchemyError
+
+ async def _do() -> IndexInputs:
+ async with repo_index_session(repo_path) as opened:
+ if opened is None:
+ return IndexInputs()
+ session, repo_id = opened
+ return await load_index_inputs(session, repo_id)
+
+ try:
+ return run_async(_do())
+ except (SQLAlchemyError, OSError):
+ return IndexInputs()
+
+
+def _analyze(
+ analyzer: RevisionHealthAnalyzer,
+ sources: dict[str, bytes],
+ paths: list[str],
+ inputs: IndexInputs,
+) -> RevisionAnalysis:
+ return analyzer.analyze(
+ sources, subject_paths=set(paths), dependents=inputs.dependents, index=inputs
+ )
+
+
+def render_live(scores: LiveScores, fmt: str) -> None:
+ """The live scores as a table, or JSON with ``--format json``."""
+ if fmt == "json":
+ click.echo(json.dumps(live_payload(scores), indent=2))
+ return
+ table = Table(title="Live scores (from disk; history and coverage from the index)")
+ table.add_column("File", style="cyan")
+ if scores.against:
+ table.add_column(f"At {scores.against}", justify="right")
+ table.add_column("Now", justify="right")
+ if scores.against:
+ table.add_column("Change", justify="right")
+ table.add_column("Structure", justify="right")
+ table.add_column("History", justify="right")
+ table.add_column("NLOC", justify="right")
+ for row in scores.rows:
+ table.add_row(*_cells(row, scores))
+ console.print(table)
+ change = score_change(scores.rows)
+ if scores.against and change is not None:
+ console.print(
+ f"Average (weighted by nloc at {scores.against}): {change.base:.2f} -> "
+ f"{change.head:.2f} ({change.head - change.base:+.2f}; structure deduction "
+ f"{change.structure_delta:+.2f})"
+ )
+ if not scores.indexed:
+ console.print(
+ "[dim]No index history: history, coverage and test pairing are left out "
+ "(code shape only).[/dim]"
+ )
+ missing = [r.path for r in scores.rows if r.head_score is None]
+ if missing:
+ console.print(f"[dim]Not scored (missing, or no health support): {', '.join(missing)}[/dim]")
+
+
+def live_payload(scores: LiveScores) -> dict[str, Any]:
+ change = score_change(scores.rows)
+ return {
+ "basis": "live",
+ "history_source": "index" if scores.indexed else "none",
+ "against": scores.against,
+ "files": [
+ {**row.as_dict(), "head_history": _history(scores.head, row.path)}
+ for row in scores.rows
+ ],
+ "score_change": change.as_dict() if change is not None else None,
+ }
+
+
+def _cells(row: FileScoreDelta, scores: LiveScores) -> list[str]:
+ cells = [row.path]
+ if scores.against:
+ cells.append(_num(row.base_score))
+ cells.append(_num(row.head_score))
+ if scores.against:
+ both = row.base_score is not None and row.head_score is not None
+ cells.append(f"{row.head_score - row.base_score:+.2f}" if both else "-")
+ cells += [
+ _num(row.head_structure),
+ _num(_history(scores.head, row.path)),
+ str(row.nloc_head) if row.nloc_head is not None else "-",
+ ]
+ return cells
+
+
+def _history(head: RevisionAnalysis, path: str) -> float | None:
+ metric = head.metrics.get(path)
+ return metric.history_deduction if metric is not None else None
+
+
+def _num(value: float | None) -> str:
+ return f"{value:.2f}" if value is not None else "-"
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 9596b71f0..f3e6fd5e1 100644
--- a/packages/core/src/repowise/core/analysis/change_health/analyzer.py
+++ b/packages/core/src/repowise/core/analysis/change_health/analyzer.py
@@ -10,6 +10,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from datetime import UTC, datetime
from pathlib import PurePosixPath
+from typing import TYPE_CHECKING, Any
from ...ingestion.graph.builder import GraphBuilder
from ...ingestion.models import (
@@ -25,6 +26,9 @@ from ..health import HealthAnalyzer, HealthFileMetricData, HealthFindingData
from ..health.complexity.languages import has_health_dialect
from ..health.source_reader import MappingSourceReader
+if TYPE_CHECKING:
+ from .index_inputs import IndexInputs
+
#: Files above this size are skipped rather than parsed on both sides.
MAX_FILE_BYTES = 1_500_000
@@ -90,6 +94,7 @@ class RevisionHealthAnalyzer:
*,
subject_paths: set[str],
dependents: dict[str, int] | None = None,
+ index: IndexInputs | None = None,
) -> RevisionAnalysis:
"""Analyze *sources*, reporting findings for the whole supplied set.
@@ -102,6 +107,9 @@ class RevisionHealthAnalyzer:
Both sides see only the changed files, so a local count is a slice of
the real one, and an import added between two changed files can carry
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.
"""
result = RevisionAnalysis()
parsed, usable = self._parse(sources, result)
@@ -113,6 +121,7 @@ class RevisionHealthAnalyzer:
repo_root=self.repo_root,
source_reader=MappingSourceReader(usable),
file_dependents=dependents,
+ **(_index_kwargs(index) if index is not None else {}),
)
report = analyzer.analyze(config=self.config, changed_files=set(usable))
result.findings = list(report.findings)
@@ -165,6 +174,15 @@ class RevisionHealthAnalyzer:
return builder.build()
+def _index_kwargs(index: IndexInputs) -> dict[str, Any]:
+ return {
+ "git_meta_map": index.git_meta,
+ "coverage_map": index.coverage,
+ "tested_files": index.tested_files,
+ "stored_blame_findings": index.blame_findings,
+ }
+
+
def _file_info(path: str, language: str, raw: bytes) -> FileInfo:
"""A FileInfo whose ``abs_path`` is the repo-relative key.
diff --git a/packages/core/src/repowise/core/analysis/change_health/file_scores.py b/packages/core/src/repowise/core/analysis/change_health/file_scores.py
index 5d46cb200..79d31d9a6 100644
--- a/packages/core/src/repowise/core/analysis/change_health/file_scores.py
+++ b/packages/core/src/repowise/core/analysis/change_health/file_scores.py
@@ -7,7 +7,7 @@ as ``counts="code_shape"`` reads the index): comparable side to side.
from __future__ import annotations
-from collections.abc import Iterable, Mapping
+from collections.abc import Callable, Iterable, Mapping
from dataclasses import dataclass, replace
from typing import Any
@@ -76,15 +76,20 @@ def file_score_deltas(
rename: Mapping[str, str],
*,
departed: Mapping[str, list[str]] | None = None,
+ full: bool = False,
) -> list[FileScoreDelta]:
"""A row per head path, largest structure move first. *rename* is ``{base: head}``.
*departed* maps each deleted file to where its code moved; it gets a base-only row.
+ *full* keeps each side's whole score, for a pass that read history and coverage.
"""
base_of = {new: old for old, new in rename.items()}
- rows = [_row(path, base.get(base_of.get(path, path)), head.get(path)) for path in paths]
+ score = _full_score if full else _shape_score
+ rows = [
+ _row(path, base.get(base_of.get(path, path)), head.get(path), score) for path in paths
+ ]
rows += [
- replace(_row(path, base.get(path), None), moved_to=tuple(moved))
+ replace(_row(path, base.get(path), None, score), moved_to=tuple(moved))
for path, moved in (departed or {}).items()
]
return sorted(rows, key=lambda r: (-abs(r.structure_change), r.path))
@@ -119,12 +124,15 @@ def score_change(rows: Iterable[FileScoreDelta]) -> ScoreChange | None:
def _row(
- path: str, base: HealthFileMetricData | None, head: HealthFileMetricData | None
+ path: str,
+ base: HealthFileMetricData | None,
+ head: HealthFileMetricData | None,
+ score: Callable[[HealthFileMetricData | None], float | None],
) -> FileScoreDelta:
return FileScoreDelta(
path=path,
- base_score=_shape_score(base),
- head_score=_shape_score(head),
+ base_score=score(base),
+ head_score=score(head),
base_structure=base.structure_deduction if base else None,
head_structure=head.structure_deduction if head else None,
nloc_base=base.nloc if base else None,
@@ -138,5 +146,9 @@ def _shape_score(metric: HealthFileMetricData | None) -> float | None:
return code_shape_score(metric.structure_deduction)
+def _full_score(metric: HealthFileMetricData | None) -> float | None:
+ return metric.score if metric is not None else None
+
+
def _round(value: float | None) -> float | None:
return round(value, 2) if value is not None else None
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
new file mode 100644
index 000000000..dd984c927
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/change_health/index_inputs.py
@@ -0,0 +1,67 @@
+"""What the index knows that a file's bytes do not, for scoring files outside a full pass.
+
+A pass over a few files from disk has no git history, coverage, test pairing or
+blame of its own. The index holds all four from its last run, so a file scored
+with them reads as the next ``repowise update`` would score it.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from ...persistence.models import HealthFileMetric, HealthFinding
+from ..health.history_refresh import BLAME_MARKERS, git_meta_rows_to_map
+from .index_context import index_dependents
+
+
+@dataclass(frozen=True)
+class IndexInputs:
+ """The index's history, coverage, test pairing, blame findings and dependents."""
+
+ 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
+
+ @property
+ def has_history(self) -> bool:
+ return bool(self.git_meta)
+
+
+async def load_index_inputs(session: AsyncSession, repository_id: str) -> IndexInputs:
+ """Every stored input a file's score reads beyond its own bytes."""
+ from ...persistence.crud import get_all_git_metadata, load_coverage_map
+
+ git_rows = await get_all_git_metadata(session, repository_id)
+ tested = await session.execute(
+ select(HealthFileMetric.file_path).where(
+ HealthFileMetric.repository_id == repository_id,
+ HealthFileMetric.has_test_file.is_(True),
+ )
+ )
+ return IndexInputs(
+ git_meta=git_meta_rows_to_map(git_rows.values()),
+ coverage=await load_coverage_map(session, repository_id),
+ tested_files=frozenset(tested.scalars().all()),
+ blame_findings=await _blame_findings(session, repository_id),
+ dependents=await index_dependents(session, repository_id),
+ )
+
+
+async def _blame_findings(session: AsyncSession, repository_id: str) -> dict[str, list[Any]]:
+ """Stored blame-based findings by path, replayed since no blame walk runs here."""
+ rows = await session.execute(
+ select(HealthFinding).where(
+ HealthFinding.repository_id == repository_id,
+ HealthFinding.biomarker_type.in_(BLAME_MARKERS),
+ )
+ )
+ out: dict[str, list[Any]] = {}
+ for finding in rows.scalars():
+ out.setdefault(finding.file_path, []).append(finding)
+ return out
diff --git a/packages/core/src/repowise/core/analysis/change_health/sources.py b/packages/core/src/repowise/core/analysis/change_health/sources.py
index 75e6cbd06..c55d6310f 100644
--- a/packages/core/src/repowise/core/analysis/change_health/sources.py
+++ b/packages/core/src/repowise/core/analysis/change_health/sources.py
@@ -156,7 +156,7 @@ class GitRevisionSource:
return self._resolve_range(*parts)
return self._resolve_commit(revspec)
- def _sha(self, ref: str) -> str:
+ def commit_sha(self, ref: str) -> str:
out = _git(
["rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}"],
self.repo_path,
@@ -167,7 +167,7 @@ class GitRevisionSource:
return out
def _resolve_working_tree(self) -> RevisionPair:
- head = self._sha("HEAD")
+ head = self.commit_sha("HEAD")
# Untracked files are part of the uncommitted change, as change risk
# and the changed lines count them.
if self.hunks:
@@ -188,7 +188,7 @@ class GitRevisionSource:
)
def _resolve_commit(self, ref: str) -> RevisionPair:
- head = self._sha(ref)
+ head = self.commit_sha(ref)
parent = _git(
["rev-parse", "--verify", "--quiet", f"{ref}^{{commit}}^"],
self.repo_path,
@@ -209,8 +209,8 @@ class GitRevisionSource:
)
def _resolve_range(self, base: str, sep: str, head: str) -> RevisionPair:
- base_sha = self._sha(base)
- head_sha = self._sha(head)
+ base_sha = self.commit_sha(base)
+ head_sha = self.commit_sha(head)
if sep == "...":
# Same meaning as change risk and changed lines: no merge-base (a
# shallow clone) is an error, not a silent two-dot diff.
diff --git a/packages/core/src/repowise/core/analysis/health/engine.py b/packages/core/src/repowise/core/analysis/health/engine.py
index 365916644..e761fd2f1 100644
--- a/packages/core/src/repowise/core/analysis/health/engine.py
+++ b/packages/core/src/repowise/core/analysis/health/engine.py
@@ -540,6 +540,7 @@ class HealthAnalyzer:
source_reader: SourceReader | None = None,
stored_blame_findings: dict[str, list[Any]] | None = None,
file_dependents: dict[str, int] | None = None,
+ tested_files: set[str] | frozenset[str] | None = None,
) -> None:
self.graph = graph
self.git_meta_map = git_meta_map or {}
@@ -591,6 +592,8 @@ class HealthAnalyzer:
# 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.
self._file_dependents_override = file_dependents
+ # Files the index records as tested (paired or reached), for a pass holding no tests.
+ self._tested_files = frozenset(tested_files or ())
self._package_roots_cache: set[str] | None = None
self._execution_graph_cache: CallGraphIndex | None = None
self.test_index = RepoTestIndex(self.graph, self.parsed_files, self._execution_graph)
@@ -929,7 +932,8 @@ class HealthAnalyzer:
analyzed_paths = {pf.file_info.path for pf in self.parsed_files}
return FileEvaluator(
self,
- paired_tests=self.test_index.paired(analyzed_paths),
+ paired_tests=self.test_index.paired(analyzed_paths)
+ | (self._tested_files & analyzed_paths),
package_roots=self._package_boundaries(analyzed_paths),
dup_report=dup_report,
run=run,
diff --git a/tests/unit/change_health/test_index_inputs.py b/tests/unit/change_health/test_index_inputs.py
new file mode 100644
index 000000000..49339d3a3
--- /dev/null
+++ b/tests/unit/change_health/test_index_inputs.py
@@ -0,0 +1,29 @@
+"""A few files scored from bytes read the index's history, tests and dependents."""
+
+from __future__ import annotations
+
+from repowise.core.analysis.change_health.analyzer import RevisionHealthAnalyzer
+from repowise.core.analysis.change_health.index_inputs import IndexInputs
+
+from .conftest import python_complex
+
+_PATH = "src/hot.py"
+
+
+def _kinds(index: IndexInputs | None) -> set[str]:
+ run = RevisionHealthAnalyzer().analyze(
+ {_PATH: python_complex("run", 3).encode()},
+ subject_paths={_PATH},
+ dependents={_PATH: 12},
+ index=index,
+ )
+ return {f.biomarker_type for f in run.findings}
+
+
+def test_index_history_reaches_the_score_and_its_test_pairing_holds():
+ history = {_PATH: {"file_path": _PATH, "is_hotspot": True}}
+ assert "untested_hotspot" not in _kinds(None)
+ assert "untested_hotspot" in _kinds(IndexInputs(git_meta=history))
+ # The index pairs a test the pass never saw, so the file is not untested.
+ paired = IndexInputs(git_meta=history, tested_files=frozenset({_PATH}))
+ assert "untested_hotspot" not in _kinds(paired)
diff --git a/tests/unit/cli/test_health_cmd_score_live.py b/tests/unit/cli/test_health_cmd_score_live.py
new file mode 100644
index 000000000..5ae81bb28
--- /dev/null
+++ b/tests/unit/cli/test_health_cmd_score_live.py
@@ -0,0 +1,73 @@
+"""``repowise health --score`` scores files from disk, with or without an index."""
+
+from __future__ import annotations
+
+import json
+import subprocess
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from click.testing import CliRunner
+
+from repowise.cli.commands.health_cmd import command as health_module
+from repowise.cli.main import cli
+
+
+def _complex(name: str, branches: int) -> str:
+ lines = [f"def {name}(value):"]
+ for i in range(branches):
+ lines.append(f" if value % {i + 2} == 0 and value > {i - 1}:")
+ lines.append(f" value = value + {i}")
+ lines.append(" return value")
+ return "\n".join(lines) + "\n"
+
+
+def _git(repo: Path, *args: str) -> None:
+ subprocess.run(["git", "-C", str(repo), *args], check=True, capture_output=True)
+
+
+def _invoke(repo: Path, *args: str):
+ with patch.object(health_module, "resolve_command_target") as resolve:
+ resolve.return_value = SimpleNamespace(
+ is_workspace=False, repo_path=repo, notice=lambda *a, **k: None
+ )
+ return CliRunner().invoke(cli, ["health", *args])
+
+
+def test_score_compares_the_file_on_disk_with_a_revision(tmp_path: Path) -> None:
+ _git(tmp_path, "init", "-q", "-b", "main")
+ _git(tmp_path, "config", "user.email", "[email protected]")
+ _git(tmp_path, "config", "user.name", "T")
+ app = tmp_path / "app.py"
+ app.write_text(_complex("tangle", 26), encoding="utf-8")
+ _git(tmp_path, "add", "-A")
+ _git(tmp_path, "commit", "-q", "-m", "seed")
+ app.write_text(_complex("tangle", 1), encoding="utf-8")
+
+ result = _invoke(tmp_path, "--score", str(app), "--against", "HEAD", "--format", "json")
+
+ assert result.exit_code == 0, result.output
+ payload = json.loads(result.stdout[result.stdout.index("{") :])
+ assert payload["history_source"] == "none"
+ row = payload["files"][0]
+ assert row["path"] == "app.py"
+ assert row["head_score"] > row["base_score"]
+ assert payload["score_change"]["delta"] > 0
+
+
+def test_against_needs_score(tmp_path: Path) -> None:
+ result = _invoke(tmp_path, "--against", "HEAD")
+ assert result.exit_code != 0
+ assert "--against needs --score" in result.output
+
+
+def test_score_refuses_a_view_flag_and_a_path_outside_the_repo(tmp_path: Path) -> None:
+ (tmp_path / "repo").mkdir()
+ repo = tmp_path / "repo"
+ clash = _invoke(repo, "--score", str(repo / "a.py"), "--trend")
+ assert clash.exit_code != 0
+ assert "--score does not combine with --trend" in clash.output
+ outside = _invoke(repo, "--score", str(tmp_path / "elsewhere.py"))
+ assert outside.exit_code != 0
+ assert "outside" in outside.output