Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
perf(mcp): stop sending the same fact twice in a tool response (#2456)
Raghav Chamadiyad79c5d689e62
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/collector.py b/packages/server/src/repowise/server/mcp_server/_budget/collector.pyindex 88e055b57..36f709d49 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/collector.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/collector.py@@ -24,12 +24,13 @@ from repowise.server.mcp_server._references import omission_referencelogger = logging.getLogger(__name__)-#: One sentence, repeated verbatim in every ``_meta.omitted`` block, telling-#: shell-less clients (e.g. Claude Desktop) how to recover without a CLI.-_RESTORE_HINT = (- "Run `repowise expand <ref>` from the repo, or call "- 'get_symbol("repowise#<ref>", query=...) to retrieve the omitted content.'-)+#: Repeated verbatim in every ``_meta.omitted`` block, so it is billed on every+#: response that omits anything. Both recovery routes survive; the prose around+#: them does not. The CLI route is already spelled out with a concrete ref in+#: the omission marker itself (``core/distill/markers.py:18``) — what only this+#: line carries is the ``get_symbol`` route, which is how a shell-less client+#: (e.g. Claude Desktop) recovers.+_RESTORE_HINT = '`repowise expand <ref>`, or get_symbol("repowise#<ref>", query=...)'_DOC_SECTION_RULE = "==== {label} ===="def render_chunk(label: str, value: Any) -> str:diff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.pyindex d52bd762d..2cf6627bc 100644--- a/packages/server/src/repowise/server/mcp_server/_helpers.py+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py@@ -775,3 +775,19 @@ def filter_embedded_path_ids(ids: list, spec: Any) -> list:if not spec:return idsreturn [i for i in ids if not is_excluded(i.split("::", 1)[0], spec)]+++def drop_echoed_target(targets: Any) -> None:+ """Stop paying for a map key a second time inside its own value.++ ``get_risk`` and ``get_context`` both build ``{r["target"]: r for r in+ results}``, so the inner ``target`` is the key by construction. Every+ internal consumer reads it off the card while the response is still being+ assembled; this runs last, and the equality guard means a card that somehow+ disagrees with its key keeps the field rather than losing it silently.+ """+ if not isinstance(targets, dict):+ return+ for key, card in targets.items():+ if isinstance(card, dict) and card.get("target") == key:+ card.pop("target", None)diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.pyindex 8f0bcf9b8..b6b985e2e 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py@@ -53,6 +53,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,_unsupported_repo_all,attach_ignored_arguments,+ drop_echoed_target,resolve_enum_argument,)from repowise.server.mcp_server._meta import build_meta as _build_meta@@ -312,6 +313,7 @@ async def get_context(if cross_repo:target_data["cross_repo"] = cross_repo+ drop_echoed_target(response.get("targets"))attach_ignored_arguments(response, ignored)collector.attach(response)return responsediff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.pyindex 78d44f570..49196350a 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py@@ -704,7 +704,9 @@ async def _resolve_health({"biomarker_type": f.biomarker_type,"severity": f.severity,- "function_name": f.function_name,+ # Absent rather than null on a file-level biomarker, same as the+ # identical field on get_risk's cards.+ **({"function_name": f.function_name} if f.function_name else {}),"impact": round(f.health_impact, 2),"suggestion": suggestion_for(f.biomarker_type),}diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex fa137d764..6c1afc0be 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -592,9 +592,12 @@ def _serialize_finding(f: HealthFinding, repository: str = "default") -> dict[st"biomarker_type": f.biomarker_type,"severity": f.severity,"file_path": f.file_path,- "function_name": f.function_name,- "line_start": f.line_start,- "line_end": f.line_end,+ # A file-level finding has no symbol and no line span. Absent rather+ # than null, on the same rule as ``rank`` below: three null keys on+ # every such row is a bill, not a disclosure.+ **({"function_name": f.function_name} if f.function_name else {}),+ **({"line_start": f.line_start} if f.line_start is not None else {}),+ **({"line_end": f.line_end} if f.line_end is not None else {}),"health_impact": round(f.health_impact, 3),"reason": f.reason,"details": details,diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.pyindex a0bffae1c..78cea3a48 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/directives.py@@ -448,6 +448,35 @@ def _governance_reason(dr: Any, currency: str, conflict_decision_ids: set[str])return None+def _project_recommendation(row: dict[str, Any]) -> dict[str, Any]:+ """Drop what a reader can rebuild from the row it ships beside.++ ``analyze_test_impact`` builds ``source_files`` and ``bases`` by folding+ ``evidence`` (``core/analysis/test_impact.py:256-270``), so on the wire they+ are the same fact twice. ``test_file`` differs from ``test_id`` only for a+ measured row whose id carries a ``::`` selector, and ``source_format`` is+ None on every inferred row. The typed row core hands its own callers is+ untouched; this is the projection get_risk emits.+ """+ out = {k: v for k, v in row.items() if k not in {"repository", "repository_id"}}+ evidence = out.get("evidence")+ if isinstance(evidence, list):+ sources = sorted({e["source_file"] for e in evidence if isinstance(e, dict)})+ if out.get("source_files") == sources:+ out.pop("source_files", None)+ out["evidence"] = [+ {k: v for k, v in e.items() if not (k == "source_format" and v is None)}+ if isinstance(e, dict)+ else e+ for e in evidence+ ]+ if out.get("bases") == [out.get("basis")]:+ out.pop("bases", None)+ if out.get("test_file") in (out.get("test_id"), None):+ out.pop("test_file", None)+ return out++def _build_pr_directive(response: dict,pr_blast_radius: dict,@@ -708,6 +737,35 @@ def _build_pr_directive(preserve_counts=(key in {"missing_tests", "tests_to_run", "test_recommendations"}),)+ # Name the repository once instead of on every recommendation: both values+ # are single arguments to ``analyze_test_impact``, so every row it builds+ # carries the same pair by construction, not by coincidence.+ emitted_recommendations = directive.get("test_recommendations") or []+ if emitted_recommendations:+ first = emitted_recommendations[0]+ directive["test_recommendations_repository"] = first.get("repository")+ directive["test_recommendations_repository_id"] = first.get("repository_id")+ directive["test_recommendations"] = [+ _project_recommendation(row) for row in emitted_recommendations+ ]++ # The same rows also ride under ``pr_blast_radius.test_impact`` as the full+ # population the directive's cap trimmed. Two copies of one row in one+ # payload must not disagree about their shape, so the projection applies to+ # both. ``trimmed_blast`` is a shallow copy of the analyzer's dict, so the+ # nested block is copied before it is rewritten.+ blast = response.get("pr_blast_radius")+ if isinstance(blast, dict):+ blast_impact = blast.get("test_impact")+ if isinstance(blast_impact, dict) and blast_impact.get("recommendations"):+ rows = blast_impact["recommendations"]+ blast["test_impact"] = {+ **blast_impact,+ "recommendations_repository": rows[0].get("repository"),+ "recommendations_repository_id": rows[0].get("repository_id"),+ "recommendations": [_project_recommendation(row) for row in rows],+ }+for key, total in (("will_break_consumers", will_break_total),("missing_cross_repo_cochanges", missing_cross_repo_total),diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.pyindex e8f9d1926..52b31e615 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/enrichment.py@@ -353,11 +353,14 @@ async def _enrich_health(results: list[dict], ctx: Any, repo_id: str) -> None:lst = top_by_file.setdefault(f.file_path, [])if len(lst) >= 3:continue+ # ``function_name`` absent rather than null on a file-level+ # biomarker, matching the coverage fields just below: an absent+ # key and a null one say the same thing, and only one is billed.lst.append({"biomarker_type": f.biomarker_type,"severity": f.severity,- "function_name": f.function_name,+ **({"function_name": f.function_name} if f.function_name else {}),"impact": round(f.health_impact, 2),})diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex 2def737f2..859fdbc30 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -24,6 +24,7 @@ from repowise.server.mcp_server._helpers import (_resolve_repo_context,_unsupported_repo_all,attach_ignored_arguments,+ drop_echoed_target,filter_path_list,filter_rows_by_attr,resolve_enum_argument,@@ -337,6 +338,7 @@ async def get_risk(targets=[*targets, *(changed_files or [])] if targets or changed_files else None,)_drop_opt_in_blocks(response, include_set)+ drop_echoed_target(response.get("targets"))attach_ignored_arguments(response, ignored)collector.attach(response)return responsediff --git a/tests/unit/server/mcp/test_context.py b/tests/unit/server/mcp/test_context.pyindex 2d3ce42b4..d16c678ab 100644--- a/tests/unit/server/mcp/test_context.py+++ b/tests/unit/server/mcp/test_context.py@@ -459,7 +459,8 @@ async def test_batch_isolation_one_target_errors(setup_mcp, monkeypatch):# Failing target carries a per-target error entry (keyed on its target).assert "boom" in targetsassert "error" in targets["boom"]- assert targets["boom"]["target"] == "boom"+ # The map key is the target. The card no longer echoes it back as a field.+ assert "target" not in targets["boom"]@pytest.mark.asynciodiff --git a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py b/tests/unit/server/mcp/test_cross_tool_reference_contracts.pyindex 7ef55b45e..22ffddd6b 100644--- a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py+++ b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py@@ -608,7 +608,9 @@ async def test_canonical_emitter_reference_inventory(resolved = await get_context([ref.value])card = resolved["targets"][ref.value]assert card.get("error") is None, (ref, card)- assert card.get("target") == ref.value+ # The ref resolves because the card is keyed on it; the+ # card no longer echoes the key back as a ``target`` field.+ assert "target" not in cardif ref.kind == "symbol":_assert_symbol_card(resolved,@@ -724,7 +726,8 @@ async def _seed_plan(session, repository_id: str) -> None:def _assert_symbol_card(result: dict, symbol_id: str, path: str, name: str) -> None:card = result["targets"][symbol_id]- assert card["target"] == symbol_id+ # The map key is the target; the card no longer echoes it back as a field.+ assert "target" not in cardassert card["type"] == "symbol"assert card["docs"]["file_path"] == pathassert card["docs"]["name"] == name@@ -809,7 +812,7 @@ async def test_emitted_file_paths_resolve_to_content(reference_repo, path: str)card = result["targets"][path]expected_type = "file" if "." in path.rsplit("/", 1)[-1] else "module"assert card.get("error") is None- assert card["target"] == path+ assert "target" not in cardassert card["type"] == expected_type, (path, card)assert "resolved_to" not in cardassert card.get("docs") or card.get("summary") or card.get("files")diff --git a/tests/unit/server/mcp/test_pr_test_impact_semantics.py b/tests/unit/server/mcp/test_pr_test_impact_semantics.pyindex 8a62dd84d..b49f8de0d 100644--- a/tests/unit/server/mcp/test_pr_test_impact_semantics.py+++ b/tests/unit/server/mcp/test_pr_test_impact_semantics.py@@ -115,7 +115,11 @@ async def test_sealed_pr_payload_is_directive_first_typed_and_count_exact(setup_row["basis"] in {"measured", "inferred"} for row in directive["test_recommendations"])assert all(row["evidence"] for row in directive["test_recommendations"])- assert all(row["repository_id"] == setup_mcp for row in full["recommendations"])+ # Named once for the whole population, not on each row, in both the+ # directive's capped copy and the full one here.+ assert all("repository_id" not in row for row in full["recommendations"])+ assert full["recommendations_repository_id"] == setup_mcp+ assert directive["test_recommendations_repository_id"] == setup_mcpassert relation["dependency"]["source"] in directive["may_break"]assert relation["co_change"]["source"] not in directive["may_break"]assert external["_meta"]["contract_version"]diff --git a/tests/unit/server/mcp/test_response_shape_projections.py b/tests/unit/server/mcp/test_response_shape_projections.pynew file mode 100644index 000000000..a1bcdab24--- /dev/null+++ b/tests/unit/server/mcp/test_response_shape_projections.py@@ -0,0 +1,112 @@+"""Phase 2 response-shape projections: what they drop, and what they must keep.++Each projection here removes a field the reader can rebuild from the response+it ships beside. That is only true while the derivation holds, so every test+below breaks the derivation and asserts the field comes back rather than being+dropped on a coincidence.+"""++from __future__ import annotations++from repowise.server.mcp_server._budget.collector import _RESTORE_HINT+from repowise.server.mcp_server._helpers import drop_echoed_target+from repowise.server.mcp_server.tool_risk.directives import _project_recommendation+++def _row(**over):+ row = {+ "test_id": "tests/test_a.py",+ "test_file": "tests/test_a.py",+ "repository_id": "repo1",+ "repository": "demo",+ "basis": "inferred",+ "bases": ["inferred"],+ "source_files": ["src/a.py"],+ "evidence": [+ {+ "basis": "inferred",+ "source_file": "src/a.py",+ "via": "call-graph",+ "source_format": None,+ }+ ],+ }+ row.update(over)+ return row+++def test_a_derivable_field_is_dropped():+ out = _project_recommendation(_row())+ for gone in ("source_files", "bases", "test_file", "repository", "repository_id"):+ assert gone not in out, gone+ # Everything the dropped fields were folded from is still on the wire.+ assert out["basis"] == "inferred"+ assert [e["source_file"] for e in out["evidence"]] == ["src/a.py"]+ assert "source_format" not in out["evidence"][0]+++def test_source_files_that_is_not_the_fold_of_evidence_survives():+ """The drop is conditional: a list that does not match what ``evidence``+ folds to is a fact of its own and stays."""+ out = _project_recommendation(_row(source_files=["src/a.py", "src/extra.py"]))+ assert out["source_files"] == ["src/a.py", "src/extra.py"]+++def test_a_null_test_file_is_absent_rather_than_null():+ """A measured row whose coverage row named no file: same rule as the+ health findings, absent says what null said."""+ out = _project_recommendation(_row(test_id="tests/test_a.py::one", test_file=None))+ assert "test_file" not in out+++def test_a_test_file_that_is_not_the_test_id_survives():+ """A measured row's id carries a ``::`` selector; its file does not."""+ out = _project_recommendation(+ _row(test_id="tests/test_a.py::test_one", test_file="tests/test_a.py")+ )+ assert out["test_file"] == "tests/test_a.py"+++def test_a_second_basis_survives():+ """``bases`` goes only when it is exactly ``[basis]``."""+ out = _project_recommendation(+ _row(basis="measured", bases=["measured", "inferred"])+ )+ assert out["bases"] == ["measured", "inferred"]+++def test_a_real_source_format_survives():+ out = _project_recommendation(+ _row(+ evidence=[+ {+ "basis": "measured",+ "source_file": "src/a.py",+ "via": "coverage-map",+ "source_format": "lcov",+ }+ ]+ )+ )+ assert out["evidence"][0]["source_format"] == "lcov"+++def test_the_echoed_map_key_is_dropped():+ targets = {"src/a.py": {"target": "src/a.py", "type": "file"}}+ drop_echoed_target(targets)+ assert targets["src/a.py"] == {"type": "file"}+++def test_a_card_that_disagrees_with_its_key_keeps_its_target():+ """The equality guard: a card is never silently stripped of a *different*+ value, because then the key would not carry it."""+ targets = {"alias": {"target": "src/a.py", "type": "file"}}+ drop_echoed_target(targets)+ assert targets["alias"]["target"] == "src/a.py"+++def test_the_restore_hint_still_names_both_recovery_routes():+ """The CLI route is also in the omission marker; the ``get_symbol`` route+ is only here, and it is how a shell-less client recovers."""+ assert "repowise expand" in _RESTORE_HINT+ assert 'get_symbol("repowise#<ref>"' in _RESTORE_HINTdiff --git a/tests/unit/server/mcp/test_risk.py b/tests/unit/server/mcp/test_risk.pyindex 6a5a7f6fb..0f0341f3d 100644--- a/tests/unit/server/mcp/test_risk.py+++ b/tests/unit/server/mcp/test_risk.py@@ -357,8 +357,12 @@ async def test_get_risk_test_compatibility_projection_cannot_contradict_typed_roassert directive["tests_to_run_emitted"] == len(recommendations)assert directive["test_recommendations_emitted"] == len(recommendations)assert all(row["basis"] in {"measured", "inferred"} for row in recommendations)- assert all(row["basis"] in row["bases"] for row in recommendations)- assert all(row["repository_id"] == "repo1" for row in recommendations)+ # ``bases`` rides only when it says something ``basis`` does not; absent+ # means ``[basis]``. The repository is named once for the whole list rather+ # than on every row.+ assert all(row["basis"] in row.get("bases", [row["basis"]]) for row in recommendations)+ assert all("repository_id" not in row for row in recommendations)+ assert directive["test_recommendations_repository_id"] == "repo1"# ---- _classify_risk_type small-team calibration (issue #361) ---------------