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
fix(mcp): emit index_behind and embedder_degraded when false, not only when true (#1449)
Raghav Chamadiya34112e54b8a0
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex 1110d922f..afc2eb873 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -115,10 +115,12 @@ Resolve refs with `repowise expand <ref>` from a shell, or| `index_age_days` | Days since the last `repowise update` || `indexed_commit` | Short (12-char) SHA the index was built against || `live_head` | Only when it differs from `indexed_commit` |-| `stale_warning` | Only on a real signal: HEAD mismatch **that actually changed files**, or age over ~90 days when git is unreachable. Two commits with identical trees (an empty commit, a no-op merge) report `index_behind` instead |-| `embedder`, `embedder_degraded`, `embedder_warning` | Only when the embedder fell back to a mock/degraded mode |+| `stale_warning` | Only on a real signal: HEAD mismatch **that actually changed files**, or age over ~90 days when git is unreachable. Two commits with identical trees (an empty commit, a no-op merge) report `index_behind` with no warning |+| `index_behind` | Whenever the live-vs-indexed comparison ran: `true` if HEAD has moved (alongside `stale_warning` when served content actually changed), `false` if the commits match. Absent means the comparison could not run (no git, or a repo-level tool that serves no file content) |+| `embedder_degraded` | Whenever an embedder is resolved, `true` or `false`. Absent means none was initialised |+| `embedder`, `embedder_warning` | Only when the embedder fell back to a mock/degraded mode |-Silence on these fields means the index is current; don't infer staleness from their absence. `list_repos`, `get_architecture`, `get_blast_radius`, and `get_conformance` don't carry a freshness envelope at all.+Silence on `stale_warning` means the index is current; don't infer staleness from its absence. `list_repos`, `get_architecture`, `get_blast_radius`, and `get_conformance` don't carry a freshness envelope at all.---diff --git a/packages/cli/src/repowise/cli/commands/_tool_adapters.py b/packages/cli/src/repowise/cli/commands/_tool_adapters.pyindex ae444ceaf..c47fc8aee 100644--- a/packages/cli/src/repowise/cli/commands/_tool_adapters.py+++ b/packages/cli/src/repowise/cli/commands/_tool_adapters.py@@ -241,6 +241,11 @@ def index_note(payload: dict) -> dict[str, Any]:for key in ("indexed_commit", "live_head", "index_behind", "index_age_days"):if key in meta:note[key] = meta[key]+ # ``index_behind: false`` exists in ``_meta`` so telemetry can tell "current"+ # apart from "never checked". A projection is read by an agent, not an+ # aggregator, and "the index is not behind" is already what silence says.+ if note.get("index_behind") is False:+ note.pop("index_behind")if meta.get("stale_warning"):note["stale_warning"] = meta["stale_warning"]return notediff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.pyindex 9b29b765b..2bd21a0c0 100644--- a/packages/server/src/repowise/server/mcp_server/_meta.py+++ b/packages/server/src/repowise/server/mcp_server/_meta.py@@ -211,7 +211,7 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = NonePass ``targets`` (the file/symbol/module paths this response actuallyserves) to scope the mismatch signal: when HEAD has moved but none of theserved targets changed between the indexed commit and live HEAD, the- response carries ``index_behind: true`` instead of ``stale_warning``.+ response carries ``index_behind: true`` on its own, with no ``stale_warning``."Silence means current" only trains trust if the warning fires only whenthe served content is actually affected — a repo-wide warning after everyunrelated commit teaches the agent to ignore the field. ``targets=None``@@ -227,11 +227,14 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = None* ``stale_warning`` — only on a real signal (a served target changed,HEAD mismatch with real file changes on a repo-level response, OR veryold with no git)- * ``index_behind`` — HEAD moved but nothing the response serves is- affected: either no served target changed, or the two commits have- identical trees so *no* file changed at all. The second case used to- warn on every repo-level response, which is the loudest possible way to- be wrong about a repo that is completely current.+ * ``index_behind``. The live-vs-indexed comparison ran and reached a+ definitive answer: ``true`` whenever HEAD has moved (with or without an+ accompanying ``stale_warning``, which is the sharper, content-scoped+ signal), ``false`` when the two commits match. Omitted only when the+ comparison could not run at all (no git, no local path, or no indexed+ commit), so absence means "not evaluated", never "false". Emitting the+ false case matters downstream: a field that is only ever present as+ ``true`` makes every consumer-side rate read 100%.Defensive throughout: any missing piece is dropped rather than raised soan upstream change to the Repository model can never poison a tool result.@@ -261,6 +264,11 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = Noneif live_full and indexed_full:if live_full != indexed_full:out["live_head"] = live_full[:12]+ # HEAD moved, so the index *is* behind, true regardless of which+ # sub-branch below fires. Emitted unconditionally here (rather than+ # only on the quiet branches) so consumers can compute a rate:+ # a key that only ever appears as True makes every aggregate 100%.+ out["index_behind"] = Truechanged = (_changed_files_between(local_path, indexed_full, live_full) if local_path else None)@@ -273,20 +281,21 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = None# to stop reading the field. Checked before the targets branch# because it holds for repo-level responses too, which are# exactly the ones that previously always warned.- out["index_behind"] = True+ passelif targets is not None and changed is not None:if targets_hit_by_changes(targets, changed):out["stale_warning"] = ("A file this response serves changed after indexing — ""verify against source or run `repowise update`.")- else:- out["index_behind"] = Trueelse:# The two SHAs are already in ``indexed_commit`` / ``live_head`` —# don't repeat them in prose. Just the directive.out["stale_warning"] = "Index is behind live HEAD — run `repowise update`."- # Match: deliberately emit nothing extra. Silence is the signal.+ else:+ # Match. No prose, since silence is the signal, but the comparison+ # did run and its answer is "not behind", so say so explicitly.+ out["index_behind"] = Falseelif live_full is None and age_days is not None and age_days > _STALE_AGE_FLOOR_DAYS:# No git signal available and the index is genuinely old.out["stale_warning"] = (@@ -348,8 +357,12 @@ def _embedder_meta() -> dict[str, Any]:fell back to mock vectors, every tool response carries ``embedder: "mock"``,``embedder_degraded: True``, and a human-readable ``embedder_warning`` so anagent can detect — programmatically — that semantic search is broken instead- of trusting empty/garbage retrieval. Emits nothing when the embedder is- healthy or unresolved, so healthy responses stay clean.+ of trusting empty/garbage retrieval. A healthy embedder still carries+ ``embedder_degraded: False`` and nothing else, so responses stay quiet while+ the field remains a two-valued signal: telemetry that only ever sees the+ ``true`` case cannot tell a 100% degradation rate from a write-only key.+ Absent entirely means the embedder was never initialised: not evaluated,+ not healthy.A *keyless* index is a different state and gets a different field. Nothingis broken and nothing was misconfigured, so it is not flagged as degraded;@@ -363,11 +376,13 @@ def _embedder_meta() -> dict[str, Any]:status = getattr(_state, "_embedder_status", None)if not status:+ # Embedder never initialised, so there is nothing to report either way.+ # Absence means "not evaluated", distinct from an explicit ``false``.return {}if not status.get("degraded"):if status.get("active") == "mock":- return {"embedder": "mock", "semantic_search": False}- return {}+ return {"embedder": "mock", "embedder_degraded": False, "semantic_search": False}+ return {"embedder_degraded": False}out: dict[str, Any] = {"embedder": status.get("active", "mock"),"embedder_degraded": True,diff --git a/tests/unit/server/mcp/test_embedder_resolution.py b/tests/unit/server/mcp/test_embedder_resolution.pyindex c796156d7..6732b9d34 100644--- a/tests/unit/server/mcp/test_embedder_resolution.py+++ b/tests/unit/server/mcp/test_embedder_resolution.py@@ -270,17 +270,24 @@ def test_build_meta_surfaces_degraded_embedder(monkeypatch):def test_build_meta_clean_when_healthy(monkeypatch):- """A healthy (or unresolved) embedder leaves _meta clean — no noise fields."""+ """A healthy embedder adds no prose, only the explicit not-degraded verdict.++ ``embedder_degraded: False`` is the whole point: the check runs on every+ call, so a key written only when degraded reads as a 100% degradation rate+ to anything that aggregates it.+ """monkeypatch.setattr(_state,"_embedder_status",{"active": "openai", "requested": "openai", "degraded": False},)meta = build_meta(timing_ms=1.0)- assert "embedder_degraded" not in meta+ assert meta["embedder_degraded"] is Falseassert "embedder" not in metaassert "embedder_warning" not in meta- # And when nothing has been resolved at all.++def test_build_meta_omits_degraded_when_embedder_unresolved(monkeypatch):+ """Nothing resolved → the check never ran, so neither value is honest."""monkeypatch.setattr(_state, "_embedder_status", None)assert "embedder_degraded" not in build_meta(timing_ms=1.0)diff --git a/tests/unit/server/mcp/test_keyless_vector_leg.py b/tests/unit/server/mcp/test_keyless_vector_leg.pyindex 64e1b799d..b5d515a30 100644--- a/tests/unit/server/mcp/test_keyless_vector_leg.py+++ b/tests/unit/server/mcp/test_keyless_vector_leg.py@@ -289,7 +289,7 @@ def test_a_keyless_index_reports_no_semantic_search_in_meta() -> None:meta = _meta_for(KeylessEmbedder(), "mock")assert meta["semantic_search"] is False- assert meta.get("embedder_degraded") is not True+ assert meta["embedder_degraded"] is Falsedef test_a_failed_pinned_embedder_reports_degraded_and_names_itself() -> None:@@ -305,7 +305,7 @@ def test_a_real_embedder_is_not_flagged() -> None:meta = _meta_for(_RealisticEmbedder(), "openai")assert "semantic_search" not in meta- assert "embedder_degraded" not in meta+ assert meta["embedder_degraded"] is Falsedef test_cli_semantic_search_says_full_text_answered() -> None:diff --git a/tests/unit/server/mcp/test_meta_freshness.py b/tests/unit/server/mcp/test_meta_freshness.pyindex 5d0ebe648..8da8c16d1 100644--- a/tests/unit/server/mcp/test_meta_freshness.py+++ b/tests/unit/server/mcp/test_meta_freshness.py@@ -3,12 +3,17 @@"Silence means current" only trains agent trust if ``stale_warning`` fireswhen the served content is actually affected. These tests pin the contract:- * HEAD match → silence (no warning, no ``index_behind``).+ * HEAD match → prose silence, and ``index_behind: false``.* HEAD mismatch + a served target changed → ``stale_warning``.* HEAD mismatch + no served target changed → ``index_behind: true`` only.* HEAD mismatch + no targets passed (repo-level tools) → repo-level warning.* git can't diff the two SHAs → fall back to the repo-level warning(fail toward warning, never toward false silence).++``index_behind`` is two-valued wherever the live-vs-indexed comparison ran, and+absent only where it could not run. It used to be written on the true branches+only, which made the key unusable as a rate: every consumer that averaged it saw+100% stale because a false was indistinguishable from a tool that never checks."""from __future__ import annotations@@ -43,16 +48,28 @@ def test_head_match_is_silent(tmp_path, monkeypatch):monkeypatch.setattr(_meta, "_read_live_head", lambda p: _INDEXED)out = _meta.freshness_from_repo(_repo(tmp_path), targets=["a.py"])assert "stale_warning" not in out- assert "index_behind" not in out+ assert out["index_behind"] is Falseassert "live_head" not in out+def test_no_git_signal_omits_index_behind_entirely(tmp_path, monkeypatch):+ """Absence means "not evaluated", which is not the same as false.++ Without a live HEAD the comparison never runs, so claiming ``false`` here+ would report a repo as verified-current on no evidence at all.+ """+ monkeypatch.setattr(_meta, "_read_live_head", lambda p: None)+ out = _meta.freshness_from_repo(_repo(tmp_path), targets=["a.py"])+ assert "index_behind" not in out++def test_served_target_changed_warns(tmp_path, monkeypatch):monkeypatch.setattr(_meta, "_read_live_head", lambda p: _LIVE)_prime(tmp_path, frozenset({"src/a.py"}))out = _meta.freshness_from_repo(_repo(tmp_path), targets=["src/a.py"])assert "stale_warning" in out- assert "index_behind" not in out+ # The sharper signal does not suppress the measurable one.+ assert out["index_behind"] is Truedef test_unaffected_targets_get_index_behind_not_warning(tmp_path, monkeypatch):@@ -101,7 +118,7 @@ def test_no_targets_with_real_changes_still_warns(tmp_path, monkeypatch):_prime(tmp_path, frozenset({"src/a.py"}))out = _meta.freshness_from_repo(_repo(tmp_path), targets=None)assert "stale_warning" in out- assert "index_behind" not in out+ assert out["index_behind"] is Truedef test_empty_commit_over_real_git_is_not_stale(tmp_path):