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(change-risk): a leaner default that keeps every fact an agent acts on (#4221)

Raghav Chamadiya2371ff9af7f8
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index bb30d32db..f5b3dd132 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -270,7 +270,7 @@ Reviews one commit, a `base..head` range, or uncommitted work by comparing the t
| `exclude_patterns` | list[string] | none | Gitignore-style paths to omit; combined with a root `.riskignore` |
| `include_paths` | list[string] or string | all | Gitignore-style paths to keep, as a list or one comma-separated string. Like `exclude_patterns`, it scopes the score, the health delta and every per-file block; `impacted_tests` still selects over the whole change, less only repowise's own output |
| `baseline` | int | `200` | Recent commits sampled for percentile ranking; `0` disables percentiles |
-| `include` | list[string] | none | `findings` (every finding), `diagnostics` (raw score mechanics, plus the delta's analyzer, revisions and limits), `scales` (units), `evidence` (the change's evidence checklist, the same record `repowise changes show` prints) |
+| `include` | list[string] | none | `findings` (every finding), `diagnostics` (raw score mechanics, plus the delta's analyzer, revisions and limits), `scales` (units), `evidence` (the change's evidence checklist, the same record `repowise changes show` prints), `tests` (why each listed test runs and the evidence per changed file) |
| `finding_id` | string | none | Expand one `health_delta` finding |
| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 185d75960..70a3c874e 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -282,13 +282,13 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`
`include=["diagnostics"]` adds `score` (the raw 0 to 10 number), `fallback_band`, `risk_authority`, `score_measures`, `score_unit`, `baseline_sample_size`, `features` and `drivers`, plus `health_delta.analyzer` (analyzer and rules fingerprint, and `context`: `index_dependents` when centrality gates read the index's dependents counts on both sides, `changed_files` with no index), `health_delta.base` and `health_delta.head` (the two resolved revisions) and `health_delta.limits`. `include=["scales"]` adds each field's unit, range and calibration.
-**health_delta.** Both revisions are analysed from their own content, and a finding at head is reported only when the diff explains it. `scope` counts changed, eligible, analysed, skipped and failed files; `status` is `available`, `partial` or `unavailable`, and `partial` is never a clean bill. Documentation and configuration files (Markdown, JSON, YAML, TOML and the other doc or config extensions) are skipped with reason `not_code` and never make a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with a headline saying health analysis does not cover them. Tree-sitter query files (`.scm` under a `queries` directory) and text templates (`.j2`, `.jinja`, `.jinja2`, `.tmpl`, `.tpl`, `.hbs`, `.mustache`, `.ejs`, `.njk`) are skipped with reason `not_analyzable_data`, which also never makes a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with its own headline, since they can still change behaviour. HTML, schema and other files with no health dialect still make a run `partial`. `introduced`, `worsened` and `resolved` are totals; `top_findings` holds the three most actionable, with `findings_total`. Each finding names `dimension`, `biomarker`, `severity`, `path`, `symbol`, head-side `lines`, a `reason`, and an `attribution` (`basis` of `added_lines`, `changed_symbol`, `changed_call_edge`, `new_file`, `file_change`, `context_change` or `unknown`, with a `confidence`). Identity ignores line numbers, so moved code introduces nothing. `inspect` gives the `finding_id` call that expands one; ids are bound to the two revisions. A finding that matches a stored one carries `health_reference` for `get_health(finding_id=...)`. Performance findings carry `opportunity_id` and are ordered by opportunity rank.
+**health_delta.** Both revisions are analysed from their own content, and a finding at head is reported only when the diff explains it. `scope` counts changed, eligible, analysed, skipped and failed files; `status` is `available`, `partial` or `unavailable`, and `partial` is never a clean bill. Documentation and configuration files (Markdown, JSON, YAML, TOML and the other doc or config extensions) are skipped with reason `not_code` and never make a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with a headline saying health analysis does not cover them. Tree-sitter query files (`.scm` under a `queries` directory) and text templates (`.j2`, `.jinja`, `.jinja2`, `.tmpl`, `.tpl`, `.hbs`, `.mustache`, `.ejs`, `.njk`) are skipped with reason `not_analyzable_data`, which also never makes a run `partial`; a change made only of them reads `clear_in_analyzed_scope` with its own headline, since they can still change behaviour. HTML, schema and other files with no health dialect still make a run `partial`. `introduced`, `worsened` and `resolved` are totals; `top_findings` holds the three most actionable, with `findings_total`. Each finding names `dimension`, `biomarker`, `severity`, `path`, `symbol`, head-side `lines`, a `reason`, and an `attribution` (`basis` of `added_lines`, `changed_symbol`, `changed_call_edge`, `new_file`, `file_change`, `context_change` or `unknown`, with a `confidence`). Identity ignores line numbers, so moved code introduces nothing. Pass a finding's `id` as `finding_id` to expand it; with `include=["findings"]` each row carries that call as `inspect`. Ids are bound to the two revisions. A finding that matches a stored one carries `health_reference` for `get_health(finding_id=...)`. Performance findings carry `opportunity_id` and are ordered by opportunity rank.
-`files` lists up to 10 analysed files, largest structure move first, each with `base_score`, `head_score`, `base_structure`, `head_structure` (structure deduction), `nloc_base` and `nloc_head`; a side the file is missing on reads null. `files_total` counts them all. `score_basis` is `structure_only`: each score is 10 minus the structure deduction, the reading `get_health(counts="code_shape")` gives, from two passes that read no git history or coverage. A deleted file has a base-only row, with `moved_to` naming where its code went when it was split. `score_change` averages files scored on both sides, weighted by base nloc so a file that grows while improving keeps its gain: `base`, `head`, `delta` (two decimals), `structure_delta` (the deduction change, which still moves when a file sits on the 1.0 floor) and `files_compared`.
+`files` lists up to 10 analysed files, largest structure move first, each with `base_score`, `head_score`, `nloc_base` and `nloc_head`; a side the file is missing on reads null. `files_total` counts them all. `include=["diagnostics"]` adds `base_structure` and `head_structure` (the structure deduction). `score_basis` is `structure_only`: each score is 10 minus the structure deduction, the reading `get_health(counts="code_shape")` gives, from two passes that read no git history or coverage. A deleted file has a base-only row, with `moved_to` naming where its code went when it was split. `score_change` averages files scored on both sides, weighted by base nloc so a file that grows while improving keeps its gain: `base`, `head`, `delta` (two decimals), `structure_delta` (the deduction change, which still moves when a file sits on the 1.0 floor) and `files_compared`.
-**impacted_tests.** The selection `repowise impacted-tests` makes, over every path the change touched whatever the score's filters, less the repowise output the score also leaves out (the index, and a managed file whose only change is repowise's block or entry), which the CLI still reads when tracked. `status` is `selected` or `run_all` (or `no_index`, `unknown`, `config_invalid`, `timeout`, `busy`, `no_source_line_changes` when nothing was selected, each with `run_all` true; `timeout` means the selection took over 30 seconds and `busy` that one for this repository is still running, and `repowise impacted-tests` gives the answer); `run_all` true means no subset can be vouched for, with up to three `reasons` (`reasons_total` counts them all). `tests_to_run` (capped at ten, `total` and `truncated`) is in `repowise impacted-tests`' [run order](CLI_REFERENCE.md#repowise-impacted-tests-revspec), the `always_run_total` tests that run with every subset last; `why` gives each listed file's reason. With `run_all` the list is what to run first. `tests_to_run_kind` is `test_id` when a coverage node id is listed, else `test_file`. `basis` is `measured` when coverage decided a changed file, `inferred` when only the graph or a rule did, `none` when nothing named a test; `basis_by_file` names the evidence per changed file (`coverage`, `changed-test`, `call-graph`, `import-graph`, `conftest`, `full-run`, `no-tests-needed`, ...). With a coverage map, `map_present` is true and `line_coverage` buckets the scored files' changed lines, matched on the side of the diff the map was measured at (by file when it was measured at neither): `untested_changes`, `stale_test_candidates` (covered lines whose test file is absent from the diff), `covered`, `no_coverage_data`. Build the measured map with `pytest --cov=<package> --cov-context=test` (needs pytest-cov) and `repowise coverage add`.
+**impacted_tests.** The selection `repowise impacted-tests` makes, over every path the change touched whatever the score's filters, less the repowise output the score also leaves out (the index, and a managed file whose only change is repowise's block or entry), which the CLI still reads when tracked. `status` is `selected`, `run_all` or `degraded` (or `no_index`, `unknown`, `config_invalid`, `timeout`, `busy`, `no_source_line_changes` when nothing was selected, each with `run_all` true; `timeout` means the selection took over 30 seconds and `busy` that one for this repository is still running, and `repowise impacted-tests` gives the answer); `run_all` true means no subset can be vouched for, with up to three `reasons` (`reasons_total` counts them all). `degraded` means the index predates files changed outside the change and the selection holds over half the test files; the list stands, `summary` says so, and the directive asks for every test. `tests_to_run` (capped at ten, `total` and `truncated`) is in `repowise impacted-tests`' [run order](CLI_REFERENCE.md#repowise-impacted-tests-revspec), the `always_run_total` tests that run with every subset last. When most of the suite is to run anyway, the list's tail is not stored for recovery. With `run_all` the list is what to run first. `tests_to_run_kind` is `test_id` when a coverage node id is listed, else `test_file`. `basis` is `measured` when coverage decided a changed file, `inferred` when only the graph or a rule did, `none` when nothing named a test. `include=["tests"]` adds `why` (each listed file's reason) and `basis_by_file`, the evidence per changed file (`coverage`, `changed-test`, `call-graph`, `import-graph`, `conftest`, `full-run`, `no-tests-needed`, ...). With a coverage map, `map_present` is true and `line_coverage` buckets the scored files' changed lines, matched on the side of the diff the map was measured at (by file when it was measured at neither): `untested_changes`, `stale_test_candidates` (covered lines whose test file is absent from the diff), `covered`, `no_coverage_data`. Build the measured map with `pytest --cov=<package> --cov-context=test` (needs pytest-cov) and `repowise coverage add`.
-**patch_coverage.** Present when the index stores coverage; the same computation and JSON shape `repowise coverage check --format json` gates on. `patch_coverage_pct` is null when no changed line is executable; files the report never names read `not_in_report`. `scope.freshness` is `stale` when coverage was measured at another commit than the change's head; then a file git shows changed since that commit reads `stale_file`, with no figures, and only untouched files keep theirs. `path_gates` judges the path-scoped gates in `coverage.gates`. Each file row carries `risk` (`fix_pressure`, `dependents`, `hotspot`, `bug_magnet`, `risky`, `reasons`, `basis`) and up to eight `hints` per uncovered range: `range`, `symbol`, up to three `tests` to extend, and a `basis` of `per_test` (measured), `call_graph` or `import_graph` (inferred). Without a `revspec`, it covers everything a push would bring, diffed from the merge-base with the default base branch.
+**patch_coverage.** Present when the index stores coverage. With a gate set and coverage measured at the change's head, it is the same computation and JSON shape `repowise coverage check --format json` gates on. Otherwise it reads `status` (`measured` or `not_measured`), `freshness` and the nonzero `file_counts`, plus the totals and `files` when a changed file was measured; `include=["diagnostics"]` keeps the full shape. `patch_coverage_pct` is null when no changed line is executable; files the report never names read `not_in_report`. `scope.freshness` is `stale` when coverage was measured at another commit than the change's head; then a file git shows changed since that commit reads `stale_file`, with no figures, and only untouched files keep theirs. `path_gates` judges the path-scoped gates in `coverage.gates`. Each file row carries `risk` (`fix_pressure`, `dependents`, `hotspot`, `bug_magnet`, `risky`, `reasons`, `basis`) and up to eight `hints` per uncovered range: `range`, `symbol`, up to three `tests` to extend, and a `basis` of `per_test` (measured), `call_graph` or `import_graph` (inferred). Without a `revspec`, it covers everything a push would bring, diffed from the merge-base with the default base branch.
**fix_history.** `is_fix` applies a fixed keyword rule to the commit subject, not the conventional-commit type. `overlap` adds a diff-shape filter and needs an index: per file, `fix_count`, `overlapping_lines` (labelled `approximate`: past fix ranges are numbered against their own parent commit, so read it as "this area was patched before"), `last_fix_days_ago`, `changed_lines` and `share_of_change`. `concentration` names a file holding at least half the changed lines. The block never names the commit that introduced a bug, and is absent on an index with no fix history.
diff --git a/packages/server/src/repowise/server/mcp_server/_change_health.py b/packages/server/src/repowise/server/mcp_server/_change_health.py
index be70712a0..3085be048 100644
--- a/packages/server/src/repowise/server/mcp_server/_change_health.py
+++ b/packages/server/src/repowise/server/mcp_server/_change_health.py
@@ -68,6 +68,8 @@ def _test_evidence(tests: dict[str, Any] | None) -> CoveringTestEvidence:
run_all = None
if tests.get("run_all"):
run_all = (tests.get("reasons") or [UNAVAILABLE_REASON])[0]
+ elif tests.get("status") == "degraded":
+ run_all = tests["summary"]
return CoveringTestEvidence(
state=state, tests_to_run=to_run, basis=tests.get("basis"), run_all=run_all
)
@@ -164,8 +166,14 @@ def _scope_words(label: str) -> str:
return f" in {label}" if label else ""
-def health_delta_block(delta: ChangeHealthDelta, *, revspec: str | None) -> dict[str, Any]:
- """The compact delta: what got worse, how much was compared, and how sure."""
+def health_delta_block(
+ delta: ChangeHealthDelta, *, revspec: str | None, full: bool = False
+) -> dict[str, Any]:
+ """The compact delta: what got worse, how much was compared, and how sure.
+
+ ``files`` rows leave out the structure deductions their scores already
+ state; *full* keeps them.
+ """
emitted = review_order(delta.findings)[:TOP_FINDINGS_LIMIT]
block: dict[str, Any] = {
"status": delta.status,
@@ -194,7 +202,7 @@ def health_delta_block(delta: ChangeHealthDelta, *, revspec: str | None) -> dict
if delta.moved_to:
block["moved_to"] = dict(list(delta.moved_to.items())[:MOVED_TO_LIMIT])
if delta.files:
- block.update(_file_scores(delta.files))
+ block.update(_file_scores(delta.files, full=full))
if delta.skipped:
block["skipped"] = _skipped(delta.skipped)
if delta.limits:
@@ -202,11 +210,21 @@ def health_delta_block(delta: ChangeHealthDelta, *, revspec: str | None) -> dict
return block
-def _file_scores(rows: list[FileScoreDelta]) -> dict[str, Any]:
+#: ``10 - score`` under ``structure_only``, so a default row leaves them out.
+_DERIVED_FILE_FIELDS = ("base_structure", "head_structure")
+
+
+def _file_scores(rows: list[FileScoreDelta], *, full: bool = False) -> dict[str, Any]:
"""The changed files' scores before and after, and their base-nloc average."""
+ shown = [r.as_dict() for r in rows]
+ if not full:
+ shown = [
+ {k: v for k, v in row.items() if k not in _DERIVED_FILE_FIELDS}
+ for row in shown
+ ]
out: dict[str, Any] = {
"score_basis": SCORE_BASIS,
- "files": [r.as_dict() for r in rows[:FILE_ROWS_LIMIT]],
+ "files": shown[:FILE_ROWS_LIMIT],
"files_total": len(rows),
}
change = score_change(rows)
@@ -215,8 +233,10 @@ def _file_scores(rows: list[FileScoreDelta]) -> dict[str, Any]:
return out
-def finding_row(finding: ChangeFinding, revspec: str | None) -> dict[str, Any]:
- """One surfaced finding, with the exact call that expands it."""
+def finding_row(
+ finding: ChangeFinding, revspec: str | None, *, inspect: bool = False
+) -> dict[str, Any]:
+ """One surfaced finding; *inspect* adds the exact call that expands it."""
row: dict[str, Any] = {
"id": finding.change_finding_id,
"change": finding.change_kind,
@@ -230,8 +250,9 @@ def finding_row(finding: ChangeFinding, revspec: str | None) -> dict[str, Any]:
"confidence": finding.attribution_confidence,
"why": finding.attribution_detail,
},
- "inspect": _call(revspec, extra=f"finding_id={finding.change_finding_id!r}"),
}
+ if inspect:
+ row["inspect"] = _call(revspec, extra=f"finding_id={finding.change_finding_id!r}")
if finding.suggestion and finding.suggestion != finding.reason:
row["suggestion"] = finding.suggestion
if finding.symbol:
@@ -253,7 +274,6 @@ def finding_row(finding: ChangeFinding, revspec: str | None) -> dict[str, Any]:
def finding_detail(finding: ChangeFinding, revspec: str | None) -> dict[str, Any]:
"""The drill-down view: the row plus the evidence behind it."""
row = finding_row(finding, revspec)
- row.pop("inspect", None)
row["evidence"] = finding.evidence
row["health_impact"] = finding.health_impact
return row
diff --git a/packages/server/src/repowise/server/mcp_server/_test_selection.py b/packages/server/src/repowise/server/mcp_server/_test_selection.py
index 4c1d69560..a94cb9fe9 100644
--- a/packages/server/src/repowise/server/mcp_server/_test_selection.py
+++ b/packages/server/src/repowise/server/mcp_server/_test_selection.py
@@ -27,6 +27,9 @@ from repowise.server.mcp_server._budget import OmissionCollector
_REASONS_LIMIT = 3
#: Changed files whose deciding evidence is named.
_BASIS_LIMIT = 10
+#: Share of the suite past which a selection made on a lagging index is
+#: labelled ``degraded``: the files the index has not seen filled it, not the change.
+_DEGRADED_SHARE = 0.5
#: Past this the agent is told to run the CLI instead of waiting. Ceiling: the
#: call walk is per-level SQL; loading call edges once is the upgrade.
SELECTION_TIMEOUT_SECONDS = 30.0
@@ -307,16 +310,26 @@ def selection_block(
*,
limit: int,
label: str,
+ detail: bool = True,
) -> dict[str, Any]:
"""The wire view of *selection*: verdict, reasons, the run list's head and why.
``tests_to_run`` empty with ``run_all`` false means the change needs no
test (documentation, a deleted test); with ``run_all`` true it means nothing
- narrower than the full suite is known.
+ narrower than the full suite is known. ``status`` is ``degraded`` when the
+ index predates files outside the change and the selection holds over half
+ the suite: the list stands and ``summary`` says why. The tail of a list
+ holding most of the suite is not stored when every test is to run anyway.
+ *detail* adds ``why`` and ``basis_by_file``.
"""
run_list = list(selection.tests) # in run order (``test_ranking``)
shown = run_list[:limit]
- if len(run_list) > limit:
+ known = set(selection.known_tests)
+ held = len(known & set(selection.test_files))
+ broad = held > len(known) * _DEGRADED_SHARE
+ degraded = broad and not selection.run_all and bool(result.get("index_gap"))
+ # Most of the suite under a verdict to run all of it: the tail restores nothing to act on.
+ if len(run_list) > limit and not (broad and (selection.run_all or degraded)):
collector.add(
f"{label}.tests_to_run beyond cap={limit} ({len(run_list) - limit} dropped)",
run_list[limit:],
@@ -330,8 +343,9 @@ def selection_block(
)
basis_rows = sorted(selection.basis.items())
always = sum(not selected_by_change(selection, t) for t in selection.test_files)
+ status = "run_all" if selection.run_all else "degraded" if degraded else "selected"
block: dict[str, Any] = {
- "status": "run_all" if selection.run_all else "selected",
+ "status": status,
"run_all": selection.run_all,
"reasons": reasons[:_REASONS_LIMIT],
"reasons_total": len(reasons),
@@ -342,14 +356,22 @@ def selection_block(
"total": len(run_list),
"truncated": len(run_list) > limit,
"always_run_total": always,
- "why": {
- path: selection.why[path]
- for path in dict.fromkeys(t.split("::", 1)[0] for t in shown)
- if path in selection.why
- },
- "basis_by_file": dict(basis_rows[:_BASIS_LIMIT]),
- "summary": _summary(selection, len(run_list), always, limit),
+ "summary": (
+ f"the index predates files changed outside this change, so {held} of "
+ f"{len(known)} test files were selected; run the whole suite, or "
+ "`repowise update` to narrow it."
+ if degraded
+ else _summary(selection, len(run_list), always, limit)
+ ),
+ }
+ if not detail:
+ return block
+ block["why"] = {
+ path: selection.why[path]
+ for path in dict.fromkeys(t.split("::", 1)[0] for t in shown)
+ if path in selection.why
}
+ block["basis_by_file"] = dict(basis_rows[:_BASIS_LIMIT])
if len(basis_rows) > _BASIS_LIMIT:
block["basis_by_file_total"] = len(basis_rows)
collector.add(
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/__init__.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/__init__.py
index 036b4c24b..b8604753f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk/__init__.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/__init__.py
@@ -149,6 +149,7 @@ from repowise.server.mcp_server.tool_change_risk.payload import (
_INCLUDE_BLOCKS,
_SHED_ORDER,
_attach_health,
+ _compact_patch_coverage,
_diff_shape_sentence,
_drill_down,
_include_blocks,
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/impacted.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/impacted.py
index de1b738c9..99f9780e6 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk/impacted.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/impacted.py
@@ -82,6 +82,7 @@ async def _impacted_tests_block(
revspec: str | None = None,
working_tree: bool = False,
owned_excludes: tuple[str, ...] = (),
+ detail: bool = True,
) -> dict[str, Any]:
"""The tests the change needs, decided as ``repowise impacted-tests`` decides them.
@@ -122,7 +123,12 @@ async def _impacted_tests_block(
try:
result, selection, _ = await _pkg.select_change_tests(ctx.path, session_factory, change)
block = selection_block(
- result, selection, collector, limit=_IMPACTED_TESTS_LIMIT, label="impacted_tests"
+ result,
+ selection,
+ collector,
+ limit=_IMPACTED_TESTS_LIMIT,
+ label="impacted_tests",
+ detail=detail,
)
if not result["map_empty"]:
lines = query_lines(change, result["measured_commit"])
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/payload.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/payload.py
index 6278f56cf..e648af5a4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk/payload.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/payload.py
@@ -34,8 +34,9 @@ _SHED_ORDER = response_budget_shed_order("get_change_risk")
#: ``diagnostics`` carries the raw model mechanics; ``findings`` lifts the
#: top-findings cap. Both are projections, recoverable by an exact call.
#: ``evidence`` adds the change's evidence checklist, the record ``repowise
-#: changes show`` and the REST change detail serve.
-_INCLUDE_BLOCKS = frozenset({"scales", "diagnostics", "findings", "evidence"})
+#: changes show`` and the REST change detail serve. ``tests`` adds why each
+#: listed test runs and the evidence that decided each changed file.
+_INCLUDE_BLOCKS = frozenset({"scales", "diagnostics", "findings", "evidence", "tests"})
#: Score mechanics that are identical or near-identical on every call, behind
#: ``include=["diagnostics"]`` so the action-first blocks lead. ``score`` and
@@ -120,20 +121,24 @@ def _attach_health(
payload: dict, delta: Any, revspec: str | None, *, expand: bool, diagnostics: bool = False
) -> None:
"""Put the directive first and the compact delta second."""
- block = _health_delta_block(delta, revspec=revspec)
+ block = _health_delta_block(delta, revspec=revspec, full=diagnostics)
if not diagnostics:
for key in _HEALTH_DIAGNOSTIC_FIELDS:
block.pop(key, None)
if expand:
from repowise.server.mcp_server._change_health import finding_row
- block["top_findings"] = [finding_row(f, revspec) for f in review_order(delta.findings)]
+ block["top_findings"] = [
+ finding_row(f, revspec, inspect=True) for f in review_order(delta.findings)
+ ]
block["findings_emitted"] = len(delta.findings)
block.pop("findings_reduced_reason", None)
block.pop("all_findings_via", None)
directive = _directive(delta, payload.get("impacted_tests"))
if action := _patch_coverage_action(payload.get("patch_coverage")):
directive["next_actions"].append(action)
+ if payload.get("patch_coverage") and not diagnostics:
+ payload["patch_coverage"] = _compact_patch_coverage(payload["patch_coverage"])
ordered = {
"directive": directive,
"health_delta": block,
@@ -144,6 +149,51 @@ def _attach_health(
payload.update(ordered)
+def _gated(block: dict) -> bool:
+ """Whether any coverage gate was set for this change, so the block is a verdict."""
+ nested = (block.get("risky") or {}, block.get("branches") or {})
+ return (
+ block.get("gate") not in (None, "not_set")
+ or bool(block.get("path_gates"))
+ or any(part.get("gate") not in (None, "not_set") for part in nested)
+ )
+
+
+def _compact_patch_coverage(block: dict) -> dict:
+ """The block as status, freshness and counts when no current gate reads it.
+
+ Ungated or stale coverage has no verdict to give, so the gate fields read
+ null or ``not_set`` and every unmeasured file reads zero; what is left is
+ whether anything was measured, how fresh it is, and the measured files.
+ ``include=["diagnostics"]`` keeps the whole block.
+ """
+ scope = block.get("scope") or {}
+ freshness = scope.get("freshness")
+ gated = _gated(block)
+ if gated and freshness == "current":
+ return block
+ counts = {status: n for status, n in (block.get("file_counts") or {}).items() if n}
+ out: dict = {
+ "status": "measured" if counts.get("measured") else "not_measured",
+ "freshness": freshness,
+ }
+ if counts.get("measured"):
+ for key in ("patch_coverage_pct", "covered_line_count", "coverable_line_count", "files"):
+ out[key] = block.get(key)
+ if counts:
+ out["file_counts"] = counts
+ if gated:
+ # A configured gate's verdict (often no_data on stale coverage) stays visible.
+ out["gate"] = block.get("gate")
+ if block.get("path_gates"):
+ out["path_gates"] = block["path_gates"]
+ if (block.get("branches") or {}).get("partial_line_count"):
+ out["branches"] = block["branches"]
+ if errors := scope.get("config_errors"):
+ out["config_errors"] = errors
+ return out
+
+
def _diff_shape_sentence(payload: dict, diagnostics: dict) -> str:
"""One line for what the diff-shape rank says, and what it does not."""
tail = " Mechanics: get_change_risk(include=['diagnostics'])." if diagnostics else ""
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py
index 8b7b43dfd..e59a73a3f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk/tool.py
@@ -94,6 +94,7 @@ async def _attach_change_blocks(
changed_read: tuple[Any, Any],
collector: OmissionCollector,
include_paths: tuple[str, ...] = (),
+ tests_detail: bool = False,
) -> None:
"""Attach the tests, patch coverage, prior fixes and cross-repo blocks, in that order."""
changed, changed_error = changed_read
@@ -105,6 +106,7 @@ async def _attach_change_blocks(
revspec=revspec,
working_tree=result.working_tree,
owned_excludes=result.owned_excludes,
+ detail=tests_detail,
)
patch_changed, patch_error, patch_label, patch_revspec = await _push_change(
str(ctx.path),
@@ -185,7 +187,7 @@ async def get_change_risk(
were skipped. ``risk_percentile`` and ``diff_shape`` measure diff size
only, not danger.
- ``impacted_tests`` is the ``impacted-tests`` selection; read ``run_all``.
+ ``impacted_tests`` is the ``impacted-tests`` selection; read ``status``.
``patch_coverage`` is the share of changed executable lines stored coverage
ran; ``hints`` name tests to extend. ``fix_history`` is the changed files'
bug-fix record, ``overlap`` the past fixes on these exact lines,
@@ -202,7 +204,7 @@ async def get_change_risk(
comma-separated string, e.g. ``"src/api/,src/db/"``. Omit for all.
baseline: Recent commits sampled for percentile ranking; 0 disables it.
include: ``"findings"``, ``"diagnostics"`` (raw mechanics),
- ``"scales"`` (units, tercile) or ``"evidence"`` (checklist).
+ ``"scales"``, ``"evidence"`` or ``"tests"`` (why each runs).
finding_id: Expand one ``health_delta`` finding by its id.
"""
if repo == "all":
@@ -269,6 +271,7 @@ async def get_change_risk(
(changed, changed_error),
collector,
includes,
+ tests_detail="tests" in include_set,
)
independent = await _attach_branch_blocks(
ctx, payload, changed, collector, revspec, finding_id
diff --git a/tests/unit/change_health/test_file_scores.py b/tests/unit/change_health/test_file_scores.py
index 28573d570..fd0c01e6c 100644
--- a/tests/unit/change_health/test_file_scores.py
+++ b/tests/unit/change_health/test_file_scores.py
@@ -18,7 +18,7 @@ def test_a_simplified_file_reports_its_score_on_both_sides(make_repo):
repo.commit("seed", {"app.py": python_complex("tangle", 26), "ok.py": "x = 1\n"})
repo.commit("simplify", {"app.py": python_complex("tangle", 1), "ok.py": "x = 2\n"})
- block = health_delta_block(_delta(repo), revspec="HEAD")
+ block = health_delta_block(_delta(repo), revspec="HEAD", full=True)
assert block["files_total"] == 2
assert block["score_basis"] == "structure_only"
@@ -35,6 +35,19 @@ def test_a_simplified_file_reports_its_score_on_both_sides(make_repo):
assert change["delta"] == round(change["head"] - change["base"], 2)
+def test_by_default_every_scored_file_is_listed_without_its_deductions(make_repo):
+ repo = make_repo()
+ repo.commit("seed", {"app.py": python_complex("tangle", 26), "ok.py": "x = 1\n"})
+ repo.commit("simplify", {"app.py": python_complex("tangle", 1), "ok.py": "x = 2\n"})
+
+ block = health_delta_block(_delta(repo), revspec="HEAD")
+
+ assert [r["path"] for r in block["files"]] == ["app.py", "ok.py"]
+ assert not any("base_structure" in r or "head_structure" in r for r in block["files"])
+ assert block["files_total"] == 2
+ assert block["score_change"]["files_compared"] == 2
+
+
def test_a_new_file_has_no_base_score_and_stays_out_of_the_average(make_repo):
repo = make_repo()
repo.commit("seed", {"ok.py": "x = 1\n"})
diff --git a/tests/unit/change_health/test_mcp_contract.py b/tests/unit/change_health/test_mcp_contract.py
index 8781b03c3..c03bce701 100644
--- a/tests/unit/change_health/test_mcp_contract.py
+++ b/tests/unit/change_health/test_mcp_contract.py
@@ -140,7 +140,10 @@ async def test_a_surfaced_finding_can_be_expanded_by_its_id(tool, make_repo):
listing = await module.get_change_risk("HEAD", baseline=0)
row = listing["health_delta"]["top_findings"][0]
- assert row["inspect"] == f"get_change_risk(revspec='HEAD', finding_id={row['id']!r})"
+ assert "inspect" not in row
+ full = await module.get_change_risk("HEAD", baseline=0, include=["findings"])
+ inspect = full["health_delta"]["top_findings"][0]["inspect"]
+ assert inspect == f"get_change_risk(revspec='HEAD', finding_id={row['id']!r})"
detail = await module.get_change_risk("HEAD", baseline=0, finding_id=row["id"])
diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.py
index aceb07f70..eed84d6f4 100644
--- a/tests/unit/server/mcp/test_change_risk.py
+++ b/tests/unit/server/mcp/test_change_risk.py
@@ -435,7 +435,8 @@ async def test_impacted_tests_falls_back_to_the_graph_without_a_map(tmp_path, mo
return SimpleNamespace(path=str(repo), session_factory=factory)
monkeypatch.setattr(module, "_resolve_repo_context", _context)
- it = (await module.get_change_risk(baseline=0))["impacted_tests"]
+ assert "why" not in (await module.get_change_risk(baseline=0))["impacted_tests"]
+ it = (await module.get_change_risk(baseline=0, include=["tests"]))["impacted_tests"]
assert it["status"] == "selected"
assert it["basis"] == "inferred"
diff --git a/tests/unit/server/mcp/test_change_test_selection.py b/tests/unit/server/mcp/test_change_test_selection.py
index 651a8b1f3..03ad0bb33 100644
--- a/tests/unit/server/mcp/test_change_test_selection.py
+++ b/tests/unit/server/mcp/test_change_test_selection.py
@@ -129,7 +129,7 @@ async def _change_risk(monkeypatch, repo: Path, factory) -> dict:
return SimpleNamespace(path=str(repo), session_factory=factory)
monkeypatch.setattr(module, "_resolve_repo_context", _context)
- return await module.get_change_risk("HEAD", baseline=0)
+ return await module.get_change_risk("HEAD", baseline=0, include=["tests"])
async def _risk_directive(monkeypatch, repo: Path, factory, changed: list[str]) -> dict:
@@ -500,3 +500,48 @@ async def test_a_repeated_selection_is_reused_until_the_tree_or_index_moves(
await session.execute(update(Repository).values(head_commit="moved"))
await session.commit()
assert await _select() is not dirty and len(threads) == 3
+
+
+def _broad(*, run_all: bool = False) -> object:
+ from repowise.core.analysis.test_selection import Selection
+
+ suite = tuple(f"tests/test_{i}.py" for i in range(20))
+ return Selection(
+ run_all=run_all,
+ reasons=("an index-gap reason",),
+ tests=suite[:15],
+ test_files=suite[:15],
+ known_tests=suite,
+ )
+
+
[email protected]("gap", [["src/elsewhere.py"], []])
+def test_a_lagging_index_that_fills_most_of_the_suite_reads_degraded(tmp_path, gap) -> None:
+ from repowise.server.mcp_server._budget import OmissionCollector
+ from repowise.server.mcp_server._test_selection import selection_block
+
+ collector = OmissionCollector("get_change_risk", store_path=tmp_path / "omissions.db")
+ block = selection_block(
+ {"index_gap": gap}, _broad(), collector, limit=10, label="impacted_tests", detail=False
+ )
+
+ assert "why" not in block and "basis_by_file" not in block
+ if gap:
+ assert block["status"] == "degraded" and block["run_all"] is False
+ assert "so 15 of 20 test files were selected; run the whole suite" in block["summary"]
+ # Most of the suite under a run-everything verdict: no tail is stored.
+ assert collector.empty
+ else:
+ assert block["status"] == "selected"
+ assert not collector.empty
+
+
+def test_a_run_all_list_holding_most_of_the_suite_stores_no_tail(tmp_path) -> None:
+ from repowise.server.mcp_server._budget import OmissionCollector
+ from repowise.server.mcp_server._test_selection import selection_block
+
+ collector = OmissionCollector("get_change_risk", store_path=tmp_path / "omissions.db")
+ block = selection_block({}, _broad(run_all=True), collector, limit=10, label="impacted_tests")
+
+ assert block["status"] == "run_all" and block["truncated"] is True
+ assert collector.empty
diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.py
index 98d2717a2..dd10f578d 100644
--- a/tests/unit/server/mcp/test_tool_change_risk.py
+++ b/tests/unit/server/mcp/test_tool_change_risk.py
@@ -900,6 +900,63 @@ def test_the_patch_coverage_action_joins_the_directive(monkeypatch):
)
+def test_a_degraded_selection_asks_for_every_test_with_its_summary(monkeypatch):
+ def _broken(_path):
+ raise RuntimeError("no comparison")
+
+ monkeypatch.setattr(tool, "_delta_service", _broken)
+ delta = tool._compare_health("/repo", None, (), ())
+ summary = "the index predates files changed outside this change, so 15 of 20 test files"
+ payload = {
+ "impacted_tests": {
+ "status": "degraded",
+ "run_all": False,
+ "tests_to_run": ["tests/test_0.py"],
+ "basis": "inferred",
+ "summary": summary,
+ }
+ }
+
+ tool._attach_health(payload, delta, None, expand=False)
+ assert f"Run every test: {summary}" in payload["directive"]["next_actions"]
+
+
+def _full_patch(freshness: str, *, gate: str = "not_set", measured: int = 0) -> dict:
+ return {
+ "patch_coverage_pct": 50.0 if measured else None,
+ "covered_line_count": measured,
+ "coverable_line_count": 2 * measured,
+ "threshold": None,
+ "min_coverable_lines": None,
+ "gate": gate,
+ "file_counts": {"measured": measured, "stale_file": 2, "out_of_scope": 0},
+ "files": [{"file_path": "src/a.py", "status": "measured"}] if measured else [],
+ "scope": {"label": "HEAD", "freshness": freshness, "config_errors": []},
+ "path_gates": [],
+ "risky": None,
+ "project": None,
+ "branches": None,
+ }
+
+
+def test_ungated_or_stale_patch_coverage_reads_as_status_and_freshness():
+ compact = tool._compact_patch_coverage
+ assert compact(_full_patch("stale")) == {
+ "status": "not_measured",
+ "freshness": "stale",
+ "file_counts": {"stale_file": 2},
+ }
+ measured = compact(_full_patch("current", measured=1))
+ assert measured["status"] == "measured"
+ assert measured["files"] == [{"file_path": "src/a.py", "status": "measured"}]
+ assert "gate" not in measured
+ # A gate set on stale coverage keeps its verdict beside the compact fields.
+ assert compact(_full_patch("stale", gate="no_data"))["gate"] == "no_data"
+ # A current gate is a verdict, so the whole block stays.
+ gated = _full_patch("current", gate="fail", measured=1)
+ assert compact(gated) is gated
+
+
@pytest.mark.asyncio
async def test_index_dependents_come_from_the_stored_graph(setup_mcp, factory):
"""Distinct importing files per file, read once for both sides of the delta."""