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(change-risk): trim redundant MCP response fields (#3152)

Nehant Fopse3daca2333a54
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 96032ac71..7094955ef 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -244,10 +244,12 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`
|-------|---------|
| `directive` | `status` (`review_required`, `review_recommended`, `clear_in_analyzed_scope`, `unknown`), a headline, reasons, next actions |
| `health_delta` | What the change newly made worse. See below |
-| `risk_percentile`, `review_priority`, `classification`, `is_fix` | The change's diff size and spread ranked against the repo's recent commits (`classification` reads `Below-typical`, `Typical` or `Above-typical diff size`). Size, not a verdict: `directive.status` is the verdict |
+| `risk_percentile`, `review_priority`, `classification` | The change's diff size and spread ranked against the repo's recent commits (`classification` reads `Below-typical`, `Typical` or `Above-typical diff size`). Size, not a verdict: `directive.status` is the verdict |
+| `is_fix` | Present only when the change is a bug fix |
+| `exclude_patterns` | Present only when something was excluded: the request's patterns plus `.riskignore` |
| `diff_shape` | One sentence on size and spread; never a danger verdict |
-| `working_tree` | Whether uncommitted work was the subject |
-| `fix_history` | Recency-weighted bug-fix record of the touched files, with `percentile` and `overlap` |
+| `working_tree` | Present only when `revspec` was omitted: whether uncommitted work was scored, or a clean tree fell back to `HEAD` |
+| `fix_history` | Recency-weighted bug-fix record of the touched files, with `percentile` and `overlap`; the raw `density` ships with `include=["diagnostics"]` |
| `impacted_tests` | Tests that execute the changed lines |
| `patch_coverage` | Share of changed executable lines the stored coverage ran |
| `branch_overlap` | Other branches editing the same files |
@@ -258,7 +260,7 @@ Every float is rounded to 4 significant digits. Direct rows' `structural_score`
**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. 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.
-**impacted_tests.** `tests_to_run` names tests the per-test coverage map proves execute the changed lines, capped at ten with `total` and `truncated`. `line_coverage` buckets: `untested_changes`, `stale_test_candidates` (covered lines whose test file is absent from the diff), `covered`, `no_coverage_data`. With no coverage map, `status` is `inferred` when the import graph names test files reaching the change, or `no_map` (run the full suite). `basis` is always present: `measured`, `inferred` or `none`; `tests_to_run_kind` is `test_id` or `test_file`. Build the measured map with `coverage run --contexts=test` and `repowise coverage add`.
+**impacted_tests.** `tests_to_run` names tests the per-test coverage map proves execute the changed lines, capped at ten with `total` and `truncated`. With a coverage map, `map_present` is true and `line_coverage` buckets: `untested_changes`, `stale_test_candidates` (covered lines whose test file is absent from the diff), `covered`, `no_coverage_data`. With no coverage map, `map_present`, `line_coverage` and (unless tests are named) `tests_to_run_kind` are absent, and `status` is `inferred` when the import graph names test files reaching the change, or `no_map` (run the full suite). `basis` is always present: `measured`, `inferred` or `none`; `tests_to_run_kind` is `test_id` or `test_file` whenever `tests_to_run` is filled. Build the measured map with `coverage run --contexts=test` 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. `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.
diff --git a/packages/claude-mod/src/views/review.ts b/packages/claude-mod/src/views/review.ts
index ef87fb3a5..345d16f61 100644
--- a/packages/claude-mod/src/views/review.ts
+++ b/packages/claude-mod/src/views/review.ts
@@ -107,7 +107,7 @@ function isClear(risk: ChangeRisk): boolean {
}
function header(risk: ChangeRisk, changed: number | null): string {
- return `Change review (${reviewScope(risk.ref ?? "working tree", risk.working_tree !== false, changed)})`;
+ return `Change review (${reviewScope(risk.ref ?? "working tree", risk.working_tree === true, changed)})`;
}
/** Each listed finding, then a count of the ones the server left out. */
diff --git a/packages/claude-mod/test/review.test.ts b/packages/claude-mod/test/review.test.ts
index 23ab18207..d38ab4e4c 100644
--- a/packages/claude-mod/test/review.test.ts
+++ b/packages/claude-mod/test/review.test.ts
@@ -198,6 +198,14 @@ describe("review card beneath the answer", () => {
);
});
+ it("a result with an explicit revspec carries no working_tree and gets the commit header", () => {
+ const commit = { ...risk("findings"), ref: "HEAD~1" };
+ delete commit.working_tree;
+ expect(segments({ phase: "done", risk: commit })?.[0]).toBe(
+ "Change review (HEAD~1 (no uncommitted changes), 1 changed file)",
+ );
+ });
+
it("counts findings past the ones the server listed, and resolved ones beside new ones", () => {
const base = risk("findings");
const more = { ...base, health_delta: { ...base.health_delta!, findings_total: 5, resolved: 1 } };
diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
index 224f19ae6..bfbfacefb 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py
@@ -221,8 +221,17 @@ async def get_change_risk(
payload["classification"] = _DIFF_SIZE_LABELS[payload["review_priority"]]
if "diagnostics" not in include_set:
diagnostics = {f: payload.pop(f) for f in _DIAGNOSTIC_FIELDS if f in payload}
+ payload["fix_history"].pop("density", None)
else:
diagnostics = {}
+ # Fields that only repeat the request or say nothing: an empty exclude list,
+ # a working-tree flag after an explicit revspec, a false ``is_fix``.
+ if not payload["exclude_patterns"]:
+ del payload["exclude_patterns"]
+ if revspec is not None:
+ del payload["working_tree"]
+ if not payload["is_fix"]:
+ del payload["is_fix"]
if result.features.nf == 0:
return await _nothing_to_score(ctx, payload["ref"], started)
# Changed lines over the SAME file universe the score counted (its
@@ -752,24 +761,18 @@ def _cross_repo_block(
def _empty_impacted(status: str, summary: str) -> dict[str, Any]:
"""Uniform impacted-tests block for the degraded (no tests to name) paths.
- ``basis`` says which signal named the tests (``none`` here) and
- ``tests_to_run_kind`` what each entry is: a coverage-map ``test_id`` on
- the measured basis, a ``test_file`` on the inferred one.
+ ``basis`` says which signal named the tests (``none`` here). With nothing
+ named there is no ``tests_to_run_kind``, and ``map_present`` and
+ ``line_coverage`` are the measured block's alone: ``status`` and ``basis``
+ already say there is no map. The inferred path sets the kind itself, a
+ ``test_file``; the measured one a coverage-map ``test_id``.
"""
return {
"status": status,
"basis": "none",
- "map_present": False,
"tests_to_run": [],
- "tests_to_run_kind": None,
"total": 0,
"truncated": False,
- "line_coverage": {
- "untested_changes": [],
- "stale_test_candidates": [],
- "covered": [],
- "no_coverage_data": [],
- },
"summary": summary,
}
@@ -1128,11 +1131,11 @@ async def _inferred_impacted(
no coverage report, which is most of them. The dependency graph can narrow
it: a test file that reaches a changed file is worth running first. That is
a candidate list and is labelled one - ``basis`` is ``"inferred"`` and
- ``map_present`` stays False, so nothing here can be read as the line-precise
+ there is no ``map_present``, so nothing here can be read as the line-precise
measured answer.
Deliberately file-level and line-blind. Reaching carries no line
- attribution, so ``line_coverage`` stays empty rather than being filled from
+ attribution, so there is no ``line_coverage`` rather than one filled from
a signal that cannot speak to lines - the distinction this whole block
exists to keep.
"""
diff --git a/plugins/claude-code/hooks/lens/lens.js b/plugins/claude-code/hooks/lens/lens.js
index 86b8c0627..71c3bf894 100644
--- a/plugins/claude-code/hooks/lens/lens.js
+++ b/plugins/claude-code/hooks/lens/lens.js
@@ -3903,7 +3903,7 @@ function isClear(risk) {
return risk.directive?.status === "clear_in_analyzed_scope";
}
function header2(risk, changed) {
- return `Change review (${reviewScope(risk.ref ?? "working tree", risk.working_tree !== false, changed)})`;
+ return `Change review (${reviewScope(risk.ref ?? "working tree", risk.working_tree === true, changed)})`;
}
function findingSegments(hd) {
const rows = hd?.top_findings ?? [];
diff --git a/tests/fixtures/mcp/tool_response_shapes.json b/tests/fixtures/mcp/tool_response_shapes.json
index 7b2513758..254bde686 100644
--- a/tests/fixtures/mcp/tool_response_shapes.json
+++ b/tests/fixtures/mcp/tool_response_shapes.json
@@ -174,10 +174,8 @@
"reasons": [],
"status": null
},
- "exclude_patterns": [],
"fix_history": {
"available": null,
- "density": null,
"files": [
{
"churn": null,
@@ -233,13 +231,6 @@
},
"impacted_tests": {
"basis": null,
- "line_coverage": {
- "covered": [],
- "no_coverage_data": [],
- "stale_test_candidates": [],
- "untested_changes": []
- },
- "map_present": null,
"status": null,
"summary": null,
"tests_to_run": [
@@ -248,11 +239,9 @@
"total": null,
"truncated": null
},
- "is_fix": null,
"ref": null,
"review_priority": null,
- "risk_percentile": null,
- "working_tree": null
+ "risk_percentile": null
},
"get_conformance": {
"_meta": {
diff --git a/tests/unit/server/mcp/test_change_risk.py b/tests/unit/server/mcp/test_change_risk.py
index 64a9d533f..1cecf97c7 100644
--- a/tests/unit/server/mcp/test_change_risk.py
+++ b/tests/unit/server/mcp/test_change_risk.py
@@ -52,7 +52,7 @@ async def test_get_change_risk_honors_riskignore_and_request_filters(tmp_path, m
"HEAD", extensions=["py", "md"], exclude_patterns=["docs/"], baseline=0
)
- assert result["working_tree"] is False
+ assert "working_tree" not in result
# Raw model mechanics are a projection now; the default leads with action.
assert "features" not in result
assert "drivers" not in result
@@ -316,10 +316,10 @@ async def test_impacted_tests_no_map_is_unknown_not_untested(tmp_path, monkeypat
it = result["impacted_tests"]
# Nothing is seeded in the graph either, so neither tier can speak.
assert it["status"] == "no_map"
- assert it["map_present"] is False
+ assert "map_present" not in it
assert it["tests_to_run"] == []
# Honest degradation: no untested claim, a "run the suite" summary instead.
- assert it["line_coverage"]["untested_changes"] == []
+ assert "line_coverage" not in it
assert "run the full suite" in it["summary"]
@@ -365,9 +365,9 @@ async def test_impacted_tests_falls_back_to_the_graph_without_a_map(tmp_path, mo
assert it["status"] == "inferred"
assert it["basis"] == "inferred"
assert it["tests_to_run_kind"] == "test_file"
- assert it["map_present"] is False
+ assert "map_present" not in it
assert it["tests_to_run"] == ["tests/test_round_trips.py"]
- assert it["line_coverage"]["untested_changes"] == []
+ assert "line_coverage" not in it
# Answered by the import tier: there is no call edge here, which is exactly
# when the weaker tier is allowed to speak.
assert "reach the changed files in the graph" in it["summary"]
@@ -425,7 +425,7 @@ async def test_impacted_tests_no_session_factory_degrades_to_no_index(
result = await module.get_change_risk(baseline=0)
assert result["impacted_tests"]["status"] == "no_index"
- assert result["impacted_tests"]["map_present"] is False
+ assert "map_present" not in result["impacted_tests"]
@pytest.mark.asyncio
@@ -443,13 +443,11 @@ async def test_the_two_risk_tools_do_not_share_a_key_for_different_questions() -
assert "missing_tests" not in empty
# Every shape says which signal named the tests, including none.
assert empty["basis"] == "none"
- assert empty["tests_to_run_kind"] is None
- assert set(empty["line_coverage"]) == {
- "untested_changes",
- "stale_test_candidates",
- "covered",
- "no_coverage_data",
- }
+ # Nothing named, so no kind; the measured block alone carries the map
+ # flag and the line buckets.
+ assert "tests_to_run_kind" not in empty
+ assert "map_present" not in empty
+ assert "line_coverage" not in empty
def test_score_measures_names_only_the_supporting_diff_shape_signal() -> None:
@@ -478,3 +476,67 @@ async def test_health_references_on_an_index_without_a_repository_are_skipped(fa
SimpleNamespace(session_factory=factory), SimpleNamespace(findings=[finding])
)
assert finding.health_reference is None
+
+
+async def test_get_change_risk_drops_request_echoes_and_empty_fields(tmp_path, monkeypatch) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _commit(repo, {"src/app.py": "a = 1\n"}, "chore: seed")
+ _commit(repo, {"src/app.py": "a = 1\nb = 2\n"}, "feat: add b")
+
+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
+
+ async def _context(_: str | None) -> SimpleNamespace:
+ return SimpleNamespace(path=str(repo))
+
+ monkeypatch.setattr(module, "_resolve_repo_context", _context)
+ result = await module.get_change_risk("HEAD", baseline=0)
+
+ assert "exclude_patterns" not in result
+ assert "working_tree" not in result
+ assert "is_fix" not in result
+ assert "density" not in result["fix_history"]
+ assert "percentile" in result["fix_history"]
+
+ diagnostics = await module.get_change_risk("HEAD", baseline=0, include=["diagnostics"])
+ assert "density" in diagnostics["fix_history"]
+
+
+async def test_get_change_risk_keeps_working_tree_without_a_revspec(tmp_path, monkeypatch) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _commit(repo, {"src/app.py": "a = 1\n"}, "chore: seed")
+ (repo / "src" / "app.py").write_text("a = 1\nb = 2\n", encoding="utf-8")
+
+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
+
+ async def _context(_: str | None) -> SimpleNamespace:
+ return SimpleNamespace(path=str(repo))
+
+ monkeypatch.setattr(module, "_resolve_repo_context", _context)
+ result = await module.get_change_risk(baseline=0)
+
+ assert result["working_tree"] is True
+
+
+async def test_get_change_risk_keeps_is_fix_when_true(tmp_path, monkeypatch) -> None:
+ repo = tmp_path / "repo"
+ repo.mkdir()
+ _git(["init", "-q"], repo)
+ _commit(repo, {"src/app.py": "a = 1\n"}, "chore: seed")
+ _commit(repo, {"src/app.py": "a = 2\n"}, "fix: wrong value")
+
+ module = importlib.import_module("repowise.server.mcp_server.tool_change_risk")
+
+ async def _context(_: str | None) -> SimpleNamespace:
+ return SimpleNamespace(path=str(repo))
+
+ monkeypatch.setattr(module, "_resolve_repo_context", _context)
+ result = await module.get_change_risk("HEAD", baseline=0)
+
+ assert result["is_fix"] is True
diff --git a/tests/unit/server/mcp/test_tool_change_risk.py b/tests/unit/server/mcp/test_tool_change_risk.py
index 013a0220a..77e00daf0 100644
--- a/tests/unit/server/mcp/test_tool_change_risk.py
+++ b/tests/unit/server/mcp/test_tool_change_risk.py
@@ -251,7 +251,7 @@ async def test_impacted_tests_pass_a_changed_lines_error_through(factory, tmp_pa
assert block["status"] == "unknown"
assert block["summary"] == "Could not read changed lines from git."
assert block["tests_to_run"] == []
- assert block["map_present"] is False
+ assert "map_present" not in block
@pytest.mark.asyncio