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.

fix(cli): keep an older index readable, and cap confidence on a truncated symbol lookup (#1458)

Raghav Chamadiya0822aefdd24d
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
index 8aa4feeb0..b4991517f 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd/repo_checks.py
@@ -13,6 +13,7 @@ from repowise.cli.helpers import (
get_db_url_for_repo,
get_repowise_dir,
load_state,
+ reconcile_schema_best_effort,
run_async,
)
@@ -102,6 +103,9 @@ def _run_repo_checks(
)
url = get_db_url_for_repo(repo_path)
+ # So doctor reports the store's real state rather than a
+ # `no such column` failure on a store one repowise older.
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
sf = create_session_factory(engine)
count = 0
@@ -214,6 +218,7 @@ def _run_repo_checks(
)
url = get_db_url_for_repo(repo_path)
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
sf = create_session_factory(engine)
async with get_session(sf) as session:
@@ -257,6 +262,7 @@ def _run_repo_checks(
from repowise.core.providers.embedding.base import MockEmbedder
url = get_db_url_for_repo(repo_path)
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
sf = create_session_factory(engine)
@@ -398,6 +404,7 @@ def _run_repo_checks(
from repowise.core.providers.embedding.base import MockEmbedder
url = get_db_url_for_repo(repo_path)
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
sf = create_session_factory(engine)
@@ -535,6 +542,7 @@ def _run_repo_checks(
)
url = get_db_url_for_repo(repo_path)
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
sf = create_session_factory(engine)
repaired = 0
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
index bedbcaf89..a3de3634e 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/persist.py
@@ -19,7 +19,7 @@ def _load_persisted_coverage_map(repo_path: object) -> dict[str, dict]:
``coverage_files`` so ``repowise health`` reflects it without a flag.
Best-effort: no repo row / no rows / any DB error yields an empty map.
"""
- from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.cli.helpers import get_db_url_for_repo, reconcile_schema_best_effort
from repowise.core.persistence import (
create_engine,
create_session_factory,
@@ -31,7 +31,11 @@ def _load_persisted_coverage_map(repo_path: object) -> dict[str, dict]:
)
async def _do() -> dict[str, dict]:
- engine = create_engine(get_db_url_for_repo(repo_path))
+ url = get_db_url_for_repo(repo_path)
+ # Without this the ORM's `no such column` on a store one repowise
+ # older is swallowed below and reads as "no coverage".
+ await reconcile_schema_best_effort(url)
+ engine = create_engine(url)
sf = create_session_factory(engine)
async with get_session(sf) as session:
repo = await get_repository_by_path(session, str(repo_path))
@@ -68,7 +72,7 @@ def _persist_health(repo_path: object, *, report: object) -> None:
Best-effort — a missing repo row or a DB error logs to stderr and
returns rather than crashing the CLI.
"""
- from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.cli.helpers import get_db_url_for_repo, reconcile_schema_best_effort
from repowise.core.analysis.health.trends import snapshot_file_maps
from repowise.core.persistence import (
create_engine,
@@ -84,6 +88,7 @@ def _persist_health(repo_path: object, *, report: object) -> None:
async def _do() -> None:
url = get_db_url_for_repo(repo_path)
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
sf = create_session_factory(engine)
async with get_session(sf) as session:
diff --git a/packages/cli/src/repowise/cli/commands/health_cmd/trends.py b/packages/cli/src/repowise/cli/commands/health_cmd/trends.py
index 2d00a7980..7f48fd77a 100644
--- a/packages/cli/src/repowise/cli/commands/health_cmd/trends.py
+++ b/packages/cli/src/repowise/cli/commands/health_cmd/trends.py
@@ -17,7 +17,7 @@ def _render_trend(repo_path: object, *, fmt: str) -> None:
workspace and single-repo indexes alike. When no snapshots exist
(e.g. health was never run), prints a friendly hint.
"""
- from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.cli.helpers import get_db_url_for_repo, reconcile_schema_best_effort
from repowise.core.analysis.health.trends import diff_snapshots, recent_kpis
from repowise.core.persistence import (
create_engine,
@@ -31,6 +31,7 @@ def _render_trend(repo_path: object, *, fmt: str) -> None:
async def _fetch() -> tuple[list[dict], object]:
url = get_db_url_for_repo(repo_path)
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
sf = create_session_factory(engine)
async with get_session(sf) as session:
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index 18909b241..d13a075fa 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -16,6 +16,7 @@ from repowise.cli.helpers import (
get_db_url_for_repo,
get_repowise_dir,
load_state,
+ reconcile_schema_best_effort,
resolve_command_target,
run_async,
)
@@ -55,6 +56,9 @@ def _query_repo_counts(repo_path: Path) -> tuple[int, int]:
from repowise.core.persistence.models import GraphNode, Repository
url = get_db_url_for_repo(repo_path)
+ # Without this a store one repowise older reports 0 files / 0 pages:
+ # the `no such column` is swallowed by the caller's except.
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
sf = create_session_factory(engine)
@@ -115,6 +119,7 @@ def _query_page_count(repo_path: Path) -> int:
from repowise.core.persistence.models import Page, Repository
url = get_db_url_for_repo(repo_path)
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
sf = create_session_factory(engine)
try:
@@ -153,7 +158,9 @@ async def _query_pages(repo_path: Path) -> tuple[dict[str, int], int]:
list_pages,
)
- engine = create_engine(get_db_url_for_repo(repo_path))
+ url = get_db_url_for_repo(repo_path)
+ await reconcile_schema_best_effort(url)
+ engine = create_engine(url)
sf = create_session_factory(engine)
counts: dict[str, int] = {}
@@ -195,6 +202,7 @@ def _query_health(repo_path: Path) -> dict | None:
)
url = get_db_url_for_repo(repo_path)
+ await reconcile_schema_best_effort(url)
engine = create_engine(url)
sf = create_session_factory(engine)
try:
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index cf004f264..5dfc068dd 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -187,6 +187,72 @@ def get_db_url_for_repo(repo_path: Path) -> str:
return resolve_db_url(repo_path)
+#: Busy timeout for the reconcile's own connection. The engine default is 30s,
+#: sized for bulk graph-edge writes; inheriting it here is a trap, because a
+#: read command opens several engines (``status`` four, ``doctor`` five) and a
+#: store locked by a concurrent ``repowise update`` would stall each one in
+#: turn — measured at 133s of silence for ``status`` before this was bounded.
+#: The reconcile is a best-effort secondary write, so it takes the same lever
+#: issue #326 gave the cost tracker: fail fast and be dropped rather than block.
+_RECONCILE_BUSY_TIMEOUT_MS = 2000
+
+
+async def reconcile_schema_best_effort(db_url: str) -> None:
+ """Back-fill additive schema drift on the store at *db_url*, best-effort.
+
+ An index built by an older repowise is missing whatever columns the models
+ have gained since, and the ORM then fails with a raw ``no such column`` on
+ the first query — which for a read command means every read. ``init_db``
+ back-fills those columns in place and is idempotent, so the CLI pairs it
+ with ``create_engine`` everywhere it opens a store, the way the MCP server,
+ the workspace registry and the FastAPI app already do in their lifespans.
+
+ Opportunistic, not a precondition, which is the part worth having in one
+ place. Reconciling needs a write, and a store can be read-only or
+ exclusively locked by a concurrent ``repowise update``. Aborting there would
+ be a regression twice over: a store already on the current schema needs no
+ DDL and would have read fine, and where the drift is real the following
+ query fails with the ``no such column`` that the failure shield turns into
+ "this index predates the installed repowise, run repowise update" — a
+ better answer than whichever write error stopped the repair.
+
+ Takes a URL rather than an engine so the repair runs on its own short-timeout
+ connection: the caller's engine keeps the full 30s window for the work it was
+ opened to do, and a contended repair gives up in two seconds instead of
+ stalling the command behind it.
+
+ Never CREATES a store. ``init_db`` on a fresh path would materialise a
+ 42-table file, so a read command run in a repo that was never indexed would
+ leave a database behind where the user expects "not indexed yet".
+ """
+ from repowise.core.persistence import create_engine, init_db
+
+ if _missing_sqlite_file(db_url):
+ return
+
+ engine = create_engine(db_url, busy_timeout_ms=_RECONCILE_BUSY_TIMEOUT_MS)
+ try:
+ with contextlib.suppress(Exception):
+ await init_db(engine)
+ finally:
+ with contextlib.suppress(Exception):
+ await engine.dispose()
+
+
+def _missing_sqlite_file(db_url: str) -> bool:
+ """True when *db_url* names a SQLite file that does not exist yet.
+
+ Only SQLite is checked: a server-backed URL has no file to create, and the
+ caller is not the component that decides whether that database should exist.
+ """
+ if not db_url.startswith("sqlite"):
+ return False
+ _, sep, tail = db_url.partition(":///")
+ if not sep or not tail or tail.startswith(":memory:"):
+ return False
+ return not Path(tail).exists()
+
+
def db_configured() -> bool:
"""True when ``REPOWISE_DB_URL`` or ``REPOWISE_DATABASE_URL`` is set.
diff --git a/packages/cli/src/repowise/cli/tool_bridge.py b/packages/cli/src/repowise/cli/tool_bridge.py
index ad04cd1cf..86e48390f 100644
--- a/packages/cli/src/repowise/cli/tool_bridge.py
+++ b/packages/cli/src/repowise/cli/tool_bridge.py
@@ -43,7 +43,7 @@ async def _acall_tool(
"""Wire tool state for *repo_path*, await ``factory()``, then tear down."""
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
- from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.cli.helpers import get_db_url_for_repo, reconcile_schema_best_effort
from repowise.core.persistence import FullTextSearch, create_engine
from repowise.server.chat_tools import init_tool_state
from repowise.server.mcp_server._failure_shield import _shape_exception
@@ -63,7 +63,14 @@ async def _acall_tool(
# opening the store and building the embedder all touch config and disk,
# and a failure there is the same condition from the caller's side.
try:
- engine = create_engine(get_db_url_for_repo(repo_path))
+ db_url = get_db_url_for_repo(repo_path)
+ # Mirrors the MCP server's lifespan (``_server.py``), which every tool
+ # reached through MCP already gets. Every tool's first query is
+ # ``select(Repository)``, so without this the whole CLI tool surface —
+ # ask, context, symbol, why, search, risk — fails on a raw
+ # ``no such column`` before it reads a single page.
+ await reconcile_schema_best_effort(db_url)
+ engine = create_engine(db_url)
session_factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
store = await _open_vector_store(repo_path)
init_tool_state(
diff --git a/packages/server/src/repowise/server/mcp_server/_failure_shield.py b/packages/server/src/repowise/server/mcp_server/_failure_shield.py
index 72c3dbdde..7b7cb1207 100644
--- a/packages/server/src/repowise/server/mcp_server/_failure_shield.py
+++ b/packages/server/src/repowise/server/mcp_server/_failure_shield.py
@@ -36,6 +36,11 @@ _WARMUP_TIMEOUT_S = 60.0
# message keeps _helpers.py free of any import back-reference to this module.
_NOT_INDEXED_MARKER = "No repositories found"
+# SQLite's wording when the ORM selects a column or table the store does not
+# have. Matched on the message rather than on an exception class so this module
+# keeps importing nothing from SQLAlchemy, the way it always has.
+_STALE_INDEX_MARKERS = ("no such column", "no such table")
+
def _shape_not_indexed() -> dict[str, Any]:
"""Success-shaped response for a repo that has never been indexed."""
@@ -68,6 +73,57 @@ def _shape_unknown_repo(exc: Exception) -> dict[str, Any]:
}
+def _driver_message(exc: Exception) -> str:
+ """The DBAPI error's own message, without SQLAlchemy's appended context.
+
+ ``str()`` on a SQLAlchemy ``OperationalError`` appends the compiled
+ statement and its bound parameters. For ``get_answer`` those parameters
+ include the user's question, so matching on the full string lets a caller
+ who merely *asks about* "no such column" be told their index is stale.
+ ``exc.orig`` is the driver exception alone.
+ """
+ orig = getattr(exc, "orig", None)
+ return str(exc if orig is None else orig).lower()
+
+
+def _is_stale_index_error(exc: Exception) -> bool:
+ """True for the ORM failure a store older than the models produces."""
+ if type(exc).__name__ != "OperationalError":
+ return False
+ return any(marker in _driver_message(exc) for marker in _STALE_INDEX_MARKERS)
+
+
+def _shape_stale_index(exc: Exception) -> dict[str, Any]:
+ """Success-shaped response for a store whose schema predates this repowise.
+
+ ``init_db`` back-fills *additive* drift on every read path, so reaching
+ here means the drift is the kind ``_reconcile_schema`` deliberately does
+ not touch (a removed or renamed column, a changed type — see
+ ``database.py``). The generic internal-error shape is the wrong answer for
+ it: it tells the caller to stop using the tool for the session, when one
+ ``repowise update`` fixes it.
+ """
+ return {
+ # The driver's own message: SQLAlchemy appends the whole compiled
+ # statement and its parameters, which is pages of SQL an agent cannot
+ # act on — and which carries the caller's own question back to them.
+ "error": (
+ "This repository's repowise index predates the installed "
+ f"repowise: {_driver_message(exc).splitlines()[0].strip()}"
+ ),
+ "remedy": (
+ "The user can rebuild it by running 'repowise update' in the repo "
+ "root. Re-indexing is the user's decision — suggest it once, do "
+ "not run it yourself."
+ ),
+ "guidance": (
+ "Until the index is rebuilt, every repowise tool will return this "
+ "notice. Answer questions about this repo with your built-in "
+ "tools (Read/Grep/Glob) for the rest of the session."
+ ),
+ }
+
+
def _shape_internal_error(tool: str, exc: Exception) -> dict[str, Any]:
"""Success-shaped response for an unexpected internal failure."""
return {
@@ -89,6 +145,8 @@ def _shape_exception(tool: str, exc: Exception) -> dict[str, Any]:
# [...]") from the registry — same expected condition, different type.
if isinstance(exc, ValueError) and str(exc).startswith("Unknown repo"):
return _shape_unknown_repo(exc)
+ if _is_stale_index_error(exc):
+ return _shape_stale_index(exc)
return _shape_internal_error(tool, exc)
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 f98aa1434..cd5df05fb 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
@@ -169,6 +169,7 @@ from repowise.server.mcp_server.tool_answer.symbols import (
_hydrate_symbols_for_hits,
_read_symbol_source,
build_homonym_union_bodies,
+ is_symbol_lookup_question,
union_defers_to_synthesis,
withheld_definitions,
)
@@ -1799,6 +1800,58 @@ async def get_answer(
if confidence == "high" and withheld_implicated:
confidence = "medium"
+ # Ninth gate — the LOOKUP half of the eighth, and a routing hole rather
+ # than a threshold problem. Gate 8 asks whether the question names a
+ # WITHHELD symbol; on a bare-name lookup it provably never can, because the
+ # question names the symbol that was SERVED and the withheld names are that
+ # symbol's own inner members. #1451 closed exactly this shape on the union
+ # path with a cap on truncation alone, on the grounds that where the caller
+ # asked for a symbol the bodies ARE the answer. But a name with a single
+ # definition never reaches the union path — `_anchor_symbol_hits`
+ # short-circuits at `len(cands) == 1` before `homonyms["union"]` is built —
+ # so it lands here with the same shape and, until now, no cap.
+ #
+ # Measured on the 2026-08-12 corpus: `ModelAdmin` (django) served 120 of
+ # 1,753 lines at `high`, 93% of the cited body withheld; `useSlider` (mui)
+ # 120 of 558, 78% withheld. Two trees, two languages. The dominance ratios
+ # (1.67x, 1.29x) are not the cause and are not touched.
+ #
+ # Deliberately narrow. It needs the question to read as a symbol lookup
+ # rather than prose, AND the truncated body to be the very symbol the
+ # question named. On a prose question the body is evidence
+ # for a claim rather than the answer itself, and truncation alone is a poor
+ # signal there (22% of truncations withhold nothing the response leans on),
+ # which is why gate 8 keeps the dependency test for that population.
+ # Kept as the entry rather than a flag so the note can quote the real served
+ # range and continuation instead of describing the cut in the abstract.
+ #
+ # `truncated` alone is not trustworthy enough to demote on. It is set by
+ # comparing the INDEXED end_line against what was read, while the read
+ # clamps to the end of the live file — so a symbol whose stored end
+ # overshoots (an unsupported language or a syntax error leaves
+ # `check_symbol_bounds` unverified, and a file that shrank since indexing
+ # does it too) is served WHOLE and still flagged. Requiring the served span
+ # to have hit the line cap says the cut was ours, which is the only case
+ # where something was really withheld.
+ named_body_cut = next(
+ (
+ b
+ for b in symbol_bodies
+ if b.get("truncated")
+ and b.get("continuation")
+ and b.get("name") in question_ids
+ and b["lines"][1] - b["lines"][0] + 1 >= _INLINE_BODY_MAX_LINES
+ ),
+ None,
+ )
+ lookup_body_truncated = (
+ confidence == "high"
+ and named_body_cut is not None
+ and is_symbol_lookup_question(question, question_ids)
+ )
+ if lookup_body_truncated:
+ confidence = "medium"
+
# Non-dominant ceiling: ambiguous retrieval is the calibration cost of
# always synthesizing — the answer may be right, but with no single dominant
# page it must never read "high" (cite without verifying). Cap at medium even
@@ -1960,23 +2013,80 @@ async def get_answer(
"participate beyond what the truncated symbol body shows."
)
elif withheld_implicated:
+ # A withheld entry whose name matches the body it was found in is
+ # the ENCLOSING symbol — served up to the cut and continuing past
+ # it — not a symbol that never arrived. Calling that "not served"
+ # is wrong about the payload directly above the note, and sends the
+ # caller to get_symbol for a body they already hold most of:
+ # `NewCmdRoot` lines 53-173 are in the payload and only 174-221 are
+ # missing. The accurate pointer is the `continuation` the entry
+ # already carries, which fetches just the missing part and is a
+ # valid get_symbol id in its own right ("path.py:174-221").
+ # Measured: 7 instances on 5 of 6 corpus trees.
+ _implicated = set(withheld_implicated)
+ _continuing = [
+ b
+ for b in symbol_bodies
+ if b.get("continuation")
+ and b.get("name") in _implicated
+ and any(s.get("name") == b.get("name") for s in (b.get("withheld_symbols") or []))
+ ]
+ _continuing_names = {b["name"] for b in _continuing}
+ _absent = [n for n in withheld_implicated if n not in _continuing_names]
_ids = [
s["symbol_id"]
for b in symbol_bodies
for s in (b.get("withheld_symbols") or [])
- if s.get("name") in set(withheld_implicated)
+ if s.get("name") in set(_absent)
]
+ _parts = []
+ if _absent:
+ _parts.append(
+ "Part of the code this answer depends on was not served: "
+ f"{', '.join(_absent)}."
+ + (
+ " Continue in this tool with "
+ f"get_symbol id='{_ids[0]}' before relying on the mechanism."
+ if _ids
+ else ""
+ )
+ )
+ # Qualify by path only when the same name was cut in more than one
+ # file, so the common case stays readable and the ambiguous case
+ # does not ship two sentences that look identical.
+ _dupe = len({_b["name"] for _b in _continuing}) < len(_continuing)
+ for _b in _continuing:
+ _who = f"{_b['name']} ({_b['path']})" if _dupe else _b["name"]
+ _parts.append(
+ f"{_who} was served through line {_b['lines'][1]}; the rest "
+ f"of its body is at {_b['continuation']}."
+ )
+ payload["note"] = " ".join(_parts)
+ payload["next_action_hint"] = (
+ f"call get_symbol id='{_ids[0]}' for the withheld body"
+ if _ids
+ else (
+ f"call get_symbol id='{_continuing[0]['continuation']}' for the rest "
+ f"of {_continuing[0]['name']}"
+ if _continuing
+ else "request the withheld body before citing"
+ )
+ )
+ elif lookup_body_truncated:
+ # The ninth gate fired: the caller asked for a symbol by name and
+ # its body did not fit. Without this the demotion would ship with
+ # no note at all, since the high-confidence branch below is now
+ # unreachable for it.
payload["note"] = (
- "Part of the code this answer depends on was not served: "
- f"{', '.join(withheld_implicated)}. Continue in this tool with "
- f"get_symbol id='{_ids[0]}' before relying on the mechanism."
- if _ids else
- "Part of the code this answer depends on was not served: "
- f"{', '.join(withheld_implicated)}."
+ f"You asked for {named_body_cut['name']} and its body did not fit: "
+ f"lines {named_body_cut['lines'][0]}-{named_body_cut['lines'][1]} are "
+ f"served and it continues at {named_body_cut['continuation']}. Held at "
+ "medium because on a symbol lookup the part you cannot see is part of "
+ "the answer."
)
payload["next_action_hint"] = (
- f"call get_symbol id='{_ids[0]}' for the withheld body"
- if _ids else "request the withheld body before citing"
+ f"call get_symbol id='{named_body_cut['continuation']}' for the rest of "
+ f"{named_body_cut['name']}"
)
elif confidence == "high":
# The rationale deliberately no longer cites "the answer is direct
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 037fb8eb0..09eaaa5df 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
@@ -375,7 +375,16 @@ _HIGH_CONFIDENCE_SCORE_FLOOR = 1.5
# payload that admits it withheld part of a cited body. Cached pre-v13 rows
# carry both the old `high` and the old "do not re-read the source" note, which
# is precisely what this version exists to stop serving, so they must bypass.
-_ANSWER_SCHEMA_VERSION = 13
+# v14: the LOOKUP half of v13. v13 capped the homonym-union path on truncation
+# alone, but a name with exactly ONE definition never reaches that path, so a
+# bare-symbol-name question about a uniquely-defined symbol still graded `high`
+# with most of the cited body withheld (measured: 93% and 78% withheld, on two
+# trees and two languages). It is now capped the same way. Separately, a
+# withheld entry naming the very symbol the payload already served is described
+# by its `continuation` range instead of being reported as "not served" with a
+# get_symbol pointer to a body the caller already holds most of. Cached pre-v14
+# rows carry both the old `high` and the old note, so they must bypass.
+_ANSWER_SCHEMA_VERSION = 14
# Hard TTL on answer-cache rows. Commit-based invalidation (the payload's
# stamped ``_indexed_commit`` vs the repo's current head) is the primary
diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py b/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py
index 1b455525f..a70fdd93f 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/symbols.py
@@ -106,6 +106,35 @@ def union_defers_to_synthesis(
return _prose_dominates(question, list(question_ids))
+def is_symbol_lookup_question(question: str, question_ids: set[str]) -> bool:
+ """True when the question IS the symbol names, not prose that mentions them.
+
+ ``ModelAdmin`` is a lookup; "how does ModelAdmin dispatch a request" is
+ prose that merely names one. The distinction matters wherever the question
+ is whether a served BODY is the answer: for a lookup it is, so truncating
+ it is a loss on its own; for prose the body is evidence for a claim, and
+ truncation alone says little (22% of truncations withhold nothing the
+ response leans on).
+
+ **Stricter than ``_prose_dominates``, deliberately.** That predicate counts
+ ``[A-Za-z0-9_]+`` tokens, so a question written in Cyrillic, Japanese or
+ Chinese tokenises to nothing but its identifiers and reads as a bare
+ lookup — and repowise ships an output-language feature, so those callers
+ exist. It also misreads dense English ("Why does ModelAdmin call
+ get_queryset, get_form and save_model?" is 4 identifiers in 7 tokens).
+ Removing the identifiers and asking whether any word character survives is
+ script-independent and says what "bare lookup" actually means.
+ """
+ if not question_ids:
+ return False
+ residual = question
+ for ident in sorted(question_ids, key=len, reverse=True):
+ residual = residual.replace(ident, " ")
+ if re.search(r"\w", residual, re.UNICODE):
+ return False
+ return not _prose_dominates(question, list(question_ids))
+
+
def _read_repo_text(repo_root: Path | None, file_path: str) -> str | None:
"""Read a repo file's live text, refusing paths outside the root.
@@ -992,6 +1021,22 @@ def _match_definition(raw: str, next_raw: str = "") -> re.Match[str] | None:
# An anonymous function passed as an argument, in either syntax.
if "=>" in raw[: m.end()] or "function" in raw[: m.end()]:
continue
+ # Go's third spelling of the same thing: ``func(req *http.Request)
+ # (*http.Response, error) {``. There is no space after ``func``, so
+ # the optional return-type group matches empty and the name group
+ # takes the keyword itself, yielding an unresolvable ``path::func``.
+ # This cannot be handled by either general-purpose set above:
+ # ``_RESERVED_NAMES`` is tested for every pattern and ``def func():``
+ # is a real Python definition (41 of them in django alone), while
+ # ``_NOT_A_DEFINITION`` is also tested against the line's FIRST
+ # word, which is ``func`` on every named Go function too.
+ #
+ # Requiring ``func`` to open the line is what keeps it to the Go
+ # literal: ``int func(int a) {`` is a real definition named ``func``
+ # in C, C++, Java, C# and Kotlin, and a name-only test suppresses
+ # all five.
+ if m.group("name") == "func" and head and head.group(0) == "func":
+ continue
# Allman: the brace is on the next line. A declaration never ends in
# a comma, but an argument on its own line inside a multi-line call
# does -- and when the following argument is a dict literal, the
diff --git a/tests/unit/cli/test_tool_bridge.py b/tests/unit/cli/test_tool_bridge.py
index d97007da3..d296000ac 100644
--- a/tests/unit/cli/test_tool_bridge.py
+++ b/tests/unit/cli/test_tool_bridge.py
@@ -18,6 +18,7 @@ from repowise.cli import tool_bridge
class _FakeEngine:
def __init__(self) -> None:
self.disposed = False
+ self.reconciled = False
async def dispose(self) -> None:
self.disposed = True
@@ -41,6 +42,11 @@ def wired(monkeypatch, tmp_path):
monkeypatch.setattr(
"repowise.core.persistence.create_engine", lambda url: engine, raising=False
)
+
+ async def _fake_reconcile(eng):
+ engine.reconciled = True
+
+ monkeypatch.setattr("repowise.cli.helpers.reconcile_schema_best_effort", _fake_reconcile)
monkeypatch.setattr(
"repowise.core.persistence.FullTextSearch", lambda eng: ("fts", eng), raising=False
)
@@ -218,6 +224,150 @@ def test_a_repo_whose_embedder_key_went_away_is_recorded_as_degraded(
assert "openai" in status["reason"]
+def test_a_store_one_repowise_older_than_the_models_is_still_readable(monkeypatch, tmp_path):
+ """A real store missing a column the models gained must not hard-fail.
+
+ Not a fake engine: this builds an actual SQLite store, drops a column from
+ it, and drives the whole bridge. Every tool's first query is
+ ``select(Repository)``, so before ``init_db`` was paired with
+ ``create_engine`` here the entire CLI tool surface — ask, context, symbol,
+ why, search, risk — came back as a raw ``no such column`` OperationalError
+ whose shaped guidance told the caller to stop using the tool.
+ """
+ import asyncio
+ import sqlite3
+
+ from sqlalchemy import select
+
+ from repowise.core.persistence import create_engine, init_db
+ from repowise.core.persistence.models import Repository
+ from repowise.server.mcp_server import _state
+
+ db_file = tmp_path / "wiki.db"
+ url = f"sqlite+aiosqlite:///{db_file}"
+
+ async def _build():
+ engine = create_engine(url)
+ await init_db(engine)
+ await engine.dispose()
+
+ asyncio.run(_build())
+
+ # Roll the store back one schema version, the way a store built by an
+ # older repowise is. 17 columns is current, 16 is legacy.
+ conn = sqlite3.connect(db_file)
+ conn.execute("ALTER TABLE repositories DROP COLUMN churn_anchor_sha")
+ conn.commit()
+ stale_cols = {r[1] for r in conn.execute("pragma table_info(repositories)")}
+ conn.close()
+ assert "churn_anchor_sha" not in stale_cols
+
+ monkeypatch.setattr("repowise.cli.helpers.get_db_url_for_repo", lambda p: url)
+
+ async def _fake_open(repo_path):
+ return None
+
+ monkeypatch.setattr(tool_bridge, "_open_vector_store", _fake_open)
+
+ async def _tool():
+ async with _state._session_factory() as session:
+ await session.execute(select(Repository).limit(1))
+ return {"ok": True}
+
+ assert tool_bridge.call_tool(tmp_path, _tool, "get_answer") == {"ok": True}
+
+ conn = sqlite3.connect(db_file)
+ healed = {r[1] for r in conn.execute("pragma table_info(repositories)")}
+ conn.close()
+ assert "churn_anchor_sha" in healed
+
+
+def test_a_store_that_cannot_be_repaired_still_serves_the_read(monkeypatch, tmp_path):
+ """Reconciling is opportunistic; a failed repair must not fail the call.
+
+ Measured while reviewing the fix: a read-only store, and a store whose
+ write lock is held by a concurrent ``repowise update``, both make the
+ ``ALTER TABLE`` raise. Aborting there would be a regression — a store
+ already on the current schema needs no DDL and reads fine either way, so
+ the repair failing says nothing about whether the read can succeed.
+ """
+ import asyncio
+
+ from repowise.cli import helpers
+
+ db = tmp_path / "wiki.db"
+ db.write_text("not a database", encoding="utf-8")
+
+ async def _explode(_engine):
+ raise RuntimeError("attempt to write a readonly database")
+
+ monkeypatch.setattr("repowise.core.persistence.init_db", _explode, raising=False)
+ # Must not raise.
+ asyncio.run(helpers.reconcile_schema_best_effort(f"sqlite+aiosqlite:///{db}"))
+
+
+def test_the_repair_never_creates_a_store_that_did_not_exist(tmp_path):
+ """A read command in an un-indexed repo must not leave a database behind.
+
+ ``init_db`` on a fresh path materialises the full 42-table schema, so
+ without this guard ``repowise ask`` in a repo that was never indexed writes
+ a ~512 KB ``wiki.db`` where the user expects "not indexed yet".
+ """
+ import asyncio
+
+ from repowise.cli import helpers
+
+ db = tmp_path / "wiki.db"
+ asyncio.run(helpers.reconcile_schema_best_effort(f"sqlite+aiosqlite:///{db}"))
+ assert not db.exists(), "the repair created a store where none existed"
+
+
+def test_the_repair_is_bounded_when_the_store_is_locked(tmp_path):
+ """It must fail fast, not inherit the 30s bulk-write window.
+
+ ``status`` opens four engines and ``doctor`` five. At the engine default a
+ store locked by a concurrent ``repowise update`` stalled ``status`` for
+ ~133s in silence — swallowing the exception does not swallow the wait.
+ """
+ import asyncio
+ import sqlite3
+ import time
+
+ from repowise.cli import helpers
+ from repowise.core.persistence import create_engine, init_db
+
+ db = tmp_path / "wiki.db"
+ url = f"sqlite+aiosqlite:///{db}"
+
+ async def _build():
+ engine = create_engine(url)
+ await init_db(engine)
+ await engine.dispose()
+
+ asyncio.run(_build())
+ # Real drift, so the repair has DDL to issue and must take the write lock.
+ conn = sqlite3.connect(db)
+ conn.execute("ALTER TABLE repositories DROP COLUMN churn_anchor_sha")
+ conn.commit()
+ conn.close()
+
+ holder = sqlite3.connect(db, isolation_level=None, timeout=1)
+ holder.execute("BEGIN EXCLUSIVE")
+ holder.execute("UPDATE repositories SET name = name")
+ try:
+ t0 = time.perf_counter()
+ asyncio.run(helpers.reconcile_schema_best_effort(url))
+ elapsed = time.perf_counter() - t0
+ finally:
+ holder.execute("ROLLBACK")
+ holder.close()
+
+ assert elapsed < 10, (
+ f"the contended repair took {elapsed:.1f}s; the engine default is 30s and "
+ "status calls this four times"
+ )
+
+
def test_a_repo_that_asked_for_keyless_is_not_reported_as_degraded(
monkeypatch, tmp_path, restore_embedder_status
):
diff --git a/tests/unit/server/mcp/test_answer_lookup_truncation.py b/tests/unit/server/mcp/test_answer_lookup_truncation.py
new file mode 100644
index 000000000..66b30cd15
--- /dev/null
+++ b/tests/unit/server/mcp/test_answer_lookup_truncation.py
@@ -0,0 +1,370 @@
+"""The lookup half of the withheld-body calibration (#1451's blind spot).
+
+#1451 capped confidence on the homonym-union path whenever any cited body was
+truncated, on the grounds that where a caller asked for a symbol the bodies ARE
+the answer. But a name with exactly ONE definition never reaches that path —
+``_anchor_symbol_hits`` short-circuits at ``len(cands) == 1`` before
+``homonyms["union"]`` is built — so a bare-name question about a uniquely
+defined symbol fell through to synthesis and kept ``high`` with most of the
+cited body withheld. Measured on the 2026-08-12 corpus: 93% withheld on
+``ModelAdmin`` (django) and 78% on ``useSlider`` (mui).
+
+Proof direction:
+ test_a_bare_lookup_whose_body_was_cut_is_not_high — FAILS at the parent.
+ test_a_lookup_whose_body_fits_stays_high — passes both (control).
+ test_a_prose_question_is_not_capped_by_truncation — passes both (control:
+ truncation alone must stay insufficient outside a lookup, per gate 8).
+
+The second file covered here is D6: when the withheld entry names the very
+symbol the payload already served, the note must describe it by its
+``continuation`` range rather than reporting it as "not served".
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+# 120 lines is _INLINE_BODY_MAX_LINES, so an end_line far past the excerpt makes
+# the body entry come back truncated with a continuation.
+_CUT_SYMBOL = {
+ "name": "min_count_policy",
+ "kind": "function",
+ "signature": "def min_count_policy() -> int",
+ "docstring": "Returns the default minimum count.",
+ "start_line": 10,
+ "end_line": 900,
+ "_matched": True,
+ "source_excerpt": "def min_count_policy() -> int:\n # gate retries\n return MIN_COUNT",
+}
+
+_WHOLE_SYMBOL = {
+ "name": "min_count_policy",
+ "kind": "function",
+ "signature": "def min_count_policy() -> int",
+ "docstring": "Returns the default minimum count.",
+ "start_line": 10,
+ "end_line": 12,
+ "_matched": True,
+ "source_excerpt": "def min_count_policy() -> int:\n # gate retries\n return MIN_COUNT",
+}
+
+
+def _patch_pipeline(monkeypatch, answer_mod, *, symbol: dict, path: str | None = None):
+ async def _fake_retrieve(question, ctx):
+ return [
+ {"page_id": "file_page:pkg/alpha/one.py", "score": 5.0},
+ {"page_id": "file_page:pkg/alpha/two.py", "score": 1.0},
+ ]
+
+ async def _fake_hydrate(hits, ctx, *, scope=None):
+ for i, h in enumerate(hits):
+ h["target_path"] = path or h["page_id"].removeprefix("file_page:")
+ h["title"] = h["target_path"]
+ h["summary"] = "Policy module summary."
+ h["snippet"] = ""
+ h["page_type"] = "file_page"
+ if i == 0:
+ h["symbols"] = [dict(symbol)]
+ return hits
+
+ monkeypatch.setattr(answer_mod, "_hybrid_retrieve", _fake_retrieve)
+ monkeypatch.setattr(answer_mod, "_hydrate_hits", _fake_hydrate)
+
+
+def _patch_provider(monkeypatch, answer_mod, content: str):
+ class _Provider:
+ provider_name = "mock"
+ model_name = "mock-1"
+
+ async def generate(self, **kwargs):
+ return SimpleNamespace(content=content)
+
+ monkeypatch.setattr(answer_mod, "_resolve_provider_for_answer", lambda _p: _Provider())
+
+
+class TestLookupPredicate:
+ """``is_symbol_lookup_question`` — the routing test the gate keys on."""
+
+ def test_a_bare_symbol_name_is_a_lookup(self) -> None:
+ from repowise.server.mcp_server.tool_answer.symbols import is_symbol_lookup_question
+
+ assert is_symbol_lookup_question("ModelAdmin", {"ModelAdmin"})
+
+ def test_prose_naming_a_symbol_is_not_a_lookup(self) -> None:
+ from repowise.server.mcp_server.tool_answer.symbols import is_symbol_lookup_question
+
+ assert not is_symbol_lookup_question(
+ "how does ModelAdmin build its changelist form", {"ModelAdmin"}
+ )
+
+ def test_prose_in_a_non_latin_script_is_not_a_lookup(self) -> None:
+ """`_prose_dominates` counts [A-Za-z0-9_], so a Cyrillic or CJK question
+ tokenises to nothing but its identifiers and read as a bare lookup —
+ capping a genuine prose question and telling the caller "you asked for
+ X" when they did not. repowise ships an output-language feature, so
+ these callers exist."""
+ from repowise.server.mcp_server.tool_answer.symbols import is_symbol_lookup_question
+
+ for q in (
+ "Как работает ModelAdmin в этом коде?",
+ "ModelAdmin はこのコードでどのように動作しますか",
+ "ModelAdmin 在这段代码中是如何工作的",
+ ):
+ assert not is_symbol_lookup_question(q, {"ModelAdmin"}), q
+
+ def test_dense_english_prose_is_not_a_lookup(self) -> None:
+ """4 identifiers in 7 tokens beats the ratio test but is still prose."""
+ from repowise.server.mcp_server.tool_answer.symbols import is_symbol_lookup_question
+
+ assert not is_symbol_lookup_question(
+ "Why does ModelAdmin call get_queryset, get_form and save_model?",
+ {"ModelAdmin", "get_queryset", "get_form", "save_model"},
+ )
+
+ def test_a_bare_name_with_punctuation_is_still_a_lookup(self) -> None:
+ from repowise.server.mcp_server.tool_answer.symbols import is_symbol_lookup_question
+
+ assert is_symbol_lookup_question("ModelAdmin?", {"ModelAdmin"})
+ assert is_symbol_lookup_question("get_form ModelAdmin", {"ModelAdmin", "get_form"})
+
+ def test_a_question_naming_no_symbol_is_not_a_lookup(self) -> None:
+ """Guards the empty-identifier case: ``_prose_dominates`` returns False
+ when there are no identifiers at all, which would otherwise read as
+ 'this is a lookup' for every identifier-free question."""
+ from repowise.server.mcp_server.tool_answer.symbols import is_symbol_lookup_question
+
+ assert not is_symbol_lookup_question("how do i run the tests", set())
+
+
+def _write_oversized_symbol(tmp_path, monkeypatch, *, name="min_count_policy", body_lines=300):
+ """A real file whose function genuinely runs past _INLINE_BODY_MAX_LINES.
+
+ Needed rather than a short `source_excerpt`: the gate requires the served
+ span to have hit the 120-line cap, because that is what distinguishes a cut
+ we made from a stale indexed end_line over a body that fits.
+ """
+ import repowise.server.mcp_server as mcp_mod
+
+ src = ["import os", ""]
+ src.append(f"def {name}():")
+ src += [f" step_{i} = {i}" for i in range(body_lines)]
+ src.append(" return step_0")
+ (tmp_path / "policy.py").write_text("\n".join(src) + "\n", encoding="utf-8")
+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))
+ return {
+ "name": name,
+ "kind": "function",
+ "signature": f"def {name}()",
+ "docstring": "Gate retries.",
+ "start_line": 3,
+ "end_line": len(src),
+ "_matched": True,
+ "source_excerpt": f"def {name}():\n step_0 = 0",
+ }
+
+
+async def test_a_bare_lookup_whose_body_was_cut_is_not_high(setup_mcp, monkeypatch, tmp_path):
+ """FAILS at the parent. The D4 shape, in one fixture.
+
+ Bare name, one definition, body genuinely longer than the inline cap. Gate
+ 8 cannot save this: it fires on a withheld symbol the QUESTION names or the
+ ANSWER references, and here the question names the symbol that was SERVED.
+ """
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.server.mcp_server import get_answer
+
+ symbol = _write_oversized_symbol(tmp_path, monkeypatch)
+ _patch_pipeline(monkeypatch, answer_mod, symbol=symbol, path="policy.py")
+ _patch_provider(monkeypatch, answer_mod, "min_count_policy returns the configured floor.")
+
+ result = await get_answer("min_count_policy")
+
+ bodies = result.get("symbol_bodies") or []
+ assert any(b.get("truncated") for b in bodies), (
+ "fixture is vacuous: nothing was truncated, so the gate had nothing to fire on"
+ )
+ assert bodies[0]["lines"][1] - bodies[0]["lines"][0] + 1 >= 120, (
+ "fixture is vacuous: the body did not reach the inline cap, so the cut "
+ "was not ours and the gate is right to ignore it"
+ )
+ assert result["confidence"] != "high", (
+ "A bare symbol lookup whose only definition arrived truncated must not "
+ f"read 'high'; got {result['confidence']!r}"
+ )
+ # The note must point at the part that is missing, not re-fetch the whole.
+ # Either the ninth gate's own note or the reworded gate-8 note may carry
+ # this — with a real file on disk the enclosing symbol is also the headline
+ # withheld entry, so gate 8 fires first. Both are correct, and both must
+ # point at the continuation rather than at the whole body.
+ cont = bodies[0]["continuation"]
+ assert cont in result.get("note", ""), result.get("note")
+ assert f"get_symbol id='{cont}'" in (result.get("next_action_hint") or ""), (
+ result.get("next_action_hint")
+ )
+
+
+async def test_a_stale_end_line_does_not_cap_a_body_that_was_served_whole(
+ setup_mcp, monkeypatch, tmp_path
+):
+ """`truncated` is not by itself evidence that anything was withheld.
+
+ It compares the INDEXED end_line against what was read, while the read
+ clamps to the end of the live file. A symbol whose stored end overshoots —
+ `check_symbol_bounds` leaves bounds unverified for an unsupported language
+ or a syntax error, and a file that shrank since indexing does it too — is
+ served in full and still flagged. Capping on that would demote a complete
+ answer and print a continuation that points past EOF.
+ """
+ import repowise.server.mcp_server as mcp_mod
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.server.mcp_server import get_answer
+
+ (tmp_path / "policy.py").write_text(
+ "\n".join(
+ ["import os", ""] * 4
+ + ["def min_count_policy():", " # gate retries", " return 3"]
+ )
+ + "\n",
+ encoding="utf-8",
+ )
+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))
+
+ stale = dict(_CUT_SYMBOL)
+ stale["start_line"] = 9
+ stale["end_line"] = 900 # the file has 11 lines
+
+ _patch_pipeline(monkeypatch, answer_mod, symbol=stale, path="policy.py")
+ _patch_provider(monkeypatch, answer_mod, "min_count_policy returns the configured floor.")
+
+ result = await get_answer("min_count_policy")
+
+ body = (result.get("symbol_bodies") or [{}])[0]
+ served = body["lines"][1] - body["lines"][0] + 1
+ assert served < 120, f"fixture is vacuous: {served} lines served, cap is 120"
+ assert result["confidence"] == "high", (
+ "the whole live symbol is in the payload; a stale indexed end_line must "
+ f"not demote it. Got {result['confidence']!r}, note={result.get('note')!r}"
+ )
+
+
+async def test_a_lookup_whose_body_fits_stays_high(setup_mcp, monkeypatch):
+ """Control. The cap is about truncation, not about lookups being suspect."""
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.server.mcp_server import get_answer
+
+ _patch_pipeline(monkeypatch, answer_mod, symbol=_WHOLE_SYMBOL)
+ _patch_provider(monkeypatch, answer_mod, "min_count_policy returns the configured floor.")
+
+ result = await get_answer("min_count_policy")
+
+ assert not any(b.get("truncated") for b in (result.get("symbol_bodies") or []))
+ assert result["confidence"] == "high", result["confidence"]
+
+
+async def test_the_served_symbol_is_described_by_its_continuation_not_as_unserved(
+ setup_mcp, monkeypatch, tmp_path
+):
+ """D6. FAILS at the parent: the note reports a served symbol as unserved.
+
+ When the truncated body IS the enclosing symbol, that symbol is correctly
+ the headline ``withheld_symbols`` entry — its body continues past the cut —
+ and the note then described it as code that "was not served" and told the
+ caller to ``get_symbol`` it, while the payload directly above already held
+ most of it. Live shape (cli/cli): ``NewCmdRoot`` lines 53-173 served,
+ 174-221 withheld, and both note and hint said to fetch ``NewCmdRoot``.
+ 7 instances on 5 of 6 corpus trees, the most frequent issue measured.
+
+ Needs a real file on disk: the enclosing-symbol entry comes from
+ ``withheld_definitions`` walking back over live source.
+ """
+ import repowise.server.mcp_server as mcp_mod
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.server.mcp_server import get_answer
+
+ src = ["import os", ""]
+ src.append("def big_handler(request):")
+ src.append(' """Handle it."""')
+ for i in range(300):
+ src.append(f" step_{i} = {i}")
+ src.append(" return step_0")
+ (tmp_path / "handler.py").write_text("\n".join(src) + "\n", encoding="utf-8")
+ monkeypatch.setattr(mcp_mod, "_repo_path", str(tmp_path))
+
+ symbol = {
+ "name": "big_handler",
+ "kind": "function",
+ "signature": "def big_handler(request)",
+ "docstring": "Handle it.",
+ "start_line": 3,
+ "end_line": len(src),
+ "_matched": True,
+ "source_excerpt": "def big_handler(request):\n step_0 = 0",
+ }
+
+ async def _fake_retrieve(question, ctx):
+ return [{"page_id": "file_page:handler.py", "score": 5.0}]
+
+ async def _fake_hydrate(hits, ctx, *, scope=None):
+ for h in hits:
+ h["target_path"] = "handler.py"
+ h["title"] = "handler.py"
+ h["summary"] = "Handler module."
+ h["snippet"] = ""
+ h["page_type"] = "file_page"
+ h["symbols"] = [dict(symbol)]
+ return hits
+
+ monkeypatch.setattr(answer_mod, "_hybrid_retrieve", _fake_retrieve)
+ monkeypatch.setattr(answer_mod, "_hydrate_hits", _fake_hydrate)
+ _patch_provider(monkeypatch, answer_mod, "big_handler runs each step in order.")
+
+ result = await get_answer("big_handler")
+
+ body = (result.get("symbol_bodies") or [{}])[0]
+ assert body.get("truncated") and body.get("continuation"), result.get("symbol_bodies")
+ assert any(
+ s.get("name") == "big_handler" for s in (body.get("withheld_symbols") or [])
+ ), "fixture is vacuous: the enclosing symbol is not the withheld entry"
+
+ note = result.get("note") or ""
+ hint = result.get("next_action_hint") or ""
+ assert "big_handler was not served" not in note, note
+ assert "not served: big_handler" not in note, note
+ # The accurate pointer is the continuation, which fetches only the part the
+ # caller is actually missing.
+ assert body["continuation"] in note, note
+ assert body["continuation"] in hint, hint
+ assert "handler.py::big_handler" not in hint, hint
+
+
+async def test_a_prose_question_is_not_capped_by_truncation_alone(setup_mcp, monkeypatch):
+ """Control, and the reason the gate is narrow.
+
+ Outside a lookup the body is evidence for a claim rather than the answer
+ itself, and 22% of truncations withhold nothing the response leans on —
+ which is why gate 8 keeps the dependency test for this population. The
+ answer text here names no withheld symbol, so nothing should downgrade it.
+ """
+ import repowise.server.mcp_server.tool_answer.answer as answer_mod
+ from repowise.server.mcp_server import get_answer
+
+ _patch_pipeline(monkeypatch, answer_mod, symbol=_CUT_SYMBOL)
+ _patch_provider(
+ monkeypatch, answer_mod, "The retry loop is gated by min_count_policy at startup."
+ )
+
+ result = await get_answer(
+ "how does the retry loop decide its floor using min_count_policy at startup"
+ )
+
+ assert result["confidence"] == "high", (
+ "truncation alone must not cap a prose question; that is gate 8's job "
+ f"and it needs a dependency. Got {result['confidence']!r}"
+ )
diff --git a/tests/unit/server/mcp/test_answer_withheld_symbols.py b/tests/unit/server/mcp/test_answer_withheld_symbols.py
index 90ff1080a..2fca7b8f2 100644
--- a/tests/unit/server/mcp/test_answer_withheld_symbols.py
+++ b/tests/unit/server/mcp/test_answer_withheld_symbols.py
@@ -725,6 +725,82 @@ def test_go_definitions_are_found(tmp_path) -> None:
assert "for" not in names
+def test_a_go_anonymous_func_literal_is_not_a_symbol_named_func(tmp_path) -> None:
+ """141 of 23,038 sweep entries on cli/cli, one of them the headline.
+
+ ``func(`` has no space after the keyword, so the brace-member pattern's
+ optional return-type group matches empty and the name group takes ``func``
+ itself — an unresolvable ``d.go::func`` that the note then tells the agent
+ to fetch. The named function around it must still be reported.
+ """
+ from repowise.server.mcp_server.tool_answer.symbols import withheld_definitions
+
+ (tmp_path / "rt.go").write_text(
+ "package main\n"
+ "\n"
+ "func NewClient(t *testing.T) *http.Client {\n"
+ "\treg := &httpmock.Registry{}\n"
+ "\treg.Register(\n"
+ "\t\thttpmock.REST(\"GET\", \"repos/o/r\"),\n"
+ "\t\tfunc(req *http.Request) (*http.Response, error) {\n"
+ "\t\t\treturn nil, nil\n"
+ "\t\t},\n"
+ "\t)\n"
+ "\treturn reg.Client()\n"
+ "}\n",
+ encoding="utf-8",
+ )
+ got = withheld_definitions(tmp_path, "rt.go:5-12")
+ names = [d["name"] for d in got]
+ assert "func" not in names, names
+ # Not vacuous: the enclosing named function is still found, so the guard
+ # is rejecting the literal rather than the whole file.
+ assert names and names[0] == "NewClient" and got[0]["body_continues"] is True
+
+
+def test_a_python_function_actually_named_func_is_still_reported(tmp_path) -> None:
+ """The reason ``func`` cannot simply join ``_RESERVED_NAMES``.
+
+ That set is consulted for every pattern, and ``def func(...)`` is a real
+ definition — 41 of them in django alone.
+ """
+ from repowise.server.mcp_server.tool_answer.symbols import withheld_definitions
+
+ (tmp_path / "fn.py").write_text(
+ "import functools\n"
+ "\n"
+ "\n"
+ "def func(a, b):\n"
+ " total = a + b\n"
+ " return total\n",
+ encoding="utf-8",
+ )
+ names = [d["name"] for d in withheld_definitions(tmp_path, "fn.py:5-6")]
+ assert "func" in names, names
+
+
+def test_a_c_style_function_actually_named_func_is_still_reported(tmp_path) -> None:
+ """The reason the guard requires ``func`` to OPEN the line.
+
+ ``int func(int a) {`` is a real definition named ``func`` in C, C++, Java,
+ C# and Kotlin, and it reaches the same brace-member pattern the Go literal
+ does. A name-only test suppresses all five languages.
+ """
+ from repowise.server.mcp_server.tool_answer.symbols import withheld_definitions
+
+ (tmp_path / "u.c").write_text(
+ "#include <stdio.h>\n"
+ "\n"
+ "int func(int a) {\n"
+ " int total = a + 1;\n"
+ " return total;\n"
+ "}\n",
+ encoding="utf-8",
+ )
+ names = [d["name"] for d in withheld_definitions(tmp_path, "u.c:4-6")]
+ assert "func" in names, names
+
+
def test_java_members_are_found(tmp_path) -> None:
from repowise.server.mcp_server.tool_answer.symbols import withheld_definitions
diff --git a/tests/unit/server/mcp/test_failure_shield.py b/tests/unit/server/mcp/test_failure_shield.py
index 5aeab214e..996eb6b20 100644
--- a/tests/unit/server/mcp/test_failure_shield.py
+++ b/tests/unit/server/mcp/test_failure_shield.py
@@ -72,6 +72,73 @@ async def test_workspace_unknown_repo_valueerror_is_success_shaped():
assert "Retry" not in result.get("guidance", "")
+async def test_a_store_older_than_the_models_says_run_update_not_give_up():
+ """Drift ``init_db`` cannot repair must not read as an internal crash.
+
+ Every read path now reconciles *additive* drift, so a ``no such column``
+ that still reaches here is the kind ``_reconcile_schema`` deliberately
+ skips — a removed or renamed column, a changed type. The generic shape
+ tells the caller to stop using the tool for the rest of the session, which
+ is the worst possible advice when one ``repowise update`` fixes it.
+ """
+ from sqlalchemy.exc import OperationalError
+
+ async def stale_store_tool() -> dict:
+ raise OperationalError(
+ "SELECT repositories.churn_anchor_sha FROM repositories",
+ {},
+ Exception("no such column: repositories.churn_anchor_sha"),
+ )
+
+ result = await shield(stale_store_tool)()
+
+ assert "predates the installed repowise" in result["error"]
+ # First line only — SQLAlchemy appends the whole compiled statement.
+ assert "\n" not in result["error"]
+ assert "repowise update" in result["remedy"]
+ assert "user" in result["remedy"]
+ assert "Retry this call once" not in result.get("guidance", "")
+
+
+async def test_an_unrelated_operationalerror_keeps_the_internal_error_shape():
+ """The stale-index branch is keyed on the message, so guard the negative."""
+ from sqlalchemy.exc import OperationalError
+
+ async def locked_db_tool() -> dict:
+ raise OperationalError("SELECT 1", {}, Exception("database is locked"))
+
+ result = await shield(locked_db_tool)()
+
+ assert "predates" not in result["error"]
+ assert "Retry this call once" in result["guidance"]
+
+
+async def test_the_users_own_question_cannot_fake_a_stale_index():
+ """`str()` on a SQLAlchemy error appends the statement AND its parameters.
+
+ `get_answer` binds the caller's question as a parameter, so matching the
+ full string let someone who merely ASKS about "no such column" be told
+ their index is stale and to re-index — over what is really a transient
+ lock. Match the driver's own message instead.
+ """
+ from sqlalchemy.exc import OperationalError
+
+ async def locked_while_asking_about_columns() -> dict:
+ raise OperationalError(
+ "INSERT INTO answer_cache (question, payload) VALUES (?, ?)",
+ ("why do I get no such column errors when I upgrade?", "{}"),
+ Exception("database is locked"),
+ )
+
+ result = await shield(locked_while_asking_about_columns)()
+
+ assert "predates" not in result["error"], result["error"]
+ assert "Retry this call once" in result["guidance"]
+
+
@pytest.mark.asyncio
async def test_unexpected_exception_is_success_shaped():
async def exploding_tool(x: int) -> dict: