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(answer): serve a ranked list of candidate files at every confidence (#3012)

Raghav Chamadiya687098be28e1
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 5d6635eca..9be46ece7 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -147,9 +147,9 @@ Answers a how, where or why question in one call: it runs hybrid retrieval over
| `repo` | string | default repo | Workspace repo alias. `"all"` is not supported |
| `include` | list[string] | none | `["evidence"]` returns the full evidence projection with a larger budget |
-**Key return fields:** `answer`, `confidence` (`high` / `medium` / `low`, rates the prose), `retrieval_quality` (`high` / `partial` / `weak`, rates the evidence), `citations`, `symbol_bodies` (live bodies of symbols the answer names), `retrieval`, `best_guesses` and `fallback_targets` (on low confidence), `episodes` (dated facts bearing on the question), `degraded` (synthesis could not run), `_meta.scope_hint` (areas the answer did not touch).
+**Key return fields:** `answer`, `confidence` (`high` / `medium` / `low`, rates the prose), `retrieval_quality` (`high` / `partial` / `weak`, rates the evidence), `citations`, `symbol_bodies` (live bodies of symbols the answer names), `retrieval`, `best_guesses` and `fallback_targets` (on low confidence), `candidate_files` (ranked file paths the citations do not already name: up to 3 at `high`, 5 otherwise), `episodes` (dated facts bearing on the question), `degraded` (synthesis could not run), `_meta.scope_hint` (areas the answer did not touch).
-A `high` answer can be cited directly. On `low`, read the rows the reply names before searching again. Without an LLM provider the tool still answers from retrieval, marked `degraded`.
+A `high` answer can be cited directly. On `low`, read the rows the reply names, then `candidate_files`, before searching again. Without an LLM provider the tool still answers from retrieval, marked `degraded`.
```
get_answer(question="How does the authentication flow work?")
diff --git a/docs/reference/MCP_RESPONSE_FIELDS.md b/docs/reference/MCP_RESPONSE_FIELDS.md
index 18c7f3a69..d51785a13 100644
--- a/docs/reference/MCP_RESPONSE_FIELDS.md
+++ b/docs/reference/MCP_RESPONSE_FIELDS.md
@@ -117,7 +117,8 @@ Every suggested follow-up (`get_health`'s `fix_first[].next_call`, the refactori
| `retrieval_quality` | `high`, `partial` or `weak`: rates the evidence under the prose |
| `symbol_bodies` | Live bodies of the symbols the answer names. Read these before calling `get_symbol` |
| `retrieval` | Evidence rows (summary, snippet, key symbols). Shrinks as confidence rises |
-| `candidates` | Ranked shortlist of files retrieval resolved, `{path, lines?}`, up to 5. Navigation, not evidence. Only with `include=["evidence"]` |
+| `candidate_files` | Ranked file paths retrieval resolved, minus those already in `citations`: up to 3 at `high`, 5 at `medium`, `low` or `degraded`. Navigation, not evidence. Served at every confidence; absent when retrieval resolved no file |
+| `candidates` | The top 5 of those files as `{path, lines?, defines?}` rows. Only with `include=["evidence"]` |
| `best_guesses`, `fallback_targets` | On low confidence: where to look, each with a one-line reason |
| `episodes` | A dated fact recorded about this checkout that bears on the question; `still_true` says how current it is |
| `degraded` | Synthesis could not run (no provider, or the call failed). The answer is assembled from retrieval and mined rationale with no LLM, and `confidence` is graded from the retrieval: `medium` unless `retrieval_quality` is `weak`, never `high` |
diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-ask.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-ask.md
index 90a2ea769..1440ea1c1 100644
--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-ask.md
+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-ask.md
@@ -36,7 +36,7 @@ the other tool-adapter commands.
## How to present the result
- `confidence: high` is content-grounded — cite it directly.
-- `medium` / `low` — say so, and follow any `best_guesses` / `fallback_targets`
+- `medium` / `low`: say so, and follow any `best_guesses` / `fallback_targets` / `candidate_files`
into `/prompts:repowise-context` or `get_context` rather than inventing detail.
- If a `note` warns that numbers may be synthesised, surface that caveat.
- Prefer this over `/prompts:repowise-search` when the user asked a *question*. Prefer
diff --git a/packages/cli/src/repowise/cli/commands/ask_cmd.py b/packages/cli/src/repowise/cli/commands/ask_cmd.py
index 9fa9c54ee..027007a2d 100644
--- a/packages/cli/src/repowise/cli/commands/ask_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/ask_cmd.py
@@ -32,7 +32,8 @@ def project(payload: dict, question: str) -> dict:
================== ===========================================
kept answer, confidence, grounding,
retrieval_quality, citations, quotes,
- fallback_targets, best_guesses (without their
+ fallback_targets, candidate_files,
+ best_guesses (without their
excerpts), next_action_hint, note,
omission_marker, episodes (subject / recorded
/ still_true), error, index (from ``_meta``)
@@ -95,6 +96,8 @@ def project(payload: dict, question: str) -> dict:
out["dropped_blocks"] = dropped
if payload.get("fallback_targets"):
out["fallback_targets"] = list(payload["fallback_targets"])
+ if payload.get("candidate_files"):
+ out["candidate_files"] = list(payload["candidate_files"])
episodes = payload.get("episodes") or []
if episodes:
out["episodes"] = [
@@ -217,7 +220,11 @@ def _render(projected: dict) -> None:
# names like get_context land in front of someone who cannot run one.
console.print(f"\n[bold]Next[/bold] {_ta.as_cli_prose(projected['next_action_hint'])}")
- for label, key in (("Citations", "citations"), ("Read next", "fallback_targets")):
+ for label, key in (
+ ("Citations", "citations"),
+ ("Read next", "fallback_targets"),
+ ("Candidate files", "candidate_files"),
+ ):
values = projected.get(key) or []
if values:
console.print(f"\n[bold]{label}[/bold]")
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 ed298e746..36fea85a8 100644
--- a/packages/core/src/repowise/core/generation/templates/agents_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/agents_md.j2
@@ -8,7 +8,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 `fallback_targets` or `best_guesses` 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.
+- **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.
- **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.
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 35f17a13c..11fd8d5a2 100644
--- a/packages/core/src/repowise/core/generation/templates/claude_md.j2
+++ b/packages/core/src/repowise/core/generation/templates/claude_md.j2
@@ -8,7 +8,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 `fallback_targets` or `best_guesses` 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.
+- **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.
- **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.
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 18671e900..578b43c32 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` 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 `fallback_targets` or `best_guesses` 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.
+- **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.
- **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.
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
index c982916ea..2ab3ef8b2 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
@@ -175,6 +175,9 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {
"candidates",
"fallback_targets[]",
"fallback_targets",
+ # Last: a bare path is the fewest bytes per file worth opening.
+ "candidate_files[]",
+ "candidate_files",
),
expansion_argument="include",
protected=("answer", "confidence", "citations", "next_action_hint", "degraded"),
diff --git a/packages/server/src/repowise/server/mcp_server/_meta.py b/packages/server/src/repowise/server/mcp_server/_meta.py
index 79abe8ff3..0a10d6052 100644
--- a/packages/server/src/repowise/server/mcp_server/_meta.py
+++ b/packages/server/src/repowise/server/mcp_server/_meta.py
@@ -712,5 +712,8 @@ def answer_hint(
"rates the ranked hits; start from the first one."
)
if confidence == "low":
- return "Low confidence — Read the listed fallback_targets to verify before answering."
+ return (
+ "Low confidence. Read the top evidence row or candidate_files to "
+ "verify before answering."
+ )
return None
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
index c965e5578..8259932c4 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py
@@ -171,9 +171,6 @@ from repowise.server.mcp_server.tool_answer.retrieval import (
_intersection_boost,
_rerank_by_coverage,
)
-from repowise.server.mcp_server.tool_answer.retrieval import (
- serialize_candidates as _serialize_candidates,
-)
from repowise.server.mcp_server.tool_answer.symbols import (
_anchor_symbol_hits,
_concept_anchor_hits,
@@ -441,7 +438,7 @@ async def get_answer(
"symbol from another file, to avoid a confidently-wrong answer. "
'Re-check the qualifier, or call search_codebase mode="symbol" '
"on the base name to see every definition. The files retrieval "
- "ranked for this question are in candidates.",
+ "ranked for this question are in candidate_files.",
repository=repository,
t0=t0,
),
@@ -600,7 +597,7 @@ async def get_answer(
return await _degrade("synthesis-failed", failure_note)
citations = [
- h["target_path"] for h in hits if h["target_path"] and h["target_path"] in answer_text
+ h["target_path"] for h in hits if h.get("target_path") and h["target_path"] in answer_text
]
if not citations:
# Fall back to top-2 retrieval paths so the agent always has something to verify.
@@ -650,9 +647,7 @@ async def get_answer(
# Where to look next, always: navigation, not evidence, so it survives the
# shrinking of ``retrieval`` on high-confidence answers.
- candidates = _serialize_candidates(resolved_pool)
- if candidates:
- payload["candidates"] = candidates
+ _with_candidates(payload, resolved_pool)
# Persist only the trust-relevant retrieval state. The cache read rebuilds
# timing/freshness metadata for the current request, then restores this
@@ -724,7 +719,8 @@ async def get_answer(
High confidence is content-grounded and may be used directly. Medium
confidence keeps the smallest verification evidence; low confidence leads
- with an actionable local conclusion and ranked evidence. Provider keys and
+ with an actionable local conclusion and ranked evidence. ``candidate_files``
+ ranks the files worth opening that the citations do not name. Provider keys and
network access are optional: local source, symbols, FTS, rationale, and
data-shape evidence remain usable when embeddings or synthesis fail.
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py b/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py
index f15334ac9..e4b4c64b0 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/cache.py
@@ -61,6 +61,7 @@ def _cached_payload_paths(payload: dict) -> list:
return [
*(payload.get("citations") or []),
*(payload.get("fallback_targets") or []),
+ *(payload.get("candidate_files") or []),
# "path" is the serialized key; "target_path" survives in rows cached
# before the clean retrieval view existed.
*(h.get("path") or h.get("target_path") for h in (payload.get("retrieval") or [])),
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py b/packages/server/src/repowise/server/mcp_server/tool_answer/config.py
index daed05938..5f6929ce6 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/config.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/config.py
@@ -271,7 +271,17 @@ _HIGH_CONFIDENCE_SCORE_FLOOR = 1.5
# Degraded (no-provider / synthesis-failed) payloads are never cached, so changes
# confined to them need no bump; a needless bump costs every keyed install a
# round of provider spend.
-_ANSWER_SCHEMA_VERSION = 17
+# 18: rows carry ``candidate_files``, the ranked paths-only list.
+_ANSWER_SCHEMA_VERSION = 18
+
+# How many paths ``candidate_files`` serves: the knee of measured coverage
+# gained per extra file, past which each path mostly costs precision. A high
+# answer already names its files, so it keeps fewer.
+_CANDIDATE_FILES_HIGH = 3
+_CANDIDATE_FILES_MAX = 5
+# The raw list is longer than either cap, so paths the citations already name
+# can be removed without leaving the served list short.
+_CANDIDATE_FILES_POOL = 10
# Backstop TTL for cache rows. Commit stamping is the primary freshness gate;
# this covers rows without a stamp (older rows, repos without git metadata).
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py b/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py
index 1d3ba68d5..9a9a84081 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/degraded.py
@@ -50,7 +50,7 @@ def _degraded_summary(reason: str, symbol_bodies: list[dict], served: int) -> st
f"`symbol_bodies` carries the live source of {names}, read from the "
"current checkout"
+ (", cut at the line cap where noted; see `continuation`. " if cut else " in full. ")
- + "Answer from that; `retrieval`, `fallback_targets` and `candidates` "
+ + "Answer from that; `retrieval`, `fallback_targets` and `candidate_files` "
"cover the wider question."
)
if served:
@@ -58,7 +58,7 @@ def _degraded_summary(reason: str, symbol_bodies: list[dict], served: int) -> st
f"No synthesized prose ({reason}), but retrieval succeeded and this "
f"payload is usable: {served} ranked "
f"{'hit' if served == 1 else 'hits'} in `retrieval`, the files to open "
- "in `fallback_targets`, and the wider ranked shortlist in `candidates`. "
+ "in `fallback_targets`, and the wider ranked shortlist in `candidate_files`. "
"Read those rather than starting a fresh search."
)
return (
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/payload.py b/packages/server/src/repowise/server/mcp_server/tool_answer/payload.py
index abbf73101..d7be4e5f5 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/payload.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/payload.py
@@ -45,6 +45,9 @@ from repowise.server.mcp_server.tool_answer.retrieval import (
_CANDIDATE_LIMIT,
_candidate_justification,
)
+from repowise.server.mcp_server.tool_answer.retrieval import (
+ serialize_candidate_files as _serialize_candidate_files,
+)
from repowise.server.mcp_server.tool_answer.retrieval import (
serialize_candidates as _serialize_candidates,
)
@@ -152,6 +155,9 @@ def _with_candidates(payload: dict, resolved_pool: list[dict]) -> dict:
candidates = _serialize_candidates(resolved_pool)
if candidates:
payload["candidates"] = candidates
+ # Longer than ``candidates``: the projection serves these paths at
+ # every confidence, while ``candidates`` waits for include=["evidence"].
+ payload["candidate_files"] = _serialize_candidate_files(resolved_pool)
return payload
@@ -239,7 +245,7 @@ def _union_answer_payload(
)
note += (
" If the question was about something other than these definitions, "
- "candidates holds the files retrieval ranked for it."
+ "candidate_files holds the files retrieval ranked for it."
)
payload: dict = {
"answer": (
@@ -352,7 +358,7 @@ def build_value_payload(
"note": (
"Extracted verbatim from the live source line — no LLM "
"synthesis involved. Cite directly; no verification "
- "Read needed. candidates holds the files retrieval ranked, "
+ "Read needed. candidate_files holds the files retrieval ranked, "
"for the wider question the value sits inside."
),
"_meta": _build_meta(
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 38a17f756..c34e58f46 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
@@ -7,6 +7,11 @@ from collections.abc import Callable
from functools import wraps
from typing import Any
+from repowise.server.mcp_server.tool_answer.config import (
+ _CANDIDATE_FILES_HIGH,
+ _CANDIDATE_FILES_MAX,
+)
+
_COLLECTIONS = (
"citations",
"retrieval",
@@ -272,10 +277,30 @@ def _keep(payload: dict[str, Any], key: str, limit: int | None) -> None:
payload[key] = rows[:limit]
-def _default_shape(payload: dict[str, Any], question: str) -> None:
+def _shape_confidence(payload: dict[str, Any]) -> Any:
# A degraded payload keeps the fullest shape whatever it graded: trimming is
# keyed on prose replacing evidence, and there the evidence IS the product.
- confidence = "low" if payload.get("degraded") else payload.get("confidence", "low")
+ return "low" if payload.get("degraded") else payload.get("confidence", "low")
+
+
+def _shape_candidate_files(payload: dict[str, Any], *, expanded: bool) -> None:
+ """Serve the ranked paths the final citations do not already name."""
+ rows = payload.pop("candidate_files", None)
+ if not isinstance(rows, list):
+ return
+ cited = {path for path in map(_nav_path, payload.get("citations") or []) if path}
+ paths = [
+ path for path in dict.fromkeys(row for row in rows if isinstance(row, str))
+ if path not in cited
+ ]
+ high = not expanded and _shape_confidence(payload) == "high"
+ paths = paths[: _CANDIDATE_FILES_HIGH if high else _CANDIDATE_FILES_MAX]
+ if paths:
+ payload["candidate_files"] = paths
+
+
+def _default_shape(payload: dict[str, Any], question: str) -> None:
+ confidence = _shape_confidence(payload)
why = question.lstrip().lower().startswith("why")
if confidence == "high":
for key in ("retrieval", "best_guesses", "candidates", "fallback_targets"):
@@ -333,6 +358,10 @@ def _record_reductions(
) -> None:
reduced = False
for key in _COLLECTIONS:
+ # By default ``candidate_files`` carries these paths, so counting the
+ # hidden rows would only advertise what the reply already serves.
+ if key == "candidates" and not expanded:
+ continue
total = totals.get(key, 0)
emitted = len(payload.get(key) or []) if isinstance(payload.get(key), list) else 0
if total <= emitted:
@@ -373,6 +402,7 @@ def project_answer_payload(
expanded = "evidence" in set(include or [])
if not expanded:
_default_shape(payload, question)
+ _shape_candidate_files(payload, expanded=expanded)
_rewrite_degraded_answer(payload)
for key in _COLLECTIONS:
if not payload.get(key):
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
index 65bb70134..126bd7053 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/retrieval.py
@@ -23,6 +23,7 @@ from repowise.server.mcp_server._retrieval_rank import rerank_by_context_coverag
from repowise.server.mcp_server.tool_answer.config import (
_BACKEND_PATH_PREFIXES,
_BACKEND_QUESTION_TOKENS,
+ _CANDIDATE_FILES_POOL,
_COVERAGE_FLOOR,
_DEFINES_CHAR_BUDGET,
_DOMAIN_PENALTY,
@@ -87,6 +88,18 @@ def serialize_candidates(hits: list[dict], *, limit: int = _CANDIDATE_LIMIT) ->
return out
+def serialize_candidate_files(hits: list[dict]) -> list[str]:
+ """Distinct openable file paths in rank order, paths only, no hydration."""
+ paths: list[str] = []
+ for h in hits:
+ path = hit_file_path(h)
+ if path and path not in paths:
+ paths.append(path)
+ if len(paths) >= _CANDIDATE_FILES_POOL:
+ break
+ return paths
+
+
def serialize_hits(
hits: list[dict],
*,
diff --git a/plugins/claude-code/commands/ask.md b/plugins/claude-code/commands/ask.md
index 1a6783cba..95724d873 100644
--- a/plugins/claude-code/commands/ask.md
+++ b/plugins/claude-code/commands/ask.md
@@ -37,7 +37,7 @@ the other tool-adapter commands.
## How to present the result
- `confidence: high` is content-grounded — cite it directly.
-- `medium` / `low` — say so, and follow any `best_guesses` / `fallback_targets`
+- `medium` / `low`: say so, and follow any `best_guesses` / `fallback_targets` / `candidate_files`
into `/repowise:context` or `get_context` rather than inventing detail.
- If a `note` warns that numbers may be synthesised, surface that caveat.
- Prefer this over `/repowise:search` when the user asked a *question*. Prefer
diff --git a/plugins/shared/commands/ask.md b/plugins/shared/commands/ask.md
index e9b54c6f4..0d1acdceb 100644
--- a/plugins/shared/commands/ask.md
+++ b/plugins/shared/commands/ask.md
@@ -38,7 +38,7 @@ the other tool-adapter commands.
## How to present the result
- `confidence: high` is content-grounded — cite it directly.
-- `medium` / `low` — say so, and follow any `best_guesses` / `fallback_targets`
+- `medium` / `low`: say so, and follow any `best_guesses` / `fallback_targets` / `candidate_files`
into `{{cmd:context}}` or `get_context` rather than inventing detail.
- If a `note` warns that numbers may be synthesised, surface that caveat.
- Prefer this over `{{cmd:search}}` when the user asked a *question*. Prefer
diff --git a/tests/fixtures/mcp/tool_response_shapes.json b/tests/fixtures/mcp/tool_response_shapes.json
index 2ee27c01a..8165c6758 100644
--- a/tests/fixtures/mcp/tool_response_shapes.json
+++ b/tests/fixtures/mcp/tool_response_shapes.json
@@ -20,9 +20,9 @@
"timing_ms": null
},
"answer": null,
- "candidates_emitted": null,
- "candidates_reduced_reason": null,
- "candidates_total": null,
+ "candidate_files": [
+ null
+ ],
"citations": [
null
],
diff --git a/tests/unit/generation/test_kg_claude_md_onboarding.py b/tests/unit/generation/test_kg_claude_md_onboarding.py
index a94e1ac4e..572d8af21 100644
--- a/tests/unit/generation/test_kg_claude_md_onboarding.py
+++ b/tests/unit/generation/test_kg_claude_md_onboarding.py
@@ -119,7 +119,7 @@ class TestClaudeMdKGSection:
assert "never re-read them" in rendered
# `confidence` rates the prose; a low grade points at the evidence the
# reply already named rather than at a second round-trip.
- assert "`fallback_targets` or `best_guesses`" in rendered
+ assert "`candidate_files` the reply names" in rendered
# An empty call-graph list is never served without the basis beside it.
assert "`*_basis`" in rendered
# Pre-edit framing: the mandatory Read of edit targets is conceded.
diff --git a/tests/unit/server/mcp/test_answer_candidates.py b/tests/unit/server/mcp/test_answer_candidates.py
index 3d3b1d7fe..d74aea282 100644
--- a/tests/unit/server/mcp/test_answer_candidates.py
+++ b/tests/unit/server/mcp/test_answer_candidates.py
@@ -8,7 +8,10 @@ built from the pool before the 5-hit synthesis cap.
from __future__ import annotations
-from repowise.server.mcp_server.tool_answer.retrieval import serialize_candidates
+from repowise.server.mcp_server.tool_answer.retrieval import (
+ serialize_candidate_files,
+ serialize_candidates,
+)
def _hit(path, symbols=None):
@@ -159,3 +162,11 @@ def test_the_char_budget_is_spent_in_rank_order_and_truncates_nothing():
for e in out:
if e.get("defines"):
assert all(":" in pair for pair in e["defines"].split(", "))
+
+
+def test_candidate_files_are_ranked_openable_paths_beyond_the_candidates_cap():
+ hits = [_hit("a.py::One"), _hit("a.py"), {"title": "no path"}]
+ hits += [_hit(f"f{i}.py") for i in range(20)]
+ out = serialize_candidate_files(hits)
+ assert out == ["a.py", *[f"f{i}.py" for i in range(9)]]
+ assert len(serialize_candidates(hits)) == 5
diff --git a/tests/unit/server/mcp/test_answer_early_return_candidates.py b/tests/unit/server/mcp/test_answer_early_return_candidates.py
index 510714959..994152fc6 100644
--- a/tests/unit/server/mcp/test_answer_early_return_candidates.py
+++ b/tests/unit/server/mcp/test_answer_early_return_candidates.py
@@ -119,12 +119,14 @@ def test_helper_attaches_the_shortlist():
payload = {"answer": "", "retrieval": []}
out = _with_candidates(payload, [{"target_path": "a.py"}, {"target_path": "b.py"}])
assert out["candidates"] == [{"path": "a.py"}, {"path": "b.py"}]
+ assert out["candidate_files"] == ["a.py", "b.py"]
def test_helper_adds_nothing_when_the_pool_is_empty():
"""An empty block is worse than none: it reads as "retrieval found nothing"."""
payload = {"answer": "", "retrieval": []}
- assert "candidates" not in _with_candidates(payload, [])
+ out = _with_candidates(payload, [])
+ assert "candidates" not in out and "candidate_files" not in out
def test_helper_takes_nothing_away():
diff --git a/tests/unit/server/mcp/test_answer_payload.py b/tests/unit/server/mcp/test_answer_payload.py
index 55ae50577..6f9d36d08 100644
--- a/tests/unit/server/mcp/test_answer_payload.py
+++ b/tests/unit/server/mcp/test_answer_payload.py
@@ -249,6 +249,26 @@ async def test_high_confidence_drops_retrieval_block(setup_mcp, monkeypatch):
_assert_no_underscore_keys(result)
+async def test_a_hit_without_target_path_does_not_break_citations(setup_mcp, monkeypatch):
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.server.mcp_server import get_answer
+
+ _patch_pipeline(monkeypatch, answer_mod, scores=(5.0, 4.0))
+ hydrate = answer_mod._hydrate_hits
+
+ async def _pathless_second(hits, ctx, *, scope=None):
+ hits = await hydrate(hits, ctx, scope=scope)
+ hits[1].pop("target_path")
+ return hits
+
+ monkeypatch.setattr(answer_mod, "_hydrate_hits", _pathless_second)
+ _patch_provider(monkeypatch, answer_mod, "The go() function drives it (pkg/beta/one.py).")
+
+ result = await get_answer("how does the beta module go function work")
+ assert "pkg/beta/one.py" in result["citations"]
+
+
@pytest.mark.asyncio
async def test_medium_confidence_keeps_two_truncated_hits(setup_mcp, monkeypatch):
import repowise.server.mcp_server.tool_answer.answer as answer_mod
diff --git a/tests/unit/server/mcp/test_answer_projection.py b/tests/unit/server/mcp/test_answer_projection.py
index 9040e8596..af3159508 100644
--- a/tests/unit/server/mcp/test_answer_projection.py
+++ b/tests/unit/server/mcp/test_answer_projection.py
@@ -80,6 +80,8 @@ async def test_fresh_and_cached_answers_share_one_external_contract(setup_mcp, m
assert fresh["confidence"] == "high"
assert cached["_meta"]["cached"] is True
+ assert "src/auth/middleware.py" in fresh["candidate_files"]
+ assert "src/auth/service.py" not in fresh["candidate_files"] # cited
assert _without_meta(fresh) == _without_meta(cached)
assert "stale_warning" not in fresh["_meta"]
assert "stale_warning" not in cached["_meta"]
@@ -332,6 +334,8 @@ async def test_no_llm_and_failed_legs_remain_compact_and_actionable(
assert result["answer"]
assert result["next_action_hint"]
assert result.get("best_guesses") or result.get("symbol_bodies") or result.get("retrieval")
+ assert result["candidate_files"]
+ assert not set(result["candidate_files"]) & set(result.get("citations") or [])
assert len(json.dumps(result, separators=(",", ":"), default=str)) < 24_000
if legs["vector"] == "error":
assert result["_meta"]["retrieval_degraded"] == ["vector"]
@@ -669,3 +673,63 @@ def test_the_expanded_projection_dedupes_key_symbols_too():
entry = expanded["retrieval"][0]["key_symbols"][0]
assert "source_excerpt" not in entry and "docstring" not in entry
assert entry["name"] == "check"
+
+
+_POOL = [f"src/auth/f{i}.py" for i in range(12)]
+
+
+def _with_pool(confidence: str, **extra) -> dict:
+ raw = _raw(confidence)
+ raw["candidate_files"] = ["src/auth/service.py", *_POOL[:9]]
+ raw.update(extra)
+ return raw
+
+
+ ("confidence", "extra", "cap"),
+ [
+ ("high", {}, 3),
+ ("medium", {}, 5),
+ ("low", {}, 5),
+ ("medium", {"degraded": "no-llm-provider"}, 5),
+ ],
+)
+def test_candidate_files_serve_ranked_uncited_paths_at_every_confidence(
+ confidence, extra, cap
+):
+ out = project_answer_payload(_with_pool(confidence, **extra), question="how does auth work")
+
+ # Ranked, minus the cited file, capped by grade: 3 at high, 5 otherwise.
+ assert out["candidate_files"] == _POOL[:cap]
+ assert "candidates" not in out
+ assert not any(key.startswith("candidates_") for key in out)
+
+
+def test_candidate_files_cap_at_five_and_dedupe_only_against_citations():
+ raw = _with_pool("low")
+ raw["candidate_files"] = ["src/auth/service.py", "src/auth/middleware.py", *_POOL]
+
+ out = project_answer_payload(raw, question="how does auth work")
+
+ # middleware.py is a fallback target and a retrieval row, not a citation.
+ assert out["candidate_files"] == ["src/auth/middleware.py", *_POOL[:4]]
+
+
+def test_candidate_files_absent_when_retrieval_resolved_no_file():
+ out = project_answer_payload(_raw("low"), question="how does auth work")
+ assert "candidate_files" not in out
+
+ raw = _raw("low")
+ raw["candidate_files"] = ["src/auth/service.py"]
+ assert "candidate_files" not in project_answer_payload(raw, question="how does auth work")
+
+
+def test_evidence_projection_only_gains_candidate_files():
+ raw = _raw("medium")
+ before = project_answer_payload(copy.deepcopy(raw), question="q", include=["evidence"])
+ raw["candidate_files"] = ["src/auth/service.py", *_POOL]
+
+ after = project_answer_payload(raw, question="q", include=["evidence"])
+
+ assert after.pop("candidate_files") == _POOL[:5]
+ assert after == before
diff --git a/tests/unit/server/mcp/test_answer_synthesis_timeout.py b/tests/unit/server/mcp/test_answer_synthesis_timeout.py
index 4bf106670..e835256d9 100644
--- a/tests/unit/server/mcp/test_answer_synthesis_timeout.py
+++ b/tests/unit/server/mcp/test_answer_synthesis_timeout.py
@@ -460,6 +460,7 @@ async def test_both_failure_modes_return_the_same_payload_shape(reason):
"fallback_targets",
"retrieval",
"candidates",
+ "candidate_files",
"best_guesses",
"next_action_hint",
"note",
@@ -480,14 +481,14 @@ async def test_degraded_answer_describes_the_payload_instead_of_being_empty():
"""An empty ``answer`` beside working retrieval reads as a failed call.
The field is the first thing a reader looks at, so leaving it blank while
- ``retrieval``/``candidates`` are populated invites throwing the whole
+ ``retrieval``/``candidate_files`` are populated invites throwing the whole
result away. It must name what survived and where to find it.
"""
payload = await _payload()
answer = payload["answer"]
assert answer, "degraded answer must not be empty"
assert "synthesis-failed" in answer, "the reason belongs in the visible field"
- for field in ("retrieval", "fallback_targets", "candidates"):
+ for field in ("retrieval", "fallback_targets", "candidate_files"):
assert field in answer, f"{field} is populated but never mentioned"
diff --git a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
index 1c916830b..c04e63535 100644
--- a/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
+++ b/tests/unit/server/mcp/test_cross_tool_reference_contracts.py
@@ -109,6 +109,7 @@ class Cell:
_PATH_FIELDS = {
"affected_files",
"candidate",
+ "candidate_files",
"candidates",
"citations",
"entry_points",
diff --git a/tests/unit/server/mcp/test_meta_freshness.py b/tests/unit/server/mcp/test_meta_freshness.py
index 10b46333d..1bd887bd5 100644
--- a/tests/unit/server/mcp/test_meta_freshness.py
+++ b/tests/unit/server/mcp/test_meta_freshness.py
@@ -246,7 +246,7 @@ def test_confident_answer_is_never_told_retrieval_found_nothing() -> None:
assert answer_hint("high") is None
assert answer_hint("medium") is None
- assert "Read the listed fallback_targets" in (answer_hint("low") or "")
+ assert "candidate_files" in (answer_hint("low") or "")
def test_no_answer_hint_names_an_external_tool() -> None:
diff --git a/website/mcp-server.md b/website/mcp-server.md
index 05b04497f..42e40cc84 100644
--- a/website/mcp-server.md
+++ b/website/mcp-server.md
@@ -188,6 +188,7 @@ One-call RAG over the wiki layer. Runs retrieval, gates on confidence, and synth
- `citations` (list of strings) — file paths backing the answer
- `confidence` (string) — `"high"`, `"medium"`, or `"low"`. High-confidence answers can be cited directly without verification reads; lower confidence indicates the agent should fall back to `search_codebase` or `Read`.
- `fallback_targets` (list of strings) — top retrieval hits the agent should `Read` if it does not trust the synthesized answer
+- `candidate_files` (list of strings): ranked file paths retrieval resolved that the citations do not already name: up to 3 on a high-confidence answer, 5 otherwise
- `retrieval` (list) — raw top-N hits with snippets
**When to use:** First call on any code question. Collapses the typical "search → read → reason" loop into a single round-trip.