Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(mcp): a basis on every zero, a scope hint, a completeness line, and no source served twice (#2125)

Raghav Chamadiyacf06e9742fd8
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 186fc9218..698fe0b14 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -157,6 +157,8 @@ Resolve refs with `repowise expand <ref>` from a shell, or
| `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 |
| `response_budget` | Always: `limit_chars` (the ceiling that applied), `tier` (`default` or `expanded`, chosen by whether the call passed an expansion argument), `serialized_chars` (the size delivered) |
+| `scope_hint` | `get_context` and `get_answer`, when knowledge-graph layers exist that contain none of the served paths: one sentence naming up to three of them with file counts, so an agent knows which areas the answer did not touch |
+| `complete` | When the response served whole units: how many symbol bodies (bounds verified against the live file) or whole files, and that they need not be re-opened. Sliced bodies and partial ranges are never counted |
| `state` | Only when something fired: `degraded` plus `degraded_reasons` mapping each contributing key to its reason (a synthesis reason string, the retrieval legs that broke), `partial`, `truncated`. A coarse roll-up of the response's own flags |
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. Neither does `search_codebase` when a workspace call merges results from several repos, since there is no single indexed commit to compare.
@@ -285,7 +287,7 @@ The workhorse tool. Returns docs, symbols, ownership, freshness, and community m
| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `targets` | list[string] | Yes | File paths, module names, or symbol IDs. Batch multiple targets in one call. Symbol ids take the same `"path/to/file.py::Name"` form `get_symbol` accepts, with the same `::` / `.` / `/` separator normalisation, so an id from either tool works in the other. |
-| `include` | list[string] | No | Additional data to include: `"full_doc"` (full wiki markdown), `"callers"` (who calls this, symbol targets), `"callees"` (what this calls, symbol targets), `"ownership"` (primary owner, bus factor, contributor count), `"last_change"` (last commit date + author), `"metrics"` (PageRank, betweenness, percentiles), `"community"` (cluster membership + neighbors), `"decisions"` (full decision records; default returns titles only), `"skeleton"` (file targets only; the file with bodies elided: every signature, imports, and the bodies of the most central symbols, token-budgeted; typically ~15% of the full file's tokens) |
+| `include` | list[string] | No | Additional data to include: `"full_doc"` (full wiki markdown), `"callers"` (who calls this, symbol targets), `"callees"` (what this calls, symbol targets), `"ownership"` (primary owner, bus factor, contributor count), `"last_change"` (last commit date + author), `"metrics"` (PageRank, betweenness, percentiles), `"community"` (cluster membership + neighbors), `"decisions"` (full decision records; default returns titles only), `"skeleton"` (file targets only; the file with bodies elided: every signature, imports, and the bodies of the most central symbols, token-budgeted; typically ~15% of the full file's tokens). An empty `callers`, `callees` or `used_by` list sits beside a `*_basis` object: the language, how many call edges the index resolved for it, the share of those that are guesses, and a note that unbound call sites are not counted, so an empty list means no resolved edge, not proof of none |
| `compact` | boolean | No | Default `true`. Set `false` for full structure block and importer list. |
| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` |
@@ -720,7 +722,7 @@ Unreachable code, unused exports, unused internals, and zombie packages, sorted
| `no_unused_exports` | boolean | No | Exclude `unused_export` findings (default `false`) |
| `finding_id` | string | No | Resolve an emitted stable finding `id` directly in one call |
-**Returns:** Dead code findings grouped by confidence tier (high >= 0.8, medium, low). Each finding includes: file path, kind, confidence score, line count, and cleanup impact estimate. In workspace mode, confidence is lowered on findings other repos still import.
+**Returns:** Dead code findings grouped by confidence tier (high >= 0.8, medium, low). Each finding includes: file path, kind, confidence score, line count, and cleanup impact estimate. In workspace mode, confidence is lowered on findings other repos still import. `summary.call_resolution_basis` lists, per language, how many call edges the index resolved and what share are guesses, which is the graph the findings rest on.
**When to use:** Cleanup tasks, not a targeted fix. Conservative by design: `safe_only` excludes dynamically-loaded patterns and framework-decorated functions.
diff --git a/packages/core/src/repowise/core/generation/templates/agents_md.j2 b/packages/core/src/repowise/core/generation/templates/agents_md.j2
index 5329755d1..37911329c 100644
--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2
@@ -4,7 +4,7 @@ Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}
### How to work in this repo
-- **Trust the index.** `verified: true` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational.
+- **Trust the index.** `verified: true` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational. `_meta.complete` names units served whole; never re-read those.
- **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.j2
index cdd1a07e3..166b349ac 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -4,7 +4,7 @@ Indexed by [Repowise](https://repowise.dev). Last indexed: {{ data.indexed_at }}
### How to work in this repo
-- **Trust the index.** `verified: true` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational.
+- **Trust the index.** `verified: true` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational. `_meta.complete` names units served whole; never re-read those.
- **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.j2
index f36893609..b85f54bc9 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
@@ -56,7 +56,7 @@ Files that frequently change together across repos — consider reviewing both w
These 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` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational.
+- **Trust the index.** `verified: true` means the bytes were checked against the live tree, so never re-read those lines. Re-read only on `bounds: "approximate"`, `_meta.stale_warning`, `search_method: "bm25"` or `confidence: "low"`; `index_behind: true` alone is informational. `_meta.complete` names units served whole; never re-read those.
- **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/_basis.py b/packages/server/src/repowise/server/mcp_server/_basis.py
new file mode 100644
index 000000000..91354bf8d
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_basis.py
@@ -0,0 +1,146 @@
+"""What an empty callers/callees/used_by list actually rests on.
+
+An empty list from the call graph reads the same whether the resolver bound
+almost every call site in that language or guessed at most of them. These
+helpers attach the basis next to the zero: how many call edges the language
+has, and how large a share of them came from a strategy the resolution
+vocabulary ranks as a guess.
+
+The one thing the index cannot say is how many call sites the resolver failed
+to bind at all: no such count is persisted, and re-parsing on a tool path is
+not an option. The note text says so plainly rather than invent a rate.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from typing import Any
+
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import GraphEdge, GraphNode
+
+# Resolution origins the vocabulary in `ingestion/models.py::ResolutionOrigin`
+# annotates at or below 0.75 confidence. Each binds a name to a symbol that
+# merely exists somewhere in the repo, so the edge is a guess, not a fact.
+# NULL is not in here: it means the row predates the vocabulary, which is
+# unknown rather than weak, so it counts in the denominator and not as a guess.
+GUESSED_ORIGINS: frozenset[str] = frozenset(
+ {
+ "global_unique",
+ "receiver_global",
+ "receiver_typed_global",
+ "receiver_field_global",
+ "receiver_framework_global",
+ "return_type_global",
+ }
+)
+
+RESOLVED_NOTE = (
+ "Call sites the resolver could not bind are not counted, so an empty list "
+ "means no resolved edge reaches this symbol, not proof that nothing calls it."
+)
+
+NO_EDGES_NOTE = (
+ "No call edges were resolved for this language, so an empty list carries no information."
+)
+
+# One aggregate query per repo per index commit, and nothing more: the whole
+# per-language grouping is cached under a key that moves when the index does.
+_CACHE: dict[tuple[str, str], dict[str, dict[str | None, int]]] = {}
+_CACHE_MAX = 32
+# Targets of one call resolve concurrently; the lock keeps a cold cache to one query.
+_LOCK = asyncio.Lock()
+
+
+def reset_cache() -> None:
+ """Drop every cached grouping. For tests and for a re-index in-process."""
+ _CACHE.clear()
+
+
+async def _grouping(
+ session: AsyncSession, repo_id: str, cache_key: str
+) -> dict[str, dict[str | None, int]]:
+ """Call-edge counts for this repo, by source-node language then origin."""
+ key = (repo_id, cache_key)
+ cached = _CACHE.get(key)
+ if cached is not None:
+ return cached
+ async with _LOCK:
+ cached = _CACHE.get(key)
+ if cached is not None:
+ return cached
+ return await _query_grouping(session, key)
+
+
+async def _query_grouping(
+ session: AsyncSession, key: tuple[str, str]
+) -> dict[str, dict[str | None, int]]:
+ repo_id = key[0]
+ stmt = (
+ select(GraphNode.language, GraphEdge.resolution_origin, func.count(GraphEdge.id))
+ .join(
+ GraphNode,
+ (GraphNode.repository_id == GraphEdge.repository_id)
+ & (GraphNode.node_id == GraphEdge.source_node_id),
+ )
+ .where(
+ GraphEdge.repository_id == repo_id,
+ GraphEdge.edge_type == "calls",
+ )
+ .group_by(GraphNode.language, GraphEdge.resolution_origin)
+ )
+ grouping: dict[str, dict[str | None, int]] = {}
+ for language, origin, count in await session.execute(stmt):
+ grouping.setdefault(language or "", {})[origin] = int(count or 0)
+
+ if len(_CACHE) >= _CACHE_MAX:
+ _CACHE.pop(next(iter(_CACHE)))
+ _CACHE[key] = grouping
+ return grouping
+
+
+def _entry(language: str, origins: dict[str | None, int]) -> dict[str, Any]:
+ total = sum(origins.values())
+ if not total:
+ return {
+ "language": language,
+ "resolved_call_edges": 0,
+ "guessed_share": None,
+ "unresolved_call_sites": None,
+ "note": NO_EDGES_NOTE,
+ }
+ guessed = sum(n for origin, n in origins.items() if origin in GUESSED_ORIGINS)
+ return {
+ "language": language,
+ "resolved_call_edges": total,
+ "guessed_share": round(guessed / total, 2),
+ "unresolved_call_sites": None,
+ "note": RESOLVED_NOTE,
+ }
+
+
+async def call_resolution_basis(
+ session: AsyncSession, repo_id: str, language: str | None, *, cache_key: str
+) -> dict[str, Any]:
+ """Basis for one language's empty call-graph list."""
+ grouping = await _grouping(session, repo_id, cache_key)
+ return _entry(language or "", grouping.get(language or "", {}))
+
+
+async def call_resolution_bases(
+ session: AsyncSession, repo_id: str, *, cache_key: str
+) -> list[dict[str, Any]]:
+ """One basis entry per language that has call edges in this repo."""
+ grouping = await _grouping(session, repo_id, cache_key)
+ return [_entry(lang, origins) for lang, origins in sorted(grouping.items()) if origins]
+
+
+def basis_cache_key(repository: Any) -> str:
+ """A key that moves whenever the index does, cheapest field first."""
+ head = getattr(repository, "head_commit", None)
+ if head:
+ return str(head)
+ updated = getattr(repository, "updated_at", None)
+ return str(updated) if updated else "unknown"
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index bc272d6b6..15a38a85e 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -528,6 +528,28 @@ INDEX_BEHIND_LOW_CONFIDENCE_HINT = (
)
+def completeness_line(*, bodies: int = 0, files: int = 0) -> str | None:
+ """One sentence naming the whole units this response already served.
+
+ Only ever counts complete units. A sliced body or a partial range is not a
+ unit, so the callers filter before they count and this returns ``None`` when
+ nothing whole was served.
+ """
+ bodies = max(0, int(bodies))
+ files = max(0, int(files))
+ if not bodies and not files:
+ return None
+ parts: list[str] = []
+ if bodies:
+ noun = "symbol body" if bodies == 1 else "symbol bodies"
+ parts.append(f"{bodies} {noun} served whole from live source")
+ if files:
+ noun = "file" if files == 1 else "files"
+ parts.append(f"{files} {noun} served whole")
+ closing = "do not re-open it." if bodies + files == 1 else "do not re-open them."
+ return f"Complete: {' and '.join(parts)}; {closing}"
+
+
def answer_hint(
confidence: str,
*,
diff --git a/packages/server/src/repowise/server/mcp_server/_scope.py b/packages/server/src/repowise/server/mcp_server/_scope.py
new file mode 100644
index 000000000..d41412eb3
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/_scope.py
@@ -0,0 +1,100 @@
+"""One sentence naming the repo areas a reply did not touch.
+
+The index already groups every file into knowledge-graph layers. Naming the
+largest layers a reply never touched keeps an agent from wandering into them.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+_PREFIX = "Unrelated to what was served: "
+_MAX_SENTENCE = 200
+_MAX_LAYERS = 3
+
+# Layers are rewritten only when the index is, so one small-table read and one
+# json parse per repo per index commit covers every call on that commit.
+_CACHE: dict[str, list[tuple[str, frozenset[str]]]] = {}
+_CACHE_LIMIT = 16
+
+
+def reset_cache() -> None:
+ """Drop every cached layer set. For tests and for a re-index in-process."""
+ _CACHE.clear()
+
+
+def _layer_paths(node_ids_json: str | None) -> frozenset[str]:
+ """Repo-relative file paths in one layer. Node ids come with or without ``file:``."""
+ try:
+ raw = json.loads(node_ids_json) if node_ids_json else []
+ except (TypeError, ValueError):
+ return frozenset()
+ if not isinstance(raw, list):
+ return frozenset()
+ paths = set()
+ for node_id in raw:
+ if not isinstance(node_id, str):
+ continue
+ path = node_id[5:] if node_id.startswith("file:") else node_id
+ if path:
+ paths.add(path)
+ return frozenset(paths)
+
+
+async def _load_layers(
+ session: Any, repo_id: str, cache_key: str
+) -> list[tuple[str, frozenset[str]]]:
+ cached = _CACHE.get(cache_key)
+ if cached is not None:
+ return cached
+ from repowise.core.persistence.crud.knowledge_graph import get_kg_layers
+
+ rows = await get_kg_layers(session, repo_id)
+ layers = [(row.name, _layer_paths(row.node_ids_json)) for row in rows]
+ if len(_CACHE) >= _CACHE_LIMIT:
+ _CACHE.clear()
+ _CACHE[cache_key] = layers
+ return layers
+
+
+def _render(items: list[tuple[str, int]]) -> str:
+ parts = [
+ f"{name} ({count:,} file{'' if count == 1 else 's'})"
+ if index == 0
+ else f"{name} ({count:,})"
+ for index, (name, count) in enumerate(items)
+ ]
+ return f"{_PREFIX}{', '.join(parts)}."
+
+
+async def unrelated_scope_hint(
+ session: Any,
+ repo_id: str,
+ served_paths: list[str],
+ *,
+ cache_key: str,
+) -> str | None:
+ """Name up to three of the largest layers holding none of ``served_paths``."""
+ served = {path for path in served_paths if isinstance(path, str) and path}
+ if not served:
+ return None
+ layers = await _load_layers(session, repo_id, cache_key)
+ if not layers:
+ return None
+ unrelated = [
+ (name, len(paths)) for name, paths in layers if paths and not (paths & served)
+ ]
+ if not unrelated:
+ return None
+ unrelated.sort(key=lambda item: (-item[1], item[0]))
+ chosen = unrelated[:_MAX_LAYERS]
+ while chosen:
+ sentence = _render(chosen)
+ if len(sentence) <= _MAX_SENTENCE:
+ return sentence
+ chosen = chosen[:-1]
+ return None
+
+
+__all__ = ["unrelated_scope_hint"]
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py b/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py
index 3d9e176f5..1325d641d 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/bodies.py
@@ -11,12 +11,14 @@ from __future__ import annotations
from pathlib import Path
+from repowise.server.mcp_server._verify import end_anchor_holds, name_at_line
from repowise.server.mcp_server.tool_answer.config import (
_ENRICH_TOP_N_HITS,
_INLINE_BODY_MAX_LINES,
_INLINE_BODY_MAX_SYMBOLS,
)
from repowise.server.mcp_server.tool_answer.symbols import (
+ _read_repo_text,
_read_symbol_source,
attach_truncation_contract,
)
@@ -118,13 +120,15 @@ def _build_symbol_bodies(
``withheld_symbols`` it covers. That is why the degraded path can call this
too.
- ``source`` is the live body sliced at the indexed bounds; it is NOT
- bounds-verified, so the field stays deliberately distinct from get_symbol's
- ``verified`` contract and this entry never carries that key.
+ ``source`` is the live body sliced at the indexed bounds. ``verified: True``
+ is set only when the cheap bounds gate holds on the live file (the name is
+ still on its definition line and the stored end still closes the body), the
+ same gate get_symbol uses; an entry that fails it carries no such key.
"""
symbol_bodies: list[dict] = []
seen: set[tuple[str, str]] = set()
served_named_body = False
+ texts: dict[str, str | None] = {}
for tier, _kind, start, path, s in body_candidates:
if len(symbol_bodies) >= _INLINE_BODY_MAX_SYMBOLS:
break
@@ -136,11 +140,24 @@ def _build_symbol_bodies(
# the agent, so a docstring-heavy def shouldn't spend its whole window
# on docstring and truncate the logic the question asked about. Falls
# back to the hydrator's excerpt if the re-read fails.
- body = _read_symbol_source(
- repo_root, path, start, sym_end, max_lines=_INLINE_BODY_MAX_LINES
+ if path not in texts:
+ texts[path] = _read_repo_text(repo_root, path)
+ text = texts[path]
+ body = (
+ _read_symbol_source(
+ repo_root, path, start, sym_end, max_lines=_INLINE_BODY_MAX_LINES, text=text
+ )
+ if text is not None
+ else None
) or s.get("source_excerpt")
if not body:
continue
+ verified = False
+ if text is not None:
+ file_lines = text.splitlines()
+ verified = name_at_line(file_lines, name, start) and (
+ not sym_end or end_anchor_holds(file_lines, start, sym_end)
+ )
served = body.count("\n") + 1
end_served = start + served - 1
sym_end = sym_end or end_served
@@ -150,6 +167,8 @@ def _build_symbol_bodies(
"lines": [start, end_served],
"source": body,
}
+ if verified:
+ entry["verified"] = True
attach_truncation_contract(
entry, indexed_end=sym_end, end_served=end_served, repo_root=repo_root
)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
index 4f311e527..456c01375 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/projection.py
@@ -60,6 +60,65 @@ def _contained(text: str, slabs: list[str]) -> bool:
return bool(compact) and any(compact in " ".join(slab.split()) for slab in slabs)
+_SYMBOL_TEXT_KEYS = ("source_excerpt", "docstring")
+
+
+def _body_spans(bodies: list[Any]) -> list[tuple[str, int, int]]:
+ """The file and line range of every body this response already serves."""
+ spans: list[tuple[str, int, int]] = []
+ for row in bodies:
+ if not isinstance(row, dict):
+ continue
+ path = _nav_path(row)
+ lines = row.get("lines")
+ if not path or not isinstance(lines, list | tuple) or len(lines) != 2:
+ continue
+ start, end = lines
+ if isinstance(start, int) and isinstance(end, int):
+ spans.append((path, start, end))
+ return spans
+
+
+def _inside_served_body(
+ entry: dict[str, Any], path: str | None, spans: list[tuple[str, int, int]]
+) -> bool:
+ """True when this symbol's lines sit inside a body served for the same file."""
+ start = entry.get("start_line")
+ end = entry.get("end_line")
+ if not path or not isinstance(start, int) or not isinstance(end, int):
+ return False
+ return any(
+ span_path == path and span_start <= start and end <= span_end
+ for span_path, span_start, span_end in spans
+ )
+
+
+def _trim_key_symbols(
+ row: dict[str, Any], spans: list[tuple[str, int, int]], served_text: list[str]
+) -> None:
+ """Drop a key symbol's source and docstring when those bytes are served elsewhere.
+
+ The symbol still names and locates itself, so nothing is lost for navigation.
+ """
+ symbols = row.get("key_symbols")
+ if not isinstance(symbols, list):
+ return
+ row_path = _nav_path(row)
+ trimmed: list[Any] = []
+ for original in symbols:
+ if not isinstance(original, dict):
+ trimmed.append(original)
+ continue
+ entry = dict(original)
+ inside = _inside_served_body(entry, _nav_path(entry) or row_path, spans)
+ for key in _SYMBOL_TEXT_KEYS:
+ text = _text(entry, key)
+ if text and (inside or _contained(text, served_text)):
+ entry.pop(key, None)
+ trimmed.append(entry)
+ row["key_symbols"] = trimmed
+
+
def _deduplicate(payload: dict[str, Any]) -> None:
"""Keep each source fragment once, then keep paths only where they add navigation."""
bodies = _unique(
@@ -68,6 +127,7 @@ def _deduplicate(payload: dict[str, Any]) -> None:
)
payload["symbol_bodies"] = bodies
body_text = [_text(row, "source") for row in bodies]
+ body_spans = _body_spans(bodies)
quotes = _unique(
[
@@ -135,6 +195,8 @@ def _deduplicate(payload: dict[str, Any]) -> None:
):
row.pop("excerpt", None)
row.pop("snippet", None)
+ if isinstance(row, dict):
+ _trim_key_symbols(row, body_spans, [*body_text, *quote_text])
retrieval.append(row)
payload["retrieval"] = retrieval
@@ -353,13 +415,22 @@ async def _refresh_freshness(payload: dict[str, Any], repo: str | None) -> None:
return
try:
from repowise.core.persistence.database import get_session
+ from repowise.server.mcp_server._basis import basis_cache_key
from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_context
from repowise.server.mcp_server._meta import freshness_from_repo
+ from repowise.server.mcp_server._scope import unrelated_scope_hint
+ served = _served_paths(payload)
ctx = await _resolve_repo_context(repo)
async with get_session(ctx.session_factory) as session:
repository = await _get_repo(session)
- freshness = freshness_from_repo(repository, targets=_served_paths(payload))
+ scope_hint = await unrelated_scope_hint(
+ session,
+ repository.id,
+ [path.split("::", 1)[0] for path in served],
+ cache_key=f"{repository.id}:{basis_cache_key(repository)}",
+ )
+ freshness = freshness_from_repo(repository, targets=served)
except Exception:
return
meta = payload.setdefault("_meta", {})
@@ -369,9 +440,12 @@ async def _refresh_freshness(payload: dict[str, Any], repo: str | None) -> None:
"live_head",
"index_behind",
"stale_warning",
+ "scope_hint",
):
meta.pop(key, None)
meta.update(freshness)
+ if scope_hint:
+ meta["scope_hint"] = scope_hint
# An error reply carries confidence "low" too, and its fault is not the
# index, so the pointer would only misdirect there.
try:
@@ -386,6 +460,38 @@ async def _refresh_freshness(payload: dict[str, Any], repo: str | None) -> None:
meta["hint"] = hint
+def _whole_bodies(payload: dict[str, Any]) -> int:
+ """Count symbol bodies that survived the projection intact.
+
+ A body that was cut, or that carries a continuation to fetch the rest, is
+ not a whole unit and must never be claimed as one.
+ """
+ return sum(
+ 1
+ for row in payload.get("symbol_bodies") or []
+ if isinstance(row, dict)
+ and row.get("verified") is True
+ and not row.get("truncated")
+ and "continuation" not in row
+ )
+
+
+def _stamp_completeness(payload: dict[str, Any]) -> None:
+ """Set or clear ``_meta.complete`` for what this projection actually served."""
+ from repowise.server.mcp_server._meta import completeness_line
+
+ line = completeness_line(bodies=_whole_bodies(payload))
+ meta = payload.get("_meta")
+ if line:
+ if not isinstance(meta, dict):
+ meta = payload.setdefault("_meta", {})
+ meta["complete"] = line
+ elif isinstance(meta, dict):
+ # A cached payload can carry a claim the current projection no longer
+ # serves, so drop it rather than let it stand.
+ meta.pop("complete", None)
+
+
def projected_answer(fn: Callable[..., Any]) -> Callable[..., Any]:
"""Project the completed raw result once, regardless of cache or early return."""
@@ -401,6 +507,7 @@ def projected_answer(fn: Callable[..., Any]) -> Callable[..., Any]:
raw, question=question, scope=scope, repo=repo, include=include
)
await _refresh_freshness(payload, repo)
+ _stamp_completeness(payload)
return payload
return _wrapped
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.py
index 988f1d3b7..196b20401 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
@@ -50,6 +50,7 @@ from repowise.server.mcp_server._helpers import (
resolve_enum_argument,
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._meta import completeness_line as _completeness_line
from repowise.server.mcp_server._meta import context_hint as _context_hint
from repowise.server.mcp_server.tool_context.targets import _resolve_one_target
@@ -78,6 +79,27 @@ _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._basis import basis_cache_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}:{basis_cache_key(repository)}",
+ )
+ except Exception:
+ return None
+
+
@mcp.tool(
surface_order=20,
artifact_type="context",
@@ -176,6 +198,10 @@ async def get_context(
return_exceptions=True,
)
+ # 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):
@@ -208,6 +234,17 @@ 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(
+ 1
+ for r in results
+ if isinstance(r.get("skeleton"), dict) and r["skeleton"].get("mode") == "raw"
+ )
+ if whole_files:
+ response["_meta"]["complete"] = _completeness_line(files=whole_files)
# Cross-repo enrichment (Phase 3 + 4)
from repowise.server.mcp_server._helpers import _is_workspace_mode
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py b/packages/server/src/repowise/server/mcp_server/tool_context/enrichment.py
index 37522c9d7..5ace74a91 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
@@ -38,6 +38,7 @@ from repowise.core.persistence.models import (
HealthFinding,
Repository,
)
+from repowise.server.mcp_server._basis import basis_cache_key, call_resolution_basis
from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
from repowise.server.mcp_server._graph_files import keep_projected_edge, node_to_file
from repowise.server.mcp_server._helpers import filter_dicts_by_key, filter_path_list
@@ -177,10 +178,13 @@ async def _resolve_call_graph(
# pass for no reason; the graph has the answer at file granularity.
if node is not None and node.node_type == "file" and want_callers:
await _resolve_file_level_callers(
- session, repo_id, node, result_data, exclude_spec, collector
+ session, repo_id, node, result_data, exclude_spec, collector, repository=repository
)
if want_callees:
result_data["callees"] = []
+ result_data["callees_basis"] = await call_resolution_basis(
+ session, repo_id, node.language, cache_key=basis_cache_key(repository)
+ )
return
if want_callers:
result_data["callers"] = []
@@ -356,6 +360,13 @@ async def _resolve_call_graph(
result_data.setdefault("callers", [])
if want_callees:
result_data.setdefault("callees", [])
+ # A zero only earns a basis. A populated list is already its own evidence,
+ # and the basis would just repeat what the rows show.
+ for key in ("callers", "callees"):
+ if key in result_data and not result_data[key]:
+ result_data[f"{key}_basis"] = await call_resolution_basis(
+ session, repo_id, node.language, cache_key=basis_cache_key(repository)
+ )
if relations:
relations.sort(key=lambda r: (r["direction"], -r["total"], r["edge_type"]))
@@ -384,6 +395,8 @@ async def _resolve_file_level_callers(
result_data: dict[str, Any],
exclude_spec: Any = None,
collector: OmissionCollector | None = None,
+ *,
+ repository: Repository | None = None,
) -> None:
"""File-target callers: importing files + inbound symbol-call rollup.
@@ -468,6 +481,10 @@ async def _resolve_file_level_callers(
"File-level rollup: importing files plus inbound cross-file call "
"counts. For symbol-precise callers pass 'file.py::Symbol'."
)
+ if repository is not None and not result_data.get("callers"):
+ result_data["callers_basis"] = await call_resolution_basis(
+ session, repo_id, node.language, cache_key=basis_cache_key(repository)
+ )
async def _resolve_metrics(
diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
index a85549f99..b818cd76f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_context/targets.py
@@ -30,6 +30,7 @@ from repowise.core.persistence.models import (
Repository,
WikiSymbol,
)
+from repowise.server.mcp_server._basis import basis_cache_key, call_resolution_basis
from repowise.server.mcp_server._budget import OmissionCollector, cap_collection
from repowise.server.mcp_server._helpers import (
LIKE_ESCAPE,
@@ -861,6 +862,15 @@ async def _resolve_one_target(
collector,
label=f"{target} :: docs.used_by beyond cap={_MAX_USED_BY}",
)
+ # No users found says nothing on its own until the reader knows how
+ # much of this language's call graph the resolver actually bound.
+ if not docs.get("used_by"):
+ docs["used_by_basis"] = await call_resolution_basis(
+ session,
+ repo_id,
+ getattr(sym, "language", None),
+ cache_key=basis_cache_key(repository),
+ )
# Candidates
if len(sym_matches) > 1: # type: ignore[possibly-undefined]
docs["candidates"] = filter_dicts_by_key(
diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
index 0362cdecf..f3165381b 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py
@@ -22,6 +22,7 @@ from repowise.core.persistence.models import (
)
from repowise.core.registry import mcp_tool_registry as mcp
from repowise.server.mcp_server import _state
+from repowise.server.mcp_server._basis import basis_cache_key, call_resolution_bases
from repowise.server.mcp_server._budget import OmissionCollector
from repowise.server.mcp_server._helpers import (
_get_exclude_spec,
@@ -422,7 +423,7 @@ async def get_dead_code(
for f in all_findings:
by_kind[f.kind] = by_kind.get(f.kind, 0) + 1
- summary = {
+ summary: dict[str, Any] = {
"total_findings": len(all_findings),
"filtered_findings": len(filtered),
"deletable_lines": sum(f.lines for f in all_findings if _effective_safe(f)),
@@ -446,6 +447,12 @@ async def get_dead_code(
_maybe_limit_note(result)
+ # How much of the call graph these findings rest on, per language. A
+ # reachability finding is only as strong as the edges that reached.
+ summary["call_resolution_basis"] = await call_resolution_bases(
+ session, repository.id, cache_key=basis_cache_key(repository)
+ )
+
result["_meta"] = _build_meta(repository=repository)
attach_ignored_arguments(result, ignored)
collector.attach(result)
diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
index 458e3aeea..bd689592f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py
@@ -65,6 +65,7 @@ from repowise.server.mcp_server._helpers import (
read_repo_file_text,
)
from repowise.server.mcp_server._meta import build_meta as _build_meta
+from repowise.server.mcp_server._meta import completeness_line as _completeness_line
from repowise.server.mcp_server._meta import symbol_hint as _symbol_hint
from repowise.server.mcp_server._references import (
omission_reference,
@@ -423,6 +424,10 @@ async def _resolve_range_read(
targets=[path],
),
}
+ if s == 1 and e == total and not range_truncated:
+ # Only a range that covers the file end to end is a whole unit; any
+ # other slice leaves lines the caller still has to go and read.
+ response["_meta"]["complete"] = _completeness_line(files=1)
remainder_end = min(requested_end, total)
if range_truncated and e < remainder_end:
# Same clean-continuation contract as a truncated symbol read: name the
@@ -581,6 +586,7 @@ async def _render_ambiguous(
candidates: list[dict] = []
not_rendered: list[dict] = []
remaining = _AMBIGUITY_CHAR_BUDGET
+ whole_bodies = 0
for i, row in enumerate(rows):
if row.file_path not in text_cache:
@@ -624,6 +630,10 @@ async def _render_ambiguous(
remaining -= len(numbered)
entry["source"] = numbered
candidates.append(entry)
+ # A candidate is whole only when the served span reaches both ends of
+ # the verified bounds; a budget-clipped or relocated one does not count.
+ if check.verified and start <= check.start_line and end >= check.end_line:
+ whole_bodies += 1
response: dict[str, Any] = {
"symbol_id": symbol_id,
@@ -641,6 +651,8 @@ async def _render_ambiguous(
targets=sorted({r.file_path for r in rows}),
),
}
+ if whole_bodies:
+ response["_meta"]["complete"] = _completeness_line(bodies=whole_bodies)
if not_rendered:
response["not_rendered"] = not_rendered
response["note"] += (
@@ -916,6 +928,10 @@ async def get_symbol(
targets=[row.file_path],
),
}
+ if not truncated and check.verified:
+ # The whole body was served against live bytes, so nothing is left to
+ # fetch for this symbol.
+ response["_meta"]["complete"] = _completeness_line(bodies=1)
if truncated and not check.approximate and end < check.end_line:
# The body exceeds the serve cap. Hand back the exact range read that
# fetches the remainder so the agent never has to guess the next span
diff --git a/tests/unit/server/mcp/conftest.py b/tests/unit/server/mcp/conftest.py
index dc2165cf7..7a9260e13 100644
--- a/tests/unit/server/mcp/conftest.py
+++ b/tests/unit/server/mcp/conftest.py
@@ -567,6 +567,12 @@ async def populated_db(session: AsyncSession, repo_id: str) -> str:
async def setup_mcp(factory, fts, vector_store, populated_db):
"""Configure the MCP module's global state for testing."""
import repowise.server.mcp_server as mcp_mod
+ from repowise.server.mcp_server import _basis, _scope
+
+ # Every test repo shares one id and one updated_at, so a grouping cached
+ # from an earlier test would be served to the next one's different seed.
+ _basis.reset_cache()
+ _scope.reset_cache()
mcp_mod._session_factory = factory
mcp_mod._fts = fts
diff --git a/tests/unit/server/mcp/test_answer_projection.py b/tests/unit/server/mcp/test_answer_projection.py
index 7206c641e..28c421a90 100644
--- a/tests/unit/server/mcp/test_answer_projection.py
+++ b/tests/unit/server/mcp/test_answer_projection.py
@@ -510,3 +510,164 @@ async def test_an_error_reply_never_gets_the_update_pointer(setup_mcp, monkeypat
assert err["_meta"]["index_behind"] is True
assert "hint" not in err["_meta"]
+
+
+_KEY_SYMBOL_BODY = 'def check():\n """Return True."""\n return True\n'
+
+
+def _raw_with_key_symbols(key_symbols: list[dict]) -> dict:
+ return {
+ "answer": "Use AuthService.check.",
+ "citations": ["src/auth/service.py"],
+ "confidence": "medium",
+ "retrieval_quality": "partial",
+ "symbol_bodies": [
+ {
+ "path": "src/auth/service.py",
+ "name": "check",
+ "lines": [10, 20],
+ "source": _KEY_SYMBOL_BODY,
+ }
+ ],
+ "retrieval": [
+ {
+ "path": "src/auth/service.py",
+ "summary": "the auth service",
+ "key_symbols": key_symbols,
+ }
+ ],
+ }
+
+
+def test_a_key_symbol_repeating_a_served_body_keeps_only_its_name_and_lines():
+ raw = _raw_with_key_symbols(
+ [
+ {
+ "name": "check",
+ "kind": "function",
+ "signature": "check()",
+ "start_line": 10,
+ "end_line": 20,
+ "source_excerpt": _KEY_SYMBOL_BODY,
+ "docstring": "Return True.",
+ }
+ ]
+ )
+
+ payload = project_answer_payload(raw, question="how does auth work")
+
+ row = payload["retrieval"][0]
+ assert row["path"] == "src/auth/service.py"
+ assert row["key_symbols"] == [
+ {
+ "name": "check",
+ "kind": "function",
+ "signature": "check()",
+ "start_line": 10,
+ "end_line": 20,
+ }
+ ]
+
+
+def test_a_key_symbol_inside_the_served_line_range_loses_its_text():
+ raw = _raw_with_key_symbols(
+ [
+ {
+ "name": "check",
+ "kind": "function",
+ "start_line": 12,
+ "end_line": 15,
+ "source_excerpt": "12: def check(): # as indexed, not as read",
+ "docstring": "Returns true when the token is valid.",
+ }
+ ]
+ )
+
+ payload = project_answer_payload(raw, question="how does auth work")
+
+ entry = payload["retrieval"][0]["key_symbols"][0]
+ assert "source_excerpt" not in entry and "docstring" not in entry
+ assert entry["name"] == "check" and entry["start_line"] == 12
+
+
+def test_key_symbols_served_nowhere_else_keep_their_text():
+ raw = _raw_with_key_symbols(
+ [
+ {
+ "name": "later",
+ "kind": "function",
+ "start_line": 90,
+ "end_line": 99,
+ "source_excerpt": "def later(): pass",
+ "docstring": "Runs after.",
+ }
+ ]
+ )
+ raw["retrieval"].append(
+ {
+ "path": "src/auth/middleware.py",
+ "summary": "the middleware",
+ "key_symbols": [
+ {
+ "name": "reject",
+ "kind": "function",
+ "start_line": 10,
+ "end_line": 20,
+ "source_excerpt": "def reject(): pass",
+ "docstring": "Rejects a missing token.",
+ }
+ ],
+ }
+ )
+
+ payload = project_answer_payload(raw, question="how does auth work")
+
+ outside = payload["retrieval"][0]["key_symbols"][0]
+ other_file = payload["retrieval"][1]["key_symbols"][0]
+ assert outside["source_excerpt"] == "def later(): pass"
+ assert outside["docstring"] == "Runs after."
+ assert other_file["source_excerpt"] == "def reject(): pass"
+ assert other_file["docstring"] == "Rejects a missing token."
+
+
+def test_key_symbol_dedupe_never_mutates_the_raw_payload():
+ raw = _raw_with_key_symbols(
+ [
+ {
+ "name": "check",
+ "kind": "function",
+ "start_line": 10,
+ "end_line": 20,
+ "source_excerpt": _KEY_SYMBOL_BODY,
+ "docstring": "Return True.",
+ }
+ ]
+ )
+ before = copy.deepcopy(raw)
+
+ project_answer_payload(raw, question="how does auth work")
+
+ assert raw == before
+
+
+def test_the_expanded_projection_dedupes_key_symbols_too():
+ raw = _raw_with_key_symbols(
+ [
+ {
+ "name": "check",
+ "kind": "function",
+ "start_line": 10,
+ "end_line": 20,
+ "source_excerpt": _KEY_SYMBOL_BODY,
+ "docstring": "Return True.",
+ }
+ ]
+ )
+
+ expanded = project_answer_payload(
+ raw, question="how does auth work", include=["evidence"]
+ )
+
+ entry = expanded["retrieval"][0]["key_symbols"][0]
+ assert "source_excerpt" not in entry and "docstring" not in entry
+ assert entry["name"] == "check"
diff --git a/tests/unit/server/mcp/test_call_resolution_basis.py b/tests/unit/server/mcp/test_call_resolution_basis.py
new file mode 100644
index 000000000..af5d035f4
--- /dev/null
+++ b/tests/unit/server/mcp/test_call_resolution_basis.py
@@ -0,0 +1,199 @@
+"""Every empty call-graph list carries what it rests on.
+
+An empty ``callers``/``callees``/``used_by`` list reads identically whether the
+resolver bound almost every call site in that language or guessed most of them.
+``_basis`` attaches the language's call-edge count and the share of those edges
+the resolution vocabulary ranks at or below 0.75 confidence, plus a note saying
+that call sites the resolver never bound are not counted anywhere.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import pytest
+
+from repowise.core.persistence.models import GraphEdge, GraphNode
+from repowise.server.mcp_server._basis import (
+ NO_EDGES_NOTE,
+ RESOLVED_NOTE,
+ call_resolution_bases,
+ call_resolution_basis,
+ reset_cache,
+)
+
+_NOW = datetime(2026, 3, 19, 12, 0, 0, tzinfo=UTC)
+
+_LONELY = "src/auth/service.py::lonely"
+_CALLED = "src/auth/service.py::called"
+_CALLER = "src/auth/middleware.py::caller"
+
+# Two guesses (0.50 and 0.75), one certainty, one NULL origin. The NULL row
+# predates the vocabulary, so it belongs in the denominator and not the numerator:
+# 2 of 4 edges are guesses.
+_ORIGINS = ["global_unique", "receiver_global", "same_file", None]
+
+
+def _sym(node_id: str, sid: str, repo_id: str, language: str = "python") -> GraphNode:
+ file_path, name = node_id.split("::", 1)
+ return GraphNode(
+ id=sid,
+ repository_id=repo_id,
+ node_id=node_id,
+ node_type="symbol",
+ language=language,
+ name=name,
+ file_path=file_path,
+ kind="function",
+ start_line=10,
+ end_line=20,
+ created_at=_NOW,
+ )
+
+
+async def _seed(session, repo_id: str) -> None:
+ """One symbol nothing calls, one with four inbound calls of mixed origin."""
+ rows: list[object] = [
+ _sym(_LONELY, "b_lonely", repo_id),
+ _sym(_CALLED, "b_called", repo_id),
+ _sym(_CALLER, "b_caller", repo_id),
+ # A typescript symbol with no call edges at all.
+ _sym("web/dashboard.ts::render", "b_ts", repo_id, language="typescript"),
+ ]
+ for i, origin in enumerate(_ORIGINS):
+ source = _sym(f"src/callers/c{i}.py::c{i}", f"b_src_{i}", repo_id)
+ rows.append(source)
+ rows.append(
+ GraphEdge(
+ id=f"b_edge_{i}",
+ repository_id=repo_id,
+ source_node_id=source.node_id,
+ target_node_id=_CALLED,
+ edge_type="calls",
+ confidence=0.95,
+ resolution_origin=origin,
+ created_at=_NOW,
+ )
+ )
+ session.add_all(rows)
+ await session.flush()
+ reset_cache()
+
+
+async def test_basis_shape_and_guessed_share(setup_mcp, session):
+ """Two guesses of four edges, with the NULL origin counted only below the line."""
+ repo_id = setup_mcp
+ await _seed(session, repo_id)
+
+ basis = await call_resolution_basis(session, repo_id, "python", cache_key="k1")
+ assert basis == {
+ "language": "python",
+ "resolved_call_edges": 4,
+ "guessed_share": 0.5,
+ "unresolved_call_sites": None,
+ "note": RESOLVED_NOTE,
+ }
+ # The count the index cannot produce is named as absent, not guessed at.
+ assert "not counted" in RESOLVED_NOTE
+
+
+async def test_language_with_no_call_edges_says_so(setup_mcp, session):
+ """A language the graph never resolved a call in gets the other note."""
+ repo_id = setup_mcp
+ await _seed(session, repo_id)
+
+ basis = await call_resolution_basis(session, repo_id, "typescript", cache_key="k1")
+ assert basis["resolved_call_edges"] == 0
+ assert basis["guessed_share"] is None
+ assert basis["note"] == NO_EDGES_NOTE
+
+
+async def test_cache_holds_per_key_and_requeries_on_a_new_one(setup_mcp, session):
+ """One aggregate query per repo per index commit, and a new key re-reads."""
+ repo_id = setup_mcp
+ await _seed(session, repo_id)
+
+ first = await call_resolution_basis(session, repo_id, "python", cache_key="k1")
+ assert first["resolved_call_edges"] == 4
+
+ # A fifth edge lands. The old key still serves the cached grouping.
+ session.add(
+ GraphEdge(
+ id="b_edge_extra",
+ repository_id=repo_id,
+ source_node_id=_CALLER,
+ target_node_id=_CALLED,
+ edge_type="calls",
+ confidence=0.95,
+ resolution_origin="same_file",
+ created_at=_NOW,
+ )
+ )
+ await session.flush()
+
+ assert (await call_resolution_basis(session, repo_id, "python", cache_key="k1")) == first
+ fresh = await call_resolution_basis(session, repo_id, "python", cache_key="k2")
+ assert fresh["resolved_call_edges"] == 5
+ assert fresh["guessed_share"] == 0.4
+
+
+async def test_bases_cover_every_language_with_edges(setup_mcp, session):
+ """The repo-wide list names only languages that actually have call edges."""
+ repo_id = setup_mcp
+ await _seed(session, repo_id)
+
+ bases = await call_resolution_bases(session, repo_id, cache_key="k1")
+ assert [b["language"] for b in bases] == ["python"]
+
+
+async def test_get_context_empty_callers_carry_a_basis(setup_mcp, session):
+ """The zero gets its basis; a populated list does not."""
+ from repowise.server.mcp_server import get_context
+
+ await _seed(session, setup_mcp)
+
+ lonely = (await get_context([_LONELY], include=["callers"], compact=False))["targets"][_LONELY]
+ assert lonely["callers"] == []
+ assert lonely["callers_basis"]["language"] == "python"
+ assert lonely["callers_basis"]["resolved_call_edges"] == 4
+
+ called = (await get_context([_CALLED], include=["callers"], compact=False))["targets"][_CALLED]
+ assert called["callers"]
+ assert "callers_basis" not in called
+
+
+async def test_dead_code_summary_carries_the_basis(setup_mcp, session):
+ """Reachability findings say how much of the graph they rest on."""
+ from repowise.server.mcp_server import get_dead_code
+
+ await _seed(session, setup_mcp)
+
+ result = await get_dead_code()
+ bases = result["summary"]["call_resolution_basis"]
+ assert isinstance(bases, list)
+ assert {b["language"] for b in bases} == {"python"}
+ assert bases[0]["guessed_share"] == 0.5
+
+
+async def test_symbol_card_empty_used_by_carries_a_basis(setup_mcp, session):
+ """Nobody uses this symbol's file, and the card says what that rests on."""
+ from repowise.server.mcp_server import get_context
+
+ repo_id = setup_mcp
+ await _seed(session, repo_id)
+ session.add(_sym("src/orphan/util.py::orphaned", "b_orphan", repo_id))
+ await session.flush()
+
+ docs = (await get_context(["src/orphan/util.py::orphaned"], compact=False))["targets"][
+ "src/orphan/util.py::orphaned"
+ ]["docs"]
+ assert docs["used_by"] == []
+ assert docs["used_by_basis"]["language"] == "python"
+ assert docs["used_by_basis"]["note"] == RESOLVED_NOTE
diff --git a/tests/unit/server/mcp/test_completeness_line.py b/tests/unit/server/mcp/test_completeness_line.py
new file mode 100644
index 000000000..c643a8222
--- /dev/null
+++ b/tests/unit/server/mcp/test_completeness_line.py
@@ -0,0 +1,210 @@
+"""``_meta.complete``: a response says once what it served whole.
+
+Completeness is what stops an agent from re-opening a file it already holds,
+so the claim is only ever made for a whole unit, never a sliced body or a
+partial range.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.server.mcp_server._meta import completeness_line
+
+MODULE_SOURCE = '''"""A module."""
+
+import os
+
+_DEFAULT_MIN_COUNT = 2
+MAX_RETRIES = 5
+
+
+def alpha(x):
+ return x + 1
+'''
+
+
+def test_bodies_only_wording():
+ assert completeness_line(bodies=1) == (
+ "Complete: 1 symbol body served whole from live source; do not re-open it."
+ )
+ assert completeness_line(bodies=2) == (
+ "Complete: 2 symbol bodies served whole from live source; do not re-open them."
+ )
+
+
+def test_files_only_wording():
+ assert completeness_line(files=1) == "Complete: 1 file served whole; do not re-open it."
+ assert completeness_line(files=3) == "Complete: 3 files served whole; do not re-open them."
+
+
+def test_both_counts_are_one_sentence():
+ line = completeness_line(bodies=1, files=1)
+ assert line == (
+ "Complete: 1 symbol body served whole from live source and 1 file "
+ "served whole; do not re-open them."
+ )
+ assert line.count(";") == 1
+ assert "—" not in line
+
+
+def test_nothing_whole_says_nothing():
+ assert completeness_line() is None
+ assert completeness_line(bodies=0, files=0) is None
+
+
+# --- get_answer -------------------------------------------------------------
+
+
+def _projected(raw: dict):
+ from repowise.server.mcp_server.tool_answer.projection import projected_answer
+
+ async def _fn(*, question, scope, repo, include):
+ return raw
+
+ return projected_answer(_fn)
+
+
+async def test_projected_answer_counts_only_whole_bodies(setup_mcp):
+ raw = {
+ "answer": "It authenticates.",
+ "confidence": "low",
+ "citations": ["src/auth/service.py"],
+ "symbol_bodies": [
+ {
+ "path": "src/auth/service.py",
+ "name": "login",
+ "source": "def login(): ...",
+ "verified": True,
+ },
+ {"path": "src/auth/service.py", "name": "drifted", "source": "def drifted(): ..."},
+ {
+ "path": "src/auth/service.py",
+ "name": "big",
+ "source": "def big(): ...",
+ "truncated": True,
+ "continuation": "repowise#deadbeef",
+ },
+ ],
+ }
+
+ result = await _projected(raw)(question="how does login work")
+
+ assert result["_meta"]["complete"] == (
+ "Complete: 1 symbol body served whole from live source; do not re-open it."
+ )
+
+
+async def test_projected_answer_pops_a_stale_claim(setup_mcp):
+ raw = {
+ "answer": "No grounded answer was found.",
+ "confidence": "low",
+ "citations": ["src/auth/service.py"],
+ "_meta": {"complete": "Complete: 4 symbol bodies served whole from live source."},
+ }
+
+ result = await _projected(raw)(question="how does login work")
+
+ assert "complete" not in result["_meta"]
+
+
+# --- get_symbol -------------------------------------------------------------
+
+
+def repo_on_disk(tmp_path, monkeypatch):
+ import repowise.server.mcp_server as mcp_mod
+
+ (tmp_path / "pkg").mkdir()
+ (tmp_path / "pkg" / "mod.py").write_text(MODULE_SOURCE)
+ huge = "def huge(x):\n" + "\n".join(f" v{i} = {i}" for i in range(1, 900)) + "\n"
+ (tmp_path / "pkg" / "big.py").write_text(huge)
+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))
+ return tmp_path
+
+
+async def _add_symbol(session, *, symbol_id, path, name, start, end, marker):
+ from sqlalchemy import select
+
+ from repowise.core.persistence.models import Repository, WikiSymbol
+
+ repo = (await session.execute(select(Repository))).scalars().first()
+ session.add(
+ WikiSymbol(
+ id=marker,
+ repository_id=repo.id,
+ file_path=path,
+ symbol_id=symbol_id,
+ name=name,
+ qualified_name=name,
+ kind="function",
+ signature=f"def {name}(x)",
+ start_line=start,
+ end_line=end,
+ language="python",
+ )
+ )
+ await session.flush()
+
+
+async def test_whole_symbol_body_carries_the_claim(setup_mcp, repo_on_disk, session):
+ from repowise.server.mcp_server import get_symbol
+
+ await _add_symbol(
+ session,
+ symbol_id="pkg/mod.py::alpha",
+ path="pkg/mod.py",
+ name="alpha",
+ start=9,
+ end=10,
+ marker="cmpl-alpha",
+ )
+ result = await get_symbol("pkg/mod.py::alpha")
+
+ assert result["truncated"] is False
+ assert result["_meta"]["complete"] == (
+ "Complete: 1 symbol body served whole from live source; do not re-open it."
+ )
+
+
+async def test_a_truncated_body_claims_nothing(setup_mcp, repo_on_disk, session):
+ from repowise.server.mcp_server import get_symbol
+
+ await _add_symbol(
+ session,
+ symbol_id="pkg/big.py::huge",
+ path="pkg/big.py",
+ name="huge",
+ start=1,
+ end=900,
+ marker="cmpl-huge",
+ )
+ result = await get_symbol("pkg/big.py::huge")
+
+ assert result["truncated"] is True
+ assert "complete" not in result["_meta"]
+
+
+async def test_a_range_covering_the_whole_file_is_a_unit(setup_mcp, repo_on_disk):
+ from repowise.server.mcp_server import get_symbol
+
+ total = len(MODULE_SOURCE.splitlines())
+ result = await get_symbol(f"pkg/mod.py:1-{total}")
+
+ assert result["start_line"] == 1
+ assert result["end_line"] == result["total_lines"] == total
+ assert result["_meta"]["complete"] == "Complete: 1 file served whole; do not re-open it."
+
+
+async def test_a_partial_range_claims_nothing(setup_mcp, repo_on_disk):
+ from repowise.server.mcp_server import get_symbol
+
+ result = await get_symbol("pkg/mod.py:5-6")
+
+ assert "complete" not in result["_meta"]
diff --git a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
index 373d58a9b..667e9a3ba 100644
--- a/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
+++ b/tests/unit/server/mcp/test_recoverable_caps_wire_contracts.py
@@ -275,7 +275,10 @@ async def test_context_used_by_and_relations_recover_in_one_bounded_query_shape(
relation_recovered = await _recover_one(relation_result, "Type025")
assert "Type025" in relation_recovered
assert "Type000" not in relation_recovered
- assert relation_statements <= 20 and used_by_statements <= 20
+ # The first call also pays the one aggregate behind the empty-callers basis
+ # and the one layer read behind the scope hint. Both are cached per repo per
+ # index commit, so the second call pays neither.
+ assert relation_statements <= 22 and used_by_statements <= 20
@pytest.mark.asyncio
diff --git a/tests/unit/server/mcp/test_scope_hint.py b/tests/unit/server/mcp/test_scope_hint.py
new file mode 100644
index 000000000..579069983
--- /dev/null
+++ b/tests/unit/server/mcp/test_scope_hint.py
@@ -0,0 +1,213 @@
+"""_meta.scope_hint: naming the index layers a reply never touched."""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence.models import KnowledgeGraphLayer
+from repowise.server.mcp_server import _scope
+from repowise.server.mcp_server._scope import unrelated_scope_hint
+
+
[email protected](autouse=True)
+def _clear_layer_cache():
+ _scope._CACHE.clear()
+ yield
+ _scope._CACHE.clear()
+
+
+def _layer(rid: str, layer_id: str, name: str, node_ids: list[str], order: int = 0):
+ return KnowledgeGraphLayer(
+ repository_id=rid,
+ layer_id=layer_id,
+ name=name,
+ description="",
+ node_ids_json=json.dumps(node_ids),
+ display_order=order,
+ )
+
+
+async def _seed(session: AsyncSession, rid: str, layers: list[KnowledgeGraphLayer]) -> None:
+ for layer in layers:
+ session.add(layer)
+ await session.flush()
+
+
+async def test_prefixed_and_bare_node_ids_both_parse(session: AsyncSession, repo_id: str):
+ await _seed(
+ session,
+ repo_id,
+ [
+ _layer(repo_id, "tests", "Automated Test Suites", ["file:tests/a.py", "tests/b.py"]),
+ _layer(repo_id, "core", "Analysis Core", ["file:src/core.py"]),
+ ],
+ )
+
+ hint = await unrelated_scope_hint(session, repo_id, ["src/core.py"], cache_key="k1")
+
+ assert hint == "Unrelated to what was served: Automated Test Suites (2 files)."
+
+
+async def test_a_served_path_excludes_its_layer(session: AsyncSession, repo_id: str):
+ await _seed(
+ session,
+ repo_id,
+ [
+ _layer(repo_id, "ui", "Frontend UI", ["file:web/a.tsx", "file:web/b.tsx"]),
+ _layer(repo_id, "docs", "Docs Tooling", ["docs/a.md"]),
+ ],
+ )
+
+ both = await unrelated_scope_hint(session, repo_id, ["web/a.tsx"], cache_key="k2")
+ assert both == "Unrelated to what was served: Docs Tooling (1 file)."
+
+ _scope._CACHE.clear()
+ none_left = await unrelated_scope_hint(
+ session, repo_id, ["web/a.tsx", "docs/a.md"], cache_key="k3"
+ )
+ assert none_left is None
+
+
+async def test_largest_layers_first_and_capped_at_three(session: AsyncSession, repo_id: str):
+ await _seed(
+ session,
+ repo_id,
+ [
+ _layer(repo_id, "l1", "Alpha", [f"file:a/{i}.py" for i in range(5)]),
+ _layer(repo_id, "l2", "Beta", [f"file:b/{i}.py" for i in range(9)]),
+ _layer(repo_id, "l3", "Gamma", [f"file:c/{i}.py" for i in range(7)]),
+ _layer(repo_id, "l4", "Delta", ["file:d/0.py"]),
+ _layer(repo_id, "l5", "Served", ["file:src/core.py"]),
+ ],
+ )
+
+ hint = await unrelated_scope_hint(session, repo_id, ["src/core.py"], cache_key="k4")
+
+ assert hint == "Unrelated to what was served: Beta (9 files), Gamma (7), Alpha (5)."
+ assert "Delta" not in hint
+
+
+async def test_the_sentence_stays_under_200_chars_by_dropping_layers(
+ session: AsyncSession, repo_id: str
+):
+ long_name = "Very Long Layer Name That Eats The Budget " * 2
+ await _seed(
+ session,
+ repo_id,
+ [
+ _layer(repo_id, "l1", long_name + "One", [f"file:a/{i}.py" for i in range(9)]),
+ _layer(repo_id, "l2", long_name + "Two", [f"file:b/{i}.py" for i in range(8)]),
+ _layer(repo_id, "l3", long_name + "Three", [f"file:c/{i}.py" for i in range(7)]),
+ _layer(repo_id, "l4", "Served", ["file:src/core.py"]),
+ ],
+ )
+
+ hint = await unrelated_scope_hint(session, repo_id, ["src/core.py"], cache_key="k5")
+
+ assert hint is not None
+ assert len(hint) <= 200
+ # Names are never cut: the list is what shortens.
+ assert (long_name + "One") in hint
+ assert (long_name + "Three") not in hint
+
+
+async def test_none_without_layers_or_without_served_paths(session: AsyncSession, repo_id: str):
+ assert await unrelated_scope_hint(session, repo_id, ["src/core.py"], cache_key="k6") is None
+
+ await _seed(session, repo_id, [_layer(repo_id, "l1", "Alpha", ["file:a/0.py"])])
+ _scope._CACHE.clear()
+ assert await unrelated_scope_hint(session, repo_id, [], cache_key="k7") is None
+ assert await unrelated_scope_hint(session, repo_id, ["", None], cache_key="k7") is None
+
+
+async def test_layers_are_read_once_per_cache_key(
+ session: AsyncSession, repo_id: str, monkeypatch
+):
+ await _seed(session, repo_id, [_layer(repo_id, "l1", "Alpha", ["file:a/0.py"])])
+
+ import repowise.core.persistence.crud.knowledge_graph as kg_mod
+
+ calls: list[str] = []
+ real = kg_mod.get_kg_layers
+
+ async def counted(sess, rid):
+ calls.append(rid)
+ return await real(sess, rid)
+
+ monkeypatch.setattr(kg_mod, "get_kg_layers", counted)
+
+ await unrelated_scope_hint(session, repo_id, ["src/core.py"], cache_key="commit-a")
+ await unrelated_scope_hint(session, repo_id, ["src/other.py"], cache_key="commit-a")
+ assert len(calls) == 1
+
+ await unrelated_scope_hint(session, repo_id, ["src/core.py"], cache_key="commit-b")
+ assert len(calls) == 2
+
+
+async def test_get_context_stamps_the_key_only_with_seeded_layers(
+ setup_mcp, session: AsyncSession, monkeypatch
+):
+ from repowise.server.mcp_server.tool_context.context import get_context
+
+ rid = setup_mcp
+
+ bare = await get_context(targets=["src/auth/service.py"])
+ assert "scope_hint" not in bare["_meta"]
+
+ await _seed(
+ session,
+ rid,
+ [
+ _layer(rid, "tests", "Automated Test Suites", ["file:tests/a.py", "file:tests/b.py"]),
+ _layer(rid, "auth", "Auth", ["file:src/auth/service.py"]),
+ ],
+ )
+ _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)."
+ )
+
+
+async def test_answer_projection_stamps_the_key_from_served_paths(
+ setup_mcp, session: AsyncSession
+):
+ from repowise.server.mcp_server.tool_answer.projection import _refresh_freshness
+
+ rid = setup_mcp
+ await _seed(
+ session,
+ rid,
+ [
+ _layer(rid, "tests", "Automated Test Suites", ["file:tests/a.py", "file:tests/b.py"]),
+ _layer(rid, "auth", "Auth", ["file:src/auth/service.py"]),
+ ],
+ )
+ _scope._CACHE.clear()
+
+ payload = {
+ "confidence": "high",
+ "citations": ["src/auth/service.py"],
+ "_meta": {"scope_hint": "stale sentence"},
+ }
+ await _refresh_freshness(payload, None)
+
+ assert payload["_meta"]["scope_hint"] == (
+ "Unrelated to what was served: Automated Test Suites (2 files)."
+ )
+
+ empty = {"confidence": "high", "citations": [], "_meta": {"scope_hint": "stale sentence"}}
+ await _refresh_freshness(empty, None)
+ assert "scope_hint" not in empty["_meta"]