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
feat(mcp): serve a lean _meta envelope by default (#3017)
Raghav Chamadiya2a88ec2a8374
diff --git a/docs/agent/DISTILL.md b/docs/agent/DISTILL.mdindex 99885ad23..91edc6648 100644--- a/docs/agent/DISTILL.md+++ b/docs/agent/DISTILL.md@@ -205,7 +205,9 @@ the optional `query` parameter searches within the stored content. SeeMCP calls also record a counterfactual saving (the raw file exploration theanswer replaced) as `mcp:<tool>` rows in the same ledger. Truncation is folded-into that figure, so it is never counted twice.+into that figure, so it is never counted twice. The saving is recorded, not+served: `_meta.tokens_saved` and `_meta.replaced_tokens` appear on a response+only with `REPOWISE_MCP_DEBUG_META=1` (and on `get_overview`).---diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.mdindex f570a2ce7..c05c211eb 100644--- a/docs/agent/MCP_TOOLS.md+++ b/docs/agent/MCP_TOOLS.md@@ -92,9 +92,9 @@ Every tool returns a JSON object with a `_meta` envelope. Most fields appear onl| `complete` | Symbol bodies or whole files served verified against the live file. Do not re-read them. || `state` | `degraded`, `partial` or `truncated` when something fired, with reasons. A degraded empty result is a failed read, not an empty repository. || `omitted` | Refs to content cut for size. Restore with `repowise expand <ref>` or `get_symbol("repowise#<ref>")`. |-| `response_budget` | The character ceiling that applied and the size delivered. |+| `response_budget` | The character ceiling that applied and the size delivered. Present when the budget cut something. |-`get_answer` adds a top-level `confidence` (rates the prose) and `retrieval_quality` (rates the evidence). Full envelope: [MCP_RESPONSE_FIELDS.md](../reference/MCP_RESPONSE_FIELDS.md#the-_meta-envelope).+`get_answer` adds a top-level `confidence` (rates the prose) and `retrieval_quality` (rates the evidence). Diagnostics such as `timing_ms` and `contract_version` ride only on `get_overview`; `REPOWISE_MCP_DEBUG_META=1` restores them everywhere. Full envelope: [MCP_RESPONSE_FIELDS.md](../reference/MCP_RESPONSE_FIELDS.md#the-_meta-envelope).### Reversible truncation: `_meta.omitted`diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.mdindex 64442edcb..464b519bb 100644--- a/docs/reference/CLI_REFERENCE.md+++ b/docs/reference/CLI_REFERENCE.md@@ -282,7 +282,7 @@ See [WORKTREES.md](../scale/WORKTREES.md).`state.json:index_scope` is the canonical machine-readable description used by `status --format json`, `/api/repos`, generated agent guidance, and MCP `_meta.index_scope`. It separately records run mode, content provenance (`none`, `template`, or `model`), Git tier, configured commit cap, achieved Git-history coverage, configured/effective file-page caps, eligible/generated/omitted file-page counts, unavailable/skipped analysis, search availability, provider choices, and upgrade state. Older indexes project missing facts as `unknown`/`null`; a configured cap is never reported as achieved coverage and a missing analysis result is never reported as a clean result.-Over MCP, an ordinary tool response carries a **compact projection** of this object rather than all of it: the run mode, content provenance, Git tier, a `status` of `complete`, `partial`, `degraded`, `upgrading` or `unknown`, the names of any degraded analyses, and a `fingerprint` identifying the canonical object. `get_overview` carries the canonical object in full, with the same `fingerprint` beside it, so a held copy can be checked against a later digest without either side resending it. `status` reaches `complete` only when the evidence exists and is clean; an index whose coverage was never recorded reports `unknown`. Set `REPOWISE_MCP_INDEX_SCOPE=full` to put the canonical object on every MCP response, as builds before `_meta.contract_version` 2 did.+Over MCP, an ordinary tool response carries a **compact projection** of this object rather than all of it: the run mode, content provenance, Git tier, a `status` of `complete`, `partial`, `degraded`, `upgrading` or `unknown`, the names of any degraded analyses, and a `fingerprint` identifying the canonical object. `get_overview` carries the canonical object in full, with the same `fingerprint` beside it, so a held copy can be checked against a later digest without either side resending it. `status` reaches `complete` only when the evidence exists and is clean; an index whose coverage was never recorded reports `unknown`. Since `_meta` contract 3 an ordinary response leaves a `complete` digest out, so only a gap rides on it. Set `REPOWISE_MCP_INDEX_SCOPE=full` to put the canonical object on every MCP response, as builds before `_meta.contract_version` 2 did.**Examples:**diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.mdindex 962aee30c..1338dad04 100644--- a/docs/reference/MCP_RESPONSE_FIELDS.md+++ b/docs/reference/MCP_RESPONSE_FIELDS.md@@ -16,10 +16,12 @@ The field dictionary for every repowise MCP tool response. [MCP_TOOLS.md](../ageEvery response carries `_meta`. Fields are present only when they carry a signal, so read absence as "nothing to report", never as an error.+Routine responses carry a lean envelope. `get_overview`, called once per session, keeps the full one: `contract_version`, `timing_ms`, `response_budget` and `completeness` on every call, and the whole `index_scope`. Setting `REPOWISE_MCP_DEBUG_META=1` in the server's environment restores the diagnostic fields on every tool (`contract_version`, `timing_ms`, `response_budget`, `completeness`, `tokens_saved`, `replaced_tokens`) for diagnosis; it is read per call, so no restart is needed.+| Field | When present | Meaning ||-------|--------------|---------|-| `contract_version` | Always | Version of the response contract |-| `timing_ms` | Usually | Tool wall time |+| `contract_version` | `get_overview`, or with `REPOWISE_MCP_DEBUG_META=1` | Version of the response contract (currently 3). It stays the version of record for wire-shape changes even when not emitted |+| `timing_ms` | `get_overview`, or with `REPOWISE_MCP_DEBUG_META=1` | Tool wall time || `hint` | Sometimes | A short follow-up suggestion. On a `get_answer` reply graded `low` while the index is behind HEAD, it says to run `repowise update` and ask again || `cached` | Only when `true` | The response came from cache || `index_age_days` | When a repository is resolved | Days since the last `repowise update` |@@ -27,16 +29,16 @@ Every response carries `_meta`. Fields are present only when they carry a signal| `live_head` | When `.git/HEAD` is readable | Short SHA of the current checkout; equal to `indexed_commit` when current || `index_behind` | When the live-versus-indexed comparison ran | `true` if HEAD moved, `false` if it matches. Absent means the comparison could not run || `stale_warning` | Only on a real signal | HEAD moved and the move changed files this response serves, or the index is very old and git is unreachable. Two commits with identical trees set `index_behind` with no warning |-| `index_scope` | When the index records it | Compact description of how the index was built: run mode, provenance, git tier, whether it is whole |+| `index_scope` | When the index records it and its `status` is not `complete` (whole object on `get_overview`, or everywhere with `REPOWISE_MCP_INDEX_SCOPE=full`) | Compact description of how the index was built: run mode, provenance, git tier, whether it is whole || `embedder_degraded` | When an embedder is resolved | `true` or `false` || `embedder`, `embedder_warning` | Only when the embedder fell back to a mock or degraded mode, or the semantic index on disk could not be opened | Which embedder, and why || `newer_release` | Once per server process | A newer repowise is published; restart the MCP server after upgrading |-| `response_budget` | Always | `limit_chars` (the ceiling), `tier` (`default` or `expanded`), `serialized_chars` (size delivered) |+| `response_budget` | When the budget cut something or could not fit the protected fields (`enforcement_error`); always on `get_overview` | `limit_chars` (the ceiling), `tier` (`default` or `expanded`), `serialized_chars` (size delivered) || `omitted` | When content was cut | `refs`, `tokens`, `restore`. See [Truncation and recovery](#truncation-and-recovery) || `recovery_unavailable` | When the omission store could not be written | Names the storage failure; the cut rows cannot be restored |-| `scope_hint` | `get_answer`, `get_context` | Up to three knowledge-graph layers holding none of the served paths, with file counts: areas the answer did not touch |+| `scope_hint` | `get_answer` | Up to three knowledge-graph layers holding none of the served paths, with file counts: areas the answer did not touch || `complete` | When whole units were served | Symbol bodies (bounds verified against the live file) or whole files. Do not re-read them. Sliced bodies and partial ranges are never counted |-| `completeness` | Always | `capped`, plus `shown` and `total` summed over the collections a reducing pass counted, and `reason` naming the pass that dropped most. It measures what survived reduction, not what share of the repository you hold |+| `completeness` | When something was capped; always on `get_overview` | `capped`, plus `shown` and `total` summed over the collections a reducing pass counted, and `reason` naming the pass that dropped most. It measures what survived reduction, not what share of the repository you hold || `floor` | When a count comes from walking the graph | Names those fields. Their values are lower bounds: an unresolved edge is uncounted, not proven absent || `state` | Only when something fired | `degraded` with `degraded_reasons`, `partial`, `truncated`. A roll-up of the response's own flags |@@ -46,7 +48,7 @@ Every response carries `_meta`. Fields are present only when they carry a signal## Truncation and recovery-Responses fit 24,000 serialized characters by default and 32,000 when the call passes an expansion argument (for most tools, a nonempty `include`; for `get_answer`, `include=["evidence"]`). `_meta.response_budget` reports which ceiling applied.+Responses fit 24,000 serialized characters by default and 32,000 when the call passes an expansion argument (for most tools, a nonempty `include`; for `get_answer`, `include=["evidence"]`). When the budget cut something, `_meta.response_budget` reports which ceiling applied.Content cut to fit is stored in the repo's [omission store](../agent/DISTILL.md#the-omission-store), and `_meta.omitted` says how to get it back:diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2index 36fea85a8..f6d31989a 100644--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2@@ -9,7 +9,7 @@ Machine-readable scope: `{{ data.index_scope | tojson }}`### How to work in this repo- **Trust the index.** `verified: true` and `_meta.complete` mean the bytes were checked against the live tree, so never re-read them. Re-read only what `bounds: "approximate"` or `_meta.stale_warning` names. `confidence` rates the prose, not the evidence: on `low` read the top evidence row or the `candidate_files` the reply names, and run `repowise update` and ask again if `_meta.hint` says the index is behind HEAD. `index_behind: true` alone is informational.-- **A zero carries its basis.** An empty `callers`/`callees`/`used_by` comes with a `*_basis` saying how much of that language's calls the graph resolved, so read it before concluding nothing calls a symbol. `_meta.scope_hint` names the areas the answer did not touch.+- **A zero carries its basis.** An empty `callers`/`callees`/`used_by` comes with a `*_basis` saying how much of that language's calls the graph resolved, so read it before concluding nothing calls a symbol. On `get_answer`, `_meta.scope_hint` names the areas the answer did not touch.- **Pre-edit, not instead-of-edit.** These tools decide *which* files to read and edit. Reading a file before you edit it is correct and expected.- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>`, the same command with its exit code preserved and errors-first output. A `[repowise#<ref>: N lines omitted]` marker is recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.- **Recording a decision** you had to reason out: `repowise decision add --title T --decision D` records it without prompting and prints the id (`--format json` to parse it back). It lands `proposed`, for a person to confirm.diff --git a/packages/core/src/repowise/core/generation/templates/claude_md.j2 b/packages/core/src/repowise/core/generation/templates/claude_md.j2index 11fd8d5a2..7096f5d08 100644--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2@@ -9,7 +9,7 @@ Machine-readable scope: `{{ data.index_scope | tojson }}`### How to work in this repo- **Trust the index.** `verified: true` and `_meta.complete` mean the bytes were checked against the live tree, so never re-read them. Re-read only what `bounds: "approximate"` or `_meta.stale_warning` names. `confidence` rates the prose, not the evidence: on `low` read the top evidence row or the `candidate_files` the reply names, and run `repowise update` and ask again if `_meta.hint` says the index is behind HEAD. `index_behind: true` alone is informational.-- **A zero carries its basis.** An empty `callers`/`callees`/`used_by` comes with a `*_basis` saying how much of that language's calls the graph resolved, so read it before concluding nothing calls a symbol. `_meta.scope_hint` names the areas the answer did not touch.+- **A zero carries its basis.** An empty `callers`/`callees`/`used_by` comes with a `*_basis` saying how much of that language's calls the graph resolved, so read it before concluding nothing calls a symbol. On `get_answer`, `_meta.scope_hint` names the areas the answer did not touch.- **Pre-edit, not instead-of-edit.** These tools decide *which* files to read and edit. Claude Code requires a raw Read of any file you will Edit, and that Read is correct and expected.- **Noisy commands** (tests, builds, `git log`/`diff`, searches, listings): prefer `repowise distill <cmd>` — same command, exit code preserved, errors-first output. A `[repowise#<ref>: N lines omitted]` marker is recoverable via `repowise expand <ref>` (add `-q <regex>` to filter); never re-run the command to see omitted output.- **Recording a decision** you had to reason out: `repowise decision add --title T --decision D` records it without prompting and prints the id (`--format json` to parse it back). It lands `proposed`, for a person to confirm.diff --git a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2 b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2index 578b43c32..1bc7f1399 100644--- a/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2+++ b/packages/core/src/repowise/core/generation/templates/workspace_claude_md.j2@@ -57,7 +57,7 @@ Files that frequently change together across repos — consider reviewing both wThese tools work across all repos in this workspace. Pass `repo="alias"` to scope, `repo="all"` for cross-repo queries, or omit for the default repo.- **Trust the index.** `verified: true` and `_meta.complete` mean the bytes were checked against the live tree, so never re-read them. Re-read only what `bounds: "approximate"` or `_meta.stale_warning` names. `confidence` rates the prose, not the evidence: on `low` read the top evidence row or the `candidate_files` the reply names, and run `repowise update` and ask again if `_meta.hint` says the index is behind HEAD. `index_behind: true` alone is informational.-- **A zero carries its basis.** An empty `callers`/`callees`/`used_by` comes with a `*_basis` saying how much of that language's calls the graph resolved, so read it before concluding nothing calls a symbol. `_meta.scope_hint` names the areas the answer did not touch.+- **A zero carries its basis.** An empty `callers`/`callees`/`used_by` comes with a `*_basis` saying how much of that language's calls the graph resolved, so read it before concluding nothing calls a symbol. On `get_answer`, `_meta.scope_hint` names the areas the answer did not touch.- **Workspace-specific:** `get_overview(repo="all")` returns cross-repo topology (co-changes, package deps, API contracts); `get_risk(changed_files=[...])` picks up cross-repo consumers automatically; `get_blast_radius` / `get_conformance` / `get_architecture` cover cross-repo impact, dependency-rule violations, and coupling.{{ data.tool_table_md }}diff --git a/packages/server/src/repowise/server/mcp_server/__init__.py b/packages/server/src/repowise/server/mcp_server/__init__.pyindex f61e4c1be..0f7bd6322 100644--- a/packages/server/src/repowise/server/mcp_server/__init__.py+++ b/packages/server/src/repowise/server/mcp_server/__init__.py@@ -105,6 +105,7 @@ def tool_middleware(fn: Any) -> Any:It must be here rather than further out, because the estimators readfields a later budget pass is free to drop.6. ``timed`` — stamps ``_meta.timing_ms`` for any tool that did not.+ On a lean envelope it removes the field instead (see ``_meta.full_meta``).7. ``budget`` — accounts for those final middleware fields and rechecks.8. ``record`` — writes the one savings event for the call.@@ -128,7 +129,7 @@ def tool_middleware(fn: Any) -> Any:resolve_response_budget_repo_root,)from repowise.server.mcp_server._failure_shield import shield- from repowise.server.mcp_server._meta import finalize_trust_envelope+ from repowise.server.mcp_server._meta import finalize_trust_envelope, full_metafrom repowise.server.mcp_server._rounding import quantizefrom repowise.server.mcp_server._savings import event as savings_eventfrom repowise.server.mcp_server._savings import instrument@@ -150,7 +151,8 @@ def tool_middleware(fn: Any) -> Any:"""Stamp elapsed time for the tools that do not thread it themselves.A tool that already reports ``timing_ms`` keeps its own number, which- measures its retrieval rather than the middleware around it.+ measures its retrieval rather than the middleware around it. On a lean+ envelope the field is a diagnostic, so it is removed instead."""@wraps(inner)@@ -159,8 +161,11 @@ def tool_middleware(fn: Any) -> Any:result = await inner(*args, **kwargs)if isinstance(result, dict):meta = result.setdefault("_meta", {})- if isinstance(meta, dict) and meta.get("timing_ms") is None:- meta["timing_ms"] = round((time.perf_counter() - started) * 1000, 2)+ if isinstance(meta, dict):+ if not full_meta(fn.__name__):+ meta.pop("timing_ms", None)+ elif meta.get("timing_ms") is None:+ meta["timing_ms"] = round((time.perf_counter() - started) * 1000, 2)return resultreturn wrappeddiff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.pyindex 2ab3ef8b2..0034c0c6e 100644--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py@@ -24,6 +24,7 @@ from repowise.server.mcp_server._budget.budgeter import ()from repowise.server.mcp_server._budget.collector import OmissionCollectorfrom repowise.server.mcp_server._budget.hooks import run_post_enforce, run_post_shed+from repowise.server.mcp_server._meta import full_metaDEFAULT_RESPONSE_CHARS = 24_000EXPANDED_RESPONSE_CHARS = 32_000@@ -628,6 +629,24 @@ def _stamp_completeness(meta["floor"] = sorted(floors)+def _slim_accounting(+ result: dict[str, Any], *, limit: int, tier: str, trimmed: bool+) -> None:+ """Keep the accounting blocks only where they carry news.++ ``completeness`` stays when something was capped and ``response_budget``+ when enforcement shed something or failed; otherwise both restate that the+ whole answer arrived, on every call.+ """+ meta = result["_meta"]+ if not meta.get("completeness", {}).get("capped"):+ meta.pop("completeness", None)+ if trimmed or "enforcement_error" in meta.get("response_budget", {}):+ _stamp_accounting(result, limit=limit, tier=tier)+ else:+ meta.pop("response_budget", None)++async def resolve_response_budget_repo_root(signature: inspect.Signature,args: tuple[Any, ...],@@ -825,7 +844,11 @@ def enforce_response_budget(tier = "expanded" if expanded else "default"if result.get("truncated"):result.setdefault("_meta", {}).setdefault("state", {})["truncated"] = True+ # A block an earlier pass kept means that pass trimmed; the lean envelope+ # keeps it so the outer pass does not hide the inner one's shedding.+ trimmed = "response_budget" in (result.get("_meta") or {})_stamp_accounting(result, limit=limit, tier=tier)+ entry_chars = result["_meta"]["response_budget"]["serialized_chars"]collector = OmissionCollector(tool, repo_root=repo_root)headroom = min(_FINAL_HEADROOM_CHARS, max(100, limit // 4))@@ -858,6 +881,7 @@ def enforce_response_budget(emergency = OmissionCollector(tool, repo_root=repo_root)_emergency_fit(result, contract, emergency, working_limit, requested)emergency.attach(result)+ trimmed = Truerun_post_enforce(tool, result)@@ -870,6 +894,13 @@ def enforce_response_budget("enforcement_error"] = "protected response fields exceed the declared budget"_stamp_accounting(result, limit=limit, tier=tier)+ if not full_meta(tool):+ trimmed = (+ trimmed+ or not collector.empty+ or result["_meta"]["response_budget"]["serialized_chars"] < entry_chars+ )+ _slim_accounting(result, limit=limit, tier=tier, trimmed=trimmed)return resultdiff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.pyindex 0a10d6052..24e6656fd 100644--- a/packages/server/src/repowise/server/mcp_server/_meta.py+++ b/packages/server/src/repowise/server/mcp_server/_meta.py@@ -36,7 +36,27 @@ from repowise.server.mcp_server._rounding import round_float# and its version field are unchanged, so a consumer reading the old shape has# no way to notice from index_scope itself — the envelope version is where a# wire-shape change is announced. REPOWISE_MCP_INDEX_SCOPE=full restores it.-MCP_CONTRACT_VERSION = 2+# 3: the lean envelope. Diagnostics (this version, timing, budget accounting,+# an uncapped completeness block, a complete index_scope digest, savings) leave+# routine responses; get_overview and REPOWISE_MCP_DEBUG_META=1 keep them.+MCP_CONTRACT_VERSION = 3++#: Restores the diagnostic ``_meta`` fields on every response, for diagnosis.+DEBUG_META_ENV = "REPOWISE_MCP_DEBUG_META"++#: Called once per session, so it is where the whole envelope is worth its bytes.+_FULL_META_TOOLS = frozenset({"get_overview"})+++def full_meta(tool: str | None = None) -> bool:+ """Whether *tool*'s response keeps the diagnostic ``_meta`` fields.++ Read per call, like the scope switch, so a client-spawned server picks a+ change up without a restart.+ """+ if tool in _FULL_META_TOOLS:+ return True+ return os.environ.get(DEBUG_META_ENV, "").strip().lower() in {"1", "true", "yes", "on"}# Only warn about age when we have no other signal AND the index is genuinely# old. A short threshold here would nag on every call and train the agent to@@ -301,7 +321,7 @@ def freshness_from_repo(repository: Any | None, targets: list[str] | None = None"""if repository is None:return {}- out: dict[str, Any] = {"contract_version": MCP_CONTRACT_VERSION}+ out: dict[str, Any] = {"contract_version": MCP_CONTRACT_VERSION} if full_meta() else {}updated_at = getattr(repository, "updated_at", None)age_days: int | None = None@@ -385,15 +405,15 @@ def build_meta(serves) to scope ``stale_warning`` to actually-affected content — see:func:`freshness_from_repo`.- ``index_scope`` rides on every response, so it carries the compact- projection: the run mode, the provenance, the git tier, one word for- whether the index is whole, and a fingerprint identifying the canonical- object. See :func:`build_meta_with_full_scope` for the calls that are+ ``index_scope`` carries the compact projection (the run mode, the+ provenance, the git tier, one word for whether the index is whole, and a+ fingerprint identifying the canonical object), and only when that word is+ not ``complete``. See :func:`build_meta_with_full_scope` for the calls that areworth the whole thing.Stable shape:{- "timing_ms": float, # tool wall-time (omitted if None)+ "timing_ms": float, # tool wall-time (REPOWISE_MCP_DEBUG_META only)"hint": str, # short follow-up suggestion (omitted if None)"cached": bool, # only included when True"index_age_days": int, # days since last `repowise update`@@ -402,8 +422,9 @@ def build_meta(...extras}"""- out: dict[str, Any] = {"contract_version": MCP_CONTRACT_VERSION}- if timing_ms is not None:+ full = full_meta()+ out: dict[str, Any] = {"contract_version": MCP_CONTRACT_VERSION} if full else {}+ if timing_ms is not None and full:# Through the shared quantizer, not ``round(..., 2)``. A wall-clock# duration is a float like any other on this wire, and two decimal# places is not the same rule the rest of the payload follows: a@@ -422,7 +443,10 @@ def build_meta(if repository is not None:out.update(freshness_from_repo(repository, targets=targets))scope = index_scope_for_response(getattr(repository, "local_path", None))- if scope is not None:+ # A complete digest restates the default; only a gap is news.+ if scope is not None and (+ full or _canonical_scope_requested() or scope.get("status") != "complete"+ ):out["index_scope"] = scopeout.update(_embedder_meta())out.update(_release_meta())@@ -439,7 +463,7 @@ def build_meta_with_full_scope(**kwargs: Any) -> dict[str, Any]:every caller must read past to learn it does not apply to them belongsbeside the one caller it does."""- meta = build_meta(**kwargs)+ meta = {"contract_version": MCP_CONTRACT_VERSION, **build_meta(**kwargs)}repository = kwargs.get("repository")if repository is not None:scope = read_index_scope(getattr(repository, "local_path", None))@@ -473,7 +497,8 @@ def finalize_trust_envelope(result: Any, *, evidence_kind: str | None = None) ->raw_meta = result.get("_meta")meta = raw_meta if isinstance(raw_meta, dict) else {}result["_meta"] = meta- meta.setdefault("contract_version", MCP_CONTRACT_VERSION)+ if full_meta():+ meta.setdefault("contract_version", MCP_CONTRACT_VERSION)if evidence_kind:meta.setdefault("evidence_kind", evidence_kind)if evidence_kind == "structural":diff --git a/packages/server/src/repowise/server/mcp_server/_savings/wrapper.py b/packages/server/src/repowise/server/mcp_server/_savings/wrapper.pyindex bc924e49b..72731ab29 100644--- a/packages/server/src/repowise/server/mcp_server/_savings/wrapper.py+++ b/packages/server/src/repowise/server/mcp_server/_savings/wrapper.py@@ -3,9 +3,9 @@:func:`instrument` wraps a registered MCP tool so that every call, after thetool produces its (already budget-trimmed) response, measures the deliveredtoken count, derives the counterfactual raw-exploration cost it replaced, and-records a ``mcp:<tool>`` row in the unified savings ledger. It optionally stamps-``_meta.tokens_saved`` / ``_meta.replaced_tokens`` onto the response for-transparency.+records a ``mcp:<tool>`` row in the unified savings ledger. On the responses that+keep the full envelope (see ``_meta.full_meta``) it also stamps+``_meta.tokens_saved`` / ``_meta.replaced_tokens`` for transparency.Two non-negotiables:@@ -34,6 +34,8 @@ import loggingfrom collections.abc import Callablefrom typing import Any+from repowise.server.mcp_server._meta import full_meta+from . import counterfactual, interactionfrom .recorder import record_mcp_dead_end, record_mcp_saving@@ -152,8 +154,8 @@ def _emit_telemetry(tool: str, result: Any, duration_ms: int) -> None:telemetry.record_event("mcp_tool_call", _telemetry_properties(tool, result, duration_ms))#: ``_meta`` key a tool sets to declare its own counterfactual (see-#: :func:`declare_replaced`). The wrapper reads and then leaves it in place as a-#: transparency annotation.+#: :func:`declare_replaced`). The wrapper reads it and, on a lean envelope,+#: removes it, so it never reaches the agent._DECLARED_KEY = "replaced_tokens"@@ -172,14 +174,14 @@ def declare_replaced(result: dict[str, Any], tokens: int) -> None:meta[_DECLARED_KEY] = tokens-def _declared_tokens(result: Any) -> int | None:+def _declared_tokens(tool: str, result: Any) -> int | None:"""Return a tool-declared counterfactual from ``_meta``, if present."""if not isinstance(result, dict):return Nonemeta = result.get("_meta")if not isinstance(meta, dict):return None- value = meta.get(_DECLARED_KEY)+ value = meta.get(_DECLARED_KEY) if full_meta(tool) else meta.pop(_DECLARED_KEY, None)return value if isinstance(value, int) and value > 0 else None@@ -220,7 +222,7 @@ def _observe_baseline(tool: str, result: Any) -> None:right number -- the old one disagreed with the telemetry's size for thesame call -- but it is a change, not a no-op."""- declared = _declared_tokens(result)+ declared = _declared_tokens(tool, result)replaced = (declared if declared is not None else counterfactual.replaced_tokens_for(tool, result))@@ -243,7 +245,8 @@ def _observe_baseline(tool: str, result: Any) -> None:from repowise.server.mcp_server import _staterepo_root = getattr(_state, "_repo_path", None)- if record_mcp_saving(repo_root, tool, replaced, delivered) and isinstance(result, dict):+ recorded = record_mcp_saving(repo_root, tool, replaced, delivered)+ if recorded and isinstance(result, dict) and full_meta(tool):meta = result.setdefault("_meta", {})if isinstance(meta, dict):# Stamped before the outer budget runs, so these bytes are budgeteddiff --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 7b2c059e4..6e0b0961e 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@@ -88,27 +88,6 @@ _INCLUDE_BLOCKS = frozenset()-async def _scope_hint(session: Any, repository: Any, raw_results: list[Any]) -> str | None:- """One sentence naming index layers that hold none of the files served here."""- try:- from repowise.server.mcp_server._index_state import index_state_key- from repowise.server.mcp_server._scope import unrelated_scope_hint-- served = [- r.get("path") or str(r.get("target") or "").split("::", 1)[0]- for r in raw_results- if isinstance(r, dict)- ]- return await unrelated_scope_hint(- session,- repository.id,- served,- cache_key=f"{repository.id}:{index_state_key(repository)}",- )- except Exception:- return None--@mcp.tool(surface_order=20,artifact_type="context",@@ -224,10 +203,6 @@ async def get_context(collector=collector,)- # repo="all" already returned above, so ctx here is always one repo.- # Computed on the open session: never open a second one for this.- scope_hint = await _scope_hint(session, repository, raw_results)-results: list[dict[str, Any]] = []for t, r in zip(targets, raw_results, strict=True):if isinstance(r, BaseException) and not isinstance(r, Exception):@@ -259,8 +234,6 @@ async def get_context(targets=targets,),}- if scope_hint:- response["_meta"]["scope_hint"] = scope_hint# A "raw" skeleton is the file's own source served untouched; the# signatures and smart modes elide bodies, so they are not whole files.whole_files = sum(diff --git a/tests/integration/mcp/test_instrument.py b/tests/integration/mcp/test_instrument.pyindex b90b934a7..0d57a9409 100644--- a/tests/integration/mcp/test_instrument.py+++ b/tests/integration/mcp/test_instrument.py@@ -61,22 +61,34 @@ async def test_wrapped_tool_records_and_preserves_output(repo: Path) -> None:wrapped = instrument(get_context)out = await wrapped(["a.py"])- # User-facing payload unchanged; only additive _meta savings fields appear.- assert out["targets"] == expected["targets"]- assert out["_meta"]["timing_ms"] == 1.0- assert out["_meta"]["replaced_tokens"] == 4000- assert out["_meta"]["tokens_saved"] > 0+ # User-facing payload unchanged; the saving is recorded, not served.+ assert out == expectedrow = _ledger(repo)["mcp:get_context"]assert row["raw_tokens"] == 4000assert row["events"] == 1+async def test_debug_meta_serves_the_savings_fields(+ repo: Path, monkeypatch: pytest.MonkeyPatch+) -> None:+ from repowise.server.mcp_server._meta import DEBUG_META_ENV++ monkeypatch.setenv(DEBUG_META_ENV, "1")+ out = await instrument(get_context)(["a.py"])++ assert out["_meta"]["timing_ms"] == 1.0+ assert out["_meta"]["replaced_tokens"] == 4000+ assert out["_meta"]["tokens_saved"] > 0++@pytest.mark.asyncioasync def test_declared_counterfactual_wins(repo: Path) -> None:wrapped = instrument(get_symbol)out = await wrapped("a.py::f")- assert out["_meta"]["replaced_tokens"] == 5000+ # Read by the wrapper, then removed so it never reaches the agent.+ assert "replaced_tokens" not in out["_meta"]assert _ledger(repo)["mcp:get_symbol"]["raw_tokens"] == 5000diff --git a/tests/integration/mcp/test_savings_event.py b/tests/integration/mcp/test_savings_event.pyindex 3489f1d0e..e9ef82cc8 100644--- a/tests/integration/mcp/test_savings_event.py+++ b/tests/integration/mcp/test_savings_event.py@@ -16,6 +16,7 @@ import pytestfrom repowise.core.distill.store import OmissionStorefrom repowise.server.mcp_server import _state, tool_middleware+from repowise.server.mcp_server._meta import DEBUG_META_ENVfrom repowise.server.mcp_server._savings import declare_replaced@@ -92,7 +93,9 @@ async def test_a_counterfactual_is_inferred_and_the_drop_is_not_added_twice(@pytest.mark.asyncio-async def test_delivered_is_measured_after_the_outermost_budget(repo: Path) -> None:+async def test_delivered_is_measured_after_the_outermost_budget(+ repo: Path, monkeypatch: pytest.MonkeyPatch+) -> None:"""The ordering fix, stated as a number.``instrument`` sits five layers deep. After it, ``timed`` stamps ``_meta``@@ -107,6 +110,8 @@ async def test_delivered_is_measured_after_the_outermost_budget(repo: Path) -> N"_meta": {},}+ # The full envelope, so the fields stamped outside instrument are present.+ monkeypatch.setenv(DEBUG_META_ENV, "1")out = await tool_middleware(get_context)(["a.py"])event = _events(repo)[0]diff --git a/tests/unit/server/mcp/conftest.py b/tests/unit/server/mcp/conftest.pyindex b4a659eaa..3c644468c 100644--- a/tests/unit/server/mcp/conftest.py+++ b/tests/unit/server/mcp/conftest.py@@ -688,6 +688,14 @@ async def health_data(session: AsyncSession, populated_db: str) -> str:return rid+def debug_meta(monkeypatch):+ """Restore the diagnostic ``_meta`` fields, for tests of the accounting itself."""+ from repowise.server.mcp_server._meta import DEBUG_META_ENV++ monkeypatch.setenv(DEBUG_META_ENV, "1")++@pytest.fixture(autouse=True)def _no_savings_writes_outside_a_test_repo(monkeypatch):"""Keep a tool call in these tests from banking a saving in the real repo.diff --git a/tests/unit/server/mcp/test_context.py b/tests/unit/server/mcp/test_context.pyindex b87e17069..5f18f5f4c 100644--- a/tests/unit/server/mcp/test_context.py+++ b/tests/unit/server/mcp/test_context.py@@ -861,8 +861,10 @@ async def test_get_context_meta_envelope(setup_mcp):result = await get_context(["src/payments/charge.py"])assert "_meta" in resultmeta = result["_meta"]- assert "contract_version" in meta- assert "timing_ms" in meta+ assert "index_age_days" in meta+ # Diagnostics stay off a routine response.+ assert "contract_version" not in meta+ assert "timing_ms" not in meta# hint was dead/always None and has been removed; no empty or spurious hint fieldassert "hint" not in metadiff --git a/tests/unit/server/mcp/test_health_semantics_matrix.py b/tests/unit/server/mcp/test_health_semantics_matrix.pyindex 305e059cd..d9a4a97fa 100644--- a/tests/unit/server/mcp/test_health_semantics_matrix.py+++ b/tests/unit/server/mcp/test_health_semantics_matrix.py@@ -14,6 +14,9 @@ from typing import Any, Literalimport pytest+# These tests read the accounting the lean envelope leaves out by default.+pytestmark = pytest.mark.usefixtures("debug_meta")+PlanReason = Literal["no_applicable_findings","plan_analysis_indeterminate",diff --git a/tests/unit/server/mcp/test_index_scope_projection.py b/tests/unit/server/mcp/test_index_scope_projection.pyindex 7057ccd17..d85db8415 100644--- a/tests/unit/server/mcp/test_index_scope_projection.py+++ b/tests/unit/server/mcp/test_index_scope_projection.py@@ -160,6 +160,17 @@ def test_a_routine_response_carries_the_digest(tmp_path: Path) -> None:assert "git_history_coverage" not in out["index_scope"]+def test_a_complete_index_leaves_the_digest_off(tmp_path: Path) -> None:+ """``complete`` restates the default, so only a gap rides on a response."""+ whole = {+ **_FULL_STATE,+ "index_scope": {**_FULL_STATE["index_scope"], "file_pages": _WHOLE_PAGES},+ }+ out = _meta.build_meta(repository=_write_state(tmp_path, whole))++ assert "index_scope" not in out++def test_an_orientation_call_carries_the_whole_scope(tmp_path: Path) -> None:out = _meta.build_meta_with_full_scope(repository=_write_state(tmp_path, _FULL_STATE)diff --git a/tests/unit/server/mcp/test_lean_meta.py b/tests/unit/server/mcp/test_lean_meta.pynew file mode 100644index 000000000..006d09d47--- /dev/null+++ b/tests/unit/server/mcp/test_lean_meta.py@@ -0,0 +1,65 @@+"""The budget layer's accounting rides on a response only when it carries news."""++from __future__ import annotations++import inspect+import json+from typing import Any++import pytest++from repowise.server.mcp_server import tool_middleware+from repowise.server.mcp_server._budget import enforce_response_budget+from repowise.server.mcp_server._meta import DEBUG_META_ENV+++def get_why(query: str | None = None) -> None:+ pass+++def _enforce(result: dict[str, Any]) -> dict[str, Any]:+ return enforce_response_budget(+ "get_why", result, signature=inspect.signature(get_why), args=(), kwargs={}+ )+++def _oversize() -> dict[str, Any]:+ return {+ "mode": "search",+ "decisions": [{"id": i, "body": "x" * 2000} for i in range(60)],+ "_meta": {},+ }+++def test_an_untouched_response_carries_no_accounting() -> None:+ result = _enforce({"mode": "search", "decisions": [], "_meta": {}})++ assert "response_budget" not in result["_meta"]+ assert "completeness" not in result["_meta"]+++def test_a_trimmed_response_carries_exact_accounting() -> None:+ result = _enforce(_oversize())++ budget = result["_meta"]["response_budget"]+ assert budget["serialized_chars"] == len(json.dumps(result, separators=(",", ":")))+ assert result["_meta"]["completeness"]["capped"] is True+++async def test_the_outer_pass_keeps_what_the_inner_pass_trimmed() -> None:+ async def get_why(query: str | None = None) -> dict[str, Any]:+ return _oversize()++ result = await tool_middleware(get_why)("why?")++ budget = result["_meta"]["response_budget"]+ assert budget["serialized_chars"] <= budget["limit_chars"]+++def test_debug_meta_restores_the_accounting(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv(DEBUG_META_ENV, "1")++ result = _enforce({"mode": "search", "decisions": [], "_meta": {}})++ assert result["_meta"]["completeness"] == {"capped": False}+ assert "serialized_chars" in result["_meta"]["response_budget"]diff --git a/tests/unit/server/mcp/test_pr_test_impact_semantics.py b/tests/unit/server/mcp/test_pr_test_impact_semantics.pyindex b49f8de0d..eceeb3521 100644--- a/tests/unit/server/mcp/test_pr_test_impact_semantics.py+++ b/tests/unit/server/mcp/test_pr_test_impact_semantics.py@@ -122,4 +122,5 @@ async def test_sealed_pr_payload_is_directive_first_typed_and_count_exact(setup_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"]+ # A routine response serves the lean envelope.+ assert "contract_version" not in external["_meta"]diff --git a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.pyindex 3100f123a..03ad52e7d 100644--- a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py+++ b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py@@ -29,6 +29,9 @@ from repowise.server.mcp_server._budget import (EXPANDED_RESPONSE_CHARS,)+# These tests read the accounting the lean envelope leaves out by default.+pytestmark = pytest.mark.usefixtures("debug_meta")+_NOW = datetime(2026, 8, 26, tzinfo=UTC)diff --git a/tests/unit/server/mcp/test_requested_projection_priority.py b/tests/unit/server/mcp/test_requested_projection_priority.pyindex 56f57dc32..28be4607b 100644--- a/tests/unit/server/mcp/test_requested_projection_priority.py+++ b/tests/unit/server/mcp/test_requested_projection_priority.py@@ -16,6 +16,9 @@ from repowise.server.mcp_server._budget.contracts import (_requested_shed_keys,)+# These tests read the accounting the lean envelope leaves out by default.+pytestmark = pytest.mark.usefixtures("debug_meta")+def _overview_signature() -> inspect.Signature:def get_overview(repo: str | None = None, include: list[str] | None = None): ...diff --git a/tests/unit/server/mcp/test_response_budget_contracts.py b/tests/unit/server/mcp/test_response_budget_contracts.pyindex 27d984396..581184256 100644--- a/tests/unit/server/mcp/test_response_budget_contracts.py+++ b/tests/unit/server/mcp/test_response_budget_contracts.py@@ -18,6 +18,9 @@ from repowise.server.mcp_server._budget import (resolve_response_budget_repo_root,)+# These tests read the accounting the lean envelope leaves out by default.+pytestmark = pytest.mark.usefixtures("debug_meta")+def _payload(tool: str, pad: int) -> dict[str, Any]:if tool == "get_health":diff --git a/tests/unit/server/mcp/test_scope_hint.py b/tests/unit/server/mcp/test_scope_hint.pyindex 6963b1cb9..0a7bc23f0 100644--- a/tests/unit/server/mcp/test_scope_hint.py+++ b/tests/unit/server/mcp/test_scope_hint.py@@ -154,16 +154,11 @@ async def test_layers_are_read_once_per_cache_key(@pytest.mark.asyncio-async def test_get_context_stamps_the_key_only_with_seeded_layers(- setup_mcp, session: AsyncSession, monkeypatch-):+async def test_get_context_carries_no_scope_hint(setup_mcp, session: AsyncSession):+ """The hint answers what a question-shaped reply missed; get_answer keeps it."""from repowise.server.mcp_server.tool_context.context import get_contextrid = setup_mcp-- bare = await get_context(targets=["src/auth/service.py"])- assert "scope_hint" not in bare["_meta"]-await _seed(session,rid,@@ -175,9 +170,7 @@ async def test_get_context_stamps_the_key_only_with_seeded_layers(_scope._CACHE.clear()seeded = await get_context(targets=["src/auth/service.py"])- assert seeded["_meta"]["scope_hint"] == (- "Unrelated to what was served: Automated Test Suites (2 files)."- )+ assert "scope_hint" not in seeded["_meta"]@pytest.mark.asynciodiff --git a/tests/unit/server/mcp/test_tool_timing_uniform.py b/tests/unit/server/mcp/test_tool_timing_uniform.pyindex bfad6c808..b3a316afd 100644--- a/tests/unit/server/mcp/test_tool_timing_uniform.py+++ b/tests/unit/server/mcp/test_tool_timing_uniform.py@@ -1,4 +1,4 @@-"""Every advertised tool reports how long it took."""+"""Every advertised tool reports how long it took, when the envelope is full."""from __future__ import annotations@@ -13,6 +13,26 @@ async def _run(fn: Any, *args: Any, **kwargs: Any) -> dict[str, Any]:return await tool_middleware(fn)(*args, **kwargs)+async def test_a_lean_envelope_carries_no_timing() -> None:+ async def get_health(targets: list[str] | None = None) -> dict[str, Any]:+ return {"files": [], "_meta": {"timing_ms": 12.5}}++ result = await _run(get_health)++ assert "timing_ms" not in result["_meta"]+++async def test_get_overview_keeps_the_full_envelope() -> None:+ async def get_overview(repo: str | None = None) -> dict[str, Any]:+ return {"overview": "x", "_meta": {}}++ result = await _run(get_overview)++ assert isinstance(result["_meta"]["timing_ms"], float)+ assert "response_budget" in result["_meta"]++[email protected]("debug_meta")async def test_timing_stamped_for_a_tool_that_does_not_thread_it() -> None:async def get_risk(targets: list[str], repo: str | None = None) -> dict[str, Any]:return {"targets": {}, "_meta": {"contract_version": 1}}@@ -23,6 +43,7 @@ async def test_timing_stamped_for_a_tool_that_does_not_thread_it() -> None:assert result["_meta"]["timing_ms"] >= 0[email protected]("debug_meta")async def test_a_tool_that_reports_its_own_timing_keeps_it() -> None:async def get_answer(question: str) -> dict[str, Any]:return {"answer": "yes", "_meta": {"contract_version": 1, "timing_ms": 1234.5}}@@ -34,6 +55,7 @@ async def test_a_tool_that_reports_its_own_timing_keeps_it() -> None:assert result["_meta"]["timing_ms"] == pytest.approx(1234.5, abs=1)[email protected]("debug_meta")async def test_timing_survives_the_final_budget_pass() -> None:async def get_why(query: str | None = None) -> dict[str, Any]:return {diff --git a/tests/unit/server/mcp/test_trust_contract.py b/tests/unit/server/mcp/test_trust_contract.pyindex 504100d83..45d534e85 100644--- a/tests/unit/server/mcp/test_trust_contract.py+++ b/tests/unit/server/mcp/test_trust_contract.py@@ -7,7 +7,7 @@ from types import SimpleNamespacefrom repowise.server.mcp_server import _meta-def test_build_meta_carries_contract_and_index_identity(tmp_path, monkeypatch):+def test_build_meta_carries_index_identity_without_diagnostics(tmp_path, monkeypatch):indexed = "a" * 40monkeypatch.setattr(_meta, "read_live_head", lambda _path: indexed)repository = SimpleNamespace(@@ -16,13 +16,19 @@ def test_build_meta_carries_contract_and_index_identity(tmp_path, monkeypatch):head_commit=indexed,)- meta = _meta.build_meta(repository=repository, targets=["src/a.py"])+ meta = _meta.build_meta(repository=repository, targets=["src/a.py"], timing_ms=5.0)- assert meta["contract_version"] == _meta.MCP_CONTRACT_VERSION+ assert "contract_version" not in meta+ assert "timing_ms" not in metaassert meta["indexed_commit"] == indexed[:12]assert meta["live_head"] == indexed[:12]assert meta["index_behind"] is False+ monkeypatch.setenv(_meta.DEBUG_META_ENV, "1")+ debug = _meta.build_meta(repository=repository, targets=["src/a.py"], timing_ms=5.0)+ assert debug["contract_version"] == _meta.MCP_CONTRACT_VERSION+ assert debug["timing_ms"] == 5.0+def test_shared_boundary_surfaces_degraded_partial_and_truncated_states():payload = {diff --git a/tests/unit/server/mcp/test_why_evidence_contract.py b/tests/unit/server/mcp/test_why_evidence_contract.pyindex 4a28f0030..1875a5892 100644--- a/tests/unit/server/mcp/test_why_evidence_contract.py+++ b/tests/unit/server/mcp/test_why_evidence_contract.py@@ -16,6 +16,9 @@ from repowise.server.mcp_server._why_evidence import ()from repowise.server.mcp_server.tool_why import _rank_keyword_matches+# These tests read the accounting the lean envelope leaves out by default.+pytestmark = pytest.mark.usefixtures("debug_meta")+def _row_by_id(result: dict, decision_id: str) -> dict:"""The row for *decision_id*, from whichever lane the response put it in.diff --git a/tests/unit/server/mcp/test_why_workspace_ranking.py b/tests/unit/server/mcp/test_why_workspace_ranking.pyindex 7a9f5f350..59d8ab03c 100644--- a/tests/unit/server/mcp/test_why_workspace_ranking.py+++ b/tests/unit/server/mcp/test_why_workspace_ranking.py@@ -13,6 +13,9 @@ import pytestfrom repowise.core.persistence.models import DecisionRecordfrom tests.unit.server.test_mcp_workspace import _make_repo_context, _MockRegistry+# These tests read the accounting the lean envelope leaves out by default.+pytestmark = pytest.mark.usefixtures("debug_meta")+_MCP_STATE = ("_registry","_workspace_root",