tools_query.py¶
clew/mcp_server/tools_query.py
R3 tier-1 tools: thin MCP wrappers, 1:1 with the R2 query library.
_answered
dict[str, Any] clew.mcp_server.tools_query.QueryTools._answered(self, dict[str, Any]|None payload, *str kind="result", str|None subject=None, str|None target=None, str|None sub_index=None)
Stamp a reply with the target it came from, making a miss self-describing.
clew/mcp_server/tools_query.py:1322
Called by _batched_dossiers, _config_space, _corpus, _lock_inventory, dossier, graph_stats
Calls _bounded_names, _default, _kind_limitation_clause, _recovery_for, _route, _scope_definitive, _scope_hit, _staleness, _target_name, _unresolved_for, _withdraw_definitive
Source · 107 lines
def _answered(
self,
payload: dict[str, Any] | None,
*,
kind: str = "result",
subject: str | None = None,
target: str | None = None,
sub_index: str | None = None,
) -> dict[str, Any]:
"""EVERY REPLY NAMES THE REPOSITORY IT ANSWERED FROM (gh#22). The server no
longer holds a target it was told to hold — it derives one — so "which
repository is this?" has to be answerable from the payload rather than from a
launch argument nobody can see. A stale target that no reply disclosed has
already invalidated a 36-cell benchmark run: 15 of 18 cells said in prose that
they were looking at the wrong repository, and all 36 were recorded valid.
AND IT TURNS A BARE `None` INTO AN ENVELOPE, for the same reason `_many` turns
a bare `[]` into one. A `None` from `dossier` means "not in this index", which
is indistinguishable from "malformed call" — and it is the reply where the
target matters MOST, because the commonest cause of a missing symbol is an
index of the wrong repository. Returning None there would omit the attribution
from precisely the case that motivated it.
`found` is present only on a miss; a caller discriminates on it or on `note`,
the same convention `_many` already uses for an empty list.
AND IT CARRIES STALENESS, WHEN THERE IS ANY (gh#2). Same argument as the target
stamp, one axis over: a payload should say what produced it, and "an index built
before the edit you just made" is as much a property of what produced an answer as
the repository is. `status` already said so, but only if asked — and a consumer
looking at a confident, fresh-LOOKING answer has no reason to ask.
ABSENT WHEN THE TOOL IS CURRENT, which is the half that keeps it worth reading.
An annotation on every reply is an annotation nobody reads, and this repo's own
record is that a warning which fires on the ordinary case gets ignored and then
gets switched off.
AND THE STAMP IS THE ROUTED REPOSITORY WHEN THE CALL NAMED ONE, resolved once here
and used for both the name and the staleness so the two cannot disagree.
@brief Stamp the answering target, and any staleness, onto a reply.
@return The reply as a dict carrying `target`.
@version 8
"""
answering = self._route(target, sub_index) if target is not None else self._default()
out = (
payload
if payload is not None
else {
"kind": kind,
"subject": subject,
"found": False,
"note": (
f"No {kind} for {subject!r} in this index. This is a definitive "
"negative from the database, NOT an error and NOT a malformed call. "
"Before concluding the symbol does not exist, check `target` below "
"names the repository you meant; a stale index would carry a `staleness` "
"block on this reply."
## gh#6: and if the name IS indexed under a kind this surface cannot
## describe, the sentence above is FALSE as a negative — so it is
## qualified here rather than left to mislead.
+ _kind_limitation_clause(self._unresolved_for(subject, target, sub_index))
## THE ADVICE ABOVE WAS TRUE AND ALMOST NEVER THE PROBLEM. Measured on the
## 1.1.0 grid: 26.7% of dossier calls returned nothing, and 80.6% of the 237
## unanswered subjects were recoverable from what this index already held —
## the qualified form of a bare name, the bare tail of a qualified one, or the
## file itself for all 48 subjects that were a path. Checking `target` was the
## only thing the reply suggested, so a model with the right target and a
## fresh index had nowhere to go but retry the same name.
##
## STILL A MISS. `found` stays False; a hint is an extra field on a negative,
## never a softening of one.
+ self._recovery_for(subject, target, sub_index)
),
}
)
## Stamped AFTER any budget trim, which is safe rather than lucky:
## `_shrink_to_budget` trims to `RESPONSE_BUDGET_BYTES - _LIMITED_BLOCK_ALLOWANCE`,
## and a path plus a key is a rounding error against that 1,800-byte headroom.
out["target"] = self._target_name(answering)
## PRESENT WHENEVER A SUB-INDEX ANSWERED, named or defaulted (gh#48). It used to be
## stamped only when the caller NAMED one, so a bare call answered from first-party read
## exactly like a whole-repository answer. Absent — not `null` — for a whole-repository
## answer, the falsy-drop convention every stamped field here uses.
if answering is not None and answering.sub_index is not None:
out["sub_index"] = answering.sub_index
if answering.not_searched:
out["not_searched"] = _bounded_names(answering.not_searched)
## AFTER the target, so the fit is measured against the finished payload rather
## than one that is still going to grow.
staleness = self._staleness(out, answering)
if staleness:
out["staleness"] = staleness
_withdraw_definitive(out, staleness)
if answering is not None and answering.sub_index is not None:
## `split` WITHOUT `not_searched` IS THE CLI-BUILT REPOSITORY: nothing else on record,
## and the repository's own `.gitmodules` saying there is more of it.
others = bool(answering.not_searched)
if others or answering.split:
_scope_definitive(out, answering.sub_index, others)
_scope_hit(out, answering.sub_index)
for entry in out.get("results") or []:
if isinstance(entry, dict):
_scope_definitive(entry, answering.sub_index, others)
_scope_hit(entry, answering.sub_index)
return out
Activity · 21 steps
Flows
_batched_dossiers
dict[str, Any] clew.mcp_server.tools_query.QueryTools._batched_dossiers(self, list[str] subjects, str|None kind, str|None target, str|None sub_index, int max_body_lines, int depth)
Dossiers for several subjects in ONE reply, sharing one response budget.
clew/mcp_server/tools_query.py:1496
Called by dossier
Calls _answered, _budget_batch, _repo_or_none, _wire_shape, batch_payload, db, prune_absent_keys
Source · 50 lines
def _batched_dossiers(
self,
subjects: list[str],
kind: str | None,
target: str | None,
sub_index: str | None,
max_body_lines: int,
depth: int,
) -> dict[str, Any]:
"""ONE TURN, NOT FIVE. Measured across three graded mbedtls runs of the same
question: every run called `dossier` five times, one symbol per call. Per-call
token cost was already below the raw-source arm's, so the remaining gap was pure
VOLUME — and a turn is the unit that costs, not a byte.
The entries stay POSITIONAL against `subjects`, misses included, so a reader can
pair every requested name with an answer. `count` is the number of entries, which
equals the number of names asked for; `found` counts the ones that resolved, so
"four of five are indexed" is readable without diffing two lists.
SUBJECT-AGNOSTIC SINCE gh#372, and the batch is where that matters most. The
motivating question — "does mbedtls use mutexes, show where and explain how" — is
answered by one batch over four names, and ONE of those four is a variable. A
batch that resolved only functions would have returned three dossiers and a miss
for the symbol the whole question turns on.
@brief Batch dossier envelope for several subjects of any kind.
@return The serialized batch.
@version 6
"""
out = _export.batch_payload(
self.db(target, sub_index),
subjects,
kind=kind,
repo_root=self._repo_or_none(target, sub_index),
max_body_lines=max_body_lines,
depth=depth,
)
entries = out["results"]
## Overhead measured against the envelope MINUS the entries, so the fair shares
## are divided over what is actually left rather than over the whole cap. The
## `+ 2 * len(entries)` covers the JSON separators the entries themselves add.
overhead = len(json.dumps({**out, "results": []})) + 2 * len(entries)
limited = _budget_batch(entries, overhead)
for entry in entries:
wire.prune_absent_keys(entry, _DOSSIER_OPTIONAL)
_wire_shape(entry)
if limited is not None:
out["_limited"] = limited
return self._answered(out, kind="dossiers", target=target, sub_index=sub_index)
Activity · 10 steps
Flows
_bounded_names
list[str] clew.mcp_server.tools_query._bounded_names(tuple[str,...] names)
A name list capped for a reply, with the overflow counted in a final entry.
clew/mcp_server/tools_query.py:363
Source · 10 lines
def _bounded_names(names: tuple[str, ...]) -> list[str]:
"""@brief Cap a name list for a reply. @return The capped list. @version 1"""
shown = list(names[:MAX_LISTED_SIBLINGS])
if len(names) > MAX_LISTED_SIBLINGS:
shown.append(
f"+{len(names) - MAX_LISTED_SIBLINGS} more — index(action='targets') lists them"
)
return shown
Activity · 4 steps
Flows
_budget_batch
dict[str, Any] | None clew.mcp_server.tools_query._budget_batch(list[dict[str, Any]] entries, int overhead)
Trim a batch of serialized dossiers to ONE shared response budget.
clew/mcp_server/tools_query.py:954
Called by _batched_dossiers, test_the_small_symbol_in_a_batch_is_not_starved_by_the_large_one
Tested by
Calls _fair_shares, _shrink_to_budget
Source · 40 lines
def _budget_batch(entries: list[dict[str, Any]], overhead: int) -> dict[str, Any] | None:
"""N DOSSIERS SHARE THE CAP, THEY DO NOT MULTIPLY IT. `_budgeted_dossier` trims one
payload against the whole-response ceiling, which is correct for one and catastrophic
for five.
THE DISCLOSURE NAMES THE SYMBOL, NOT JUST THE FIELD. In a single-symbol reply
`_limited: {callers: ...}` is unambiguous because there is only one subject; in a
batch it is useless. Keys are `"<symbol>.<field>"` so a reader can see that
`psa_get_and_lock_key_slot` lost callers while the other four are intact — which is
exactly the "is this truncation or absence?" question a batch makes easy to get
wrong.
@brief Divide the response budget across a batch, disclosing per-symbol cuts.
@return The batch `_limited` block, or None when nothing was trimmed.
@version 1
"""
available = RESPONSE_BUDGET_BYTES - _BATCH_LIMITED_ALLOWANCE - overhead
sizes = [len(json.dumps(e, default=str)) for e in entries]
adjusted: dict[str, str] = {}
for entry, share in zip(entries, _fair_shares(sizes, available), strict=True):
cut = _shrink_to_budget(entry, _DOSSIER_LISTS, ceiling=share)
for field_name, was in cut.items():
adjusted[f"{entry.get('name', '?')}.{field_name}"] = (
f"{was} -> {len(entry.get(field_name) or [])}"
)
if not adjusted:
return None
return {
"reason": (
f"{len(entries)} dossiers shared the {RESPONSE_BUDGET_BYTES:,}-byte response "
"cap, so each got a fair share of it"
),
"adjusted": adjusted,
"how_to_narrow": (
"ask for FEWER symbols in one call — a single-symbol dossier gets the whole "
"budget — or name the one symbol you need in full"
),
}
Activity · 10 steps
Flows
_budgeted_dossier
dict[str, Any] | None clew.mcp_server.tools_query._budgeted_dossier(dict[str, Any]|None doss)
Trim a serialized dossier's nested lists to the response budget.
clew/mcp_server/tools_query.py:833
Source · 61 lines
def _budgeted_dossier(doss: dict[str, Any] | None) -> dict[str, Any] | None:
"""`dossier` is the tool a model is told to CALL FIRST, and it was the largest
unbounded response in the surface: **125,559 bytes measured** for a symbol with
331 callers.
Trims the nested lists rather than refusing the call, because the identity
fields — signature, file, brief, liveness, thread membership — are small, always
wanted, and are the reason the tool is called first. Losing them to protect the
budget would defeat the purpose; losing the 300th caller costs nothing.
Each trimmed list gets its own `_limited` entry naming the field and its
before/after count, so a model can see WHICH panel was reduced instead of being
told the response was "large".
Ends by ELIDING the one-shot panels that say nothing (`_DOSSIER_OPTIONAL`), after
trimming rather than before: a panel `_shrink_to_budget` reported in `_limited`
always keeps at least one row, so the disclosure can never end up describing a key
that was then removed.
@brief Trim a dossier's nested lists to budget, reporting each reduction.
@return The dossier, possibly trimmed, with a `_limited` block when it was.
@version 2
"""
if doss is None:
return None
cut = _shrink_to_budget(doss, _DOSSIER_LISTS)
if cut:
## The depth step is worded as a DEPTH, not as a row count (gh#383). Reusing
## `_limited_block` here would print "chain_depth: 3 -> 0" and offer to call
## `chain_depth()`, which is neither a field nor a tool — a disclosure that
## misdescribes what it cut is worse than the silence it replaced.
depth = cut.pop(CHAIN_DEPTH_CUT, None)
doss["_limited"] = {
field_name: _limited_block(
field_name,
was,
len(doss.get(field_name) or []),
_DOSSIER_HINTS.get(
field_name,
f"re-ask dossier for a focused view of `{field_name}`, passing "
f"`qualified` first if the name is overloaded",
),
)
for field_name, was in cut.items()
}
if depth is not None:
doss["_limited"][CHAIN_DEPTH_CUT] = {
"reason": (
f"the full response exceeded the {RESPONSE_BUDGET_BYTES:,}-byte cap, so "
f"the chain's outermost ring(s) were dropped BEFORE any neighbour list "
f"was trimmed — depth 1 is adjacency and the section already carries it"
),
"depth_dropped_at_or_above": depth,
"how_to_narrow": (
"re-ask with a lower depth= to get a complete chain, or depth=1 for "
"adjacency alone"
),
}
return wire.prune_absent_keys(doss, _DOSSIER_OPTIONAL)
Activity · 9 steps
Flows
_capped_neighbors
dict[str, Any] | None clew.mcp_server.tools_query._capped_neighbors(dict[str, Any]|None doss, int cap)
A dossier with its depth-1 callers and callees capped at cap , each cut disclosed.
clew/mcp_server/tools_query.py:608
Source · 34 lines
def _capped_neighbors(doss: dict[str, Any] | None, cap: int) -> dict[str, Any] | None:
"""THE PARAMETER SAID IT CAPPED, AND AT DEPTH 1 IT DID NOT. `max_neighbors` reached only a
depth > 1 walk, so a depth-1 reply listed every caller up to the byte budget. Capped here, and
NEVER SILENTLY: the cut list's `_limited` entry carries `total_available` — the single most
useful fact about a hub — and says to raise `max_neighbors` for the rest.
@brief Cap and disclose depth-1 neighbours.
@return The dossier.
@version 1
"""
if doss is None or cap < 1:
return doss
for field_name in ("callers", "callees"):
rows = doss.get(field_name)
if not isinstance(rows, list) or len(rows) <= cap:
continue
doss[field_name] = rows[:cap]
block = _limited_block(
field_name,
len(rows),
cap,
f"raise `max_neighbors` (currently {cap}) to list more of the {len(rows)} {field_name}",
)
block["reason"] = f"`max_neighbors` lists at most {cap} {field_name} per symbol"
limited = doss.setdefault("_limited", {})
if field_name in limited:
limited[field_name]["total_available"] = max(
limited[field_name].get("total_available", 0), len(rows)
)
else:
limited[field_name] = block
return doss
Activity · 15 steps
Flows
_config_space
dict[str, Any] clew.mcp_server.tools_query.QueryTools._config_space(self, str|None symbol=None, str|None target=None, str|None sub_index=None)
The repo's Kconfig configuration space: what build variants exist.
clew/mcp_server/tools_query.py:1830
Source · 27 lines
def _config_space(
self,
symbol: str | None = None,
target: str | None = None,
sub_index: str | None = None,
) -> dict[str, Any]:
"""Returned through `wire.one` and NOT through `_many`, deliberately. `_many`
wraps a list and produces the definitive-sounding "the database records none"
note on an empty result — which is exactly the wrong answer here, because three
different repositories yield zero symbols and `found`/`source`/`error` are what
tell them apart. An envelope that hides those fields would turn a parse failure
into "this firmware has no variants".
@brief Query the configuration space, its choice groups and its gating sites.
@return Serialized KconfigSpace.
@version 2
"""
return self._answered(
_config_found_on_the_wire(
wire.one(q.kconfig_space(self.db(target, sub_index), symbol))
),
kind="configuration space",
subject=symbol,
target=target,
sub_index=sub_index,
)
Activity · 1 steps
Requirements
_default
Answering | None clew.mcp_server.tools_query.QueryTools._default(self)
The default target's routing record, or None when it cannot be resolved.
clew/mcp_server/tools_query.py:1433
Source · 16 lines
def _default(self) -> Answering | None:
"""NON-RAISING, like `_target_name`: it attributes a reply that has already been
answered, so a default that cannot be resolved costs the attribution, never the answer.
A tool set with no answerer — the bound, test-only shape — keeps its old stamps.
@brief Resolve the default target for attribution, tolerating failure.
@return Answering or None.
@version 1
"""
if self._answerer is None:
return None
try:
return self._answerer(None, None)
except Exception:
return None
Activity · 6 steps
Flows
_limited_block
dict[str, Any] clew.mcp_server.tools_query._limited_block(str field_name, int was, int now, str how_to_narrow)
Build the _limited disclosure for one trimmed field.
clew/mcp_server/tools_query.py:650
Source · 19 lines
def _limited_block(field_name: str, was: int, now: int, how_to_narrow: str) -> dict[str, Any]:
"""Names the FIELD and its before/after count, so the degradation is
reproducible and reversible by the caller rather than a hidden policy; reports
`total_available`, which turns a truncation into a MEASUREMENT — "this symbol has
331 callers" is the single most useful fact about a hub; and says how to get the
rest.
@brief Describe one field's reduction.
@return Disclosure dict.
@version 1
"""
return {
"reason": f"the full response exceeded the {RESPONSE_BUDGET_BYTES:,}-byte cap",
"adjusted": {field_name: f"{was} -> {now}"},
"total_available": was,
"how_to_narrow": how_to_narrow,
}
Activity · 1 steps
Flows
_lock_inventory
dict[str, Any] clew.mcp_server.tools_query.QueryTools._lock_inventory(self, str|None target=None, str|None sub_index=None)
The whole lock layer: every lock, the mutex count, the origin split, the nestings.
clew/mcp_server/tools_query.py:1773
Called by none
Calls _answered, _limited_block, _shrink_to_budget, db, lock_roster, one
Source · 48 lines
def _lock_inventory(
self, target: str | None = None, sub_index: str | None = None
) -> dict[str, Any]:
"""Through `wire.one` and NOT `_many`, for the same reason `kconfig` is: the
answer is a single object carrying every count and the sentence that keeps them
apart, not a list. Routing it through `_many` would flatten away
`distinct_mutexes`, `origin` and `row_meaning` — the fields that stop a caller
reporting the row count as the mutex count, or a vendored submodule's mutexes as
this repository's, which are the errors this tool exists to make harder.
`origin` rides in the ENVELOPE rather than in the rows, so its zero buckets
survive: `_absent` prunes empty strings and sequences inside rows, and a
`first_party: 0` that vanished would read as "not measured".
AND IT IS BUDGETED NOW, WHICH IT WAS NOT BEFORE. `_shrink_to_budget` only ever ran
inside `_many`, so every `wire.one` envelope — this one included — was UNCAPPED: a
target with enough locks would have blown the 32,768-byte cap silently, which is the
exact silent-truncation failure the cap exists to convert into a disclosure. Folding
the nestings in is what made it live rather than latent. Measured on the public
entropic index the reply went 23,510 -> 30,556 bytes, leaving ~400 bytes of headroom
under the trim ceiling once `target` and a two-axis staleness block are stamped on.
A fold that quietly truncated the POPULATED target to save a call on the empty one
would be a regression dressed as an optimisation.
`nestings` IS TRIMMED BEFORE `locks`, by giving `_shrink_to_budget` only that key.
The roster is the answer to the question the caller asked; the nestings ride along
because they are cheap, and a passenger must not evict the payload. `_limited` names
which list was cut and how to recover it — `query.lock_nestings` still returns the
whole set to a direct R2 consumer, and that is what the advice says.
@brief The whole lock inventory in one call.
@return Serialized LockInventory.
@version 4
"""
out = wire.one(q.lock_roster(self.db(target, sub_index)))
if out is not None:
cut = _shrink_to_budget(out, ("nestings",))
if cut:
out["_limited"] = _limited_block(
"nestings",
cut["nestings"],
len(out["nestings"]),
"the locks themselves are complete and untrimmed; only the nesting "
"pairs were reduced. Ask dossier for a named lock's sections, "
"or read the full set from the query library's lock_nestings",
)
return self._answered(out, target=target, sub_index=sub_index)
Activity · 6 steps
Requirements
_recovery_for
str clew.mcp_server.tools_query.QueryTools._recovery_for(self, str|None subject, str|None target, str|None sub_index=None)
What to try instead, for a subject this index could not answer.
clew/mcp_server/tools_query.py:1257
Source · 21 lines
def _recovery_for(
self, subject: str | None, target: str | None, sub_index: str | None = None
) -> str:
"""SAME TOLERANCE AS `_unresolved_for`, and for the same reason: this runs while building a
reply that has already failed, so nothing here may turn a clean negative into a traceback.
Measured on the 1.1.0 grid: the old miss note advised checking `target` and staleness,
which is true and was almost never the problem — 80.6% of the 237 unanswered subjects were
recoverable from what the index already held.
@brief Probe for a recovery hint, tolerating any failure.
@return The hint, or "".
@version 1
"""
if not subject:
return ""
try:
return recovery_hint(self.db(target, sub_index), subject)
except Exception:
return ""
Activity · 6 steps
Flows
_repo_or_none
Path | None clew.mcp_server.tools_query.QueryTools._repo_or_none(self, str|None target=None, str|None sub_index=None)
The working tree for this call, or None when there isn't one.
clew/mcp_server/tools_query.py:1196
Source · 27 lines
def _repo_or_none(self, target: str | None = None, sub_index: str | None = None) -> Path | None:
"""NON-RAISING, unlike `repo()`, and that is the whole reason it exists.
`source` MUST fail loudly without a working tree — its entire answer is bytes off
disk, so a silent empty reply would be indistinguishable from "this function has
no body". `dossier` must not: the working tree is needed for two panels out of
twenty fields, it answered without them for its whole life before the one-shot,
and a tool set bound without a repo provider is the shape every unit test uses.
Turning that into an exception would make the composite payload fail where the
narrow tool it replaces succeeded.
`sub_index` HAS TO REACH `repo()` HERE TOO, not only at the `db()` call beside it. A
repository with ONLY sub-indexes has no whole-repository record for `resolve_target` to
fall back on, so `repo(target, None)` raised "ambiguous bare root" and this method's own
non-raising contract turned that into a silent `None` — the database routed correctly
while the `body` panel vanished, reading exactly like "this function has no recorded
source" instead of the routing gap it actually was.
@brief Resolve this call's working tree, or None.
@return Repo root or None.
@version 2
"""
try:
return self.repo(target, sub_index)
except (RuntimeError, ValueError, OSError):
return None
Activity · 4 steps
Flows
_route
Answering clew.mcp_server.tools_query.QueryTools._route(self, str target, str|None sub_index=None)
Resolve an explicit per-call target, refusing when this set cannot route.
clew/mcp_server/tools_query.py:1108
Source · 17 lines
def _route(self, target: str, sub_index: str | None = None) -> Answering:
"""Refusing beats falling back. A tool set with no answerer is bound to one
database, and serving that database for a call that named a different one would
produce a reply whose `target` field names the bound repository — which reads as a
successful routed call and hides the mistake completely.
@brief Resolve a routed target, or say this tool set cannot route.
@return The resolved repository.
@version 2
"""
if self._answerer is None:
raise RuntimeError(
f"These tools cannot route to {target!r}: they are bound to a single "
"repository. Call status to see which repository answers here."
)
return self._answerer(target, sub_index)
Activity · 3 steps
Flows
_scope_definitive
None clew.mcp_server.tools_query._scope_definitive(dict[str, Any] payload, str answered_from, bool others=True)
Withdraw a definitive negative that was answered from one part of a split repository.
clew/mcp_server/tools_query.py:423
Source · 32 lines
def _scope_definitive(payload: dict[str, Any], answered_from: str, others: bool = True) -> None:
"""`others` SAYS WHETHER ANY OTHER PART IS ON RECORD. Found by driving a model at a fixture
(gh#48 ask 5): a first-party index built by the CLI registers no sibling and records no
split, so `not_searched` was empty and the negative kept its definitive wording — and the
model then reported a symbol as absent from the REPOSITORY. The repository still declares
itself split in `.gitmodules`; with no names to offer, the reply says how to find them.
@brief Scope a negative to the sub-index that answered it.
@version 2
"""
note = payload.get("note")
negative = payload.get("found") is False or payload.get("count") == 0
if not isinstance(note, str) or not negative:
return
if not re.search(_DEFINITIVE_SPLIT, note):
return
kept = re.split(_DEFINITIVE_SPLIT, note)[0].rstrip()
where = (
"`not_searched` lists this repository's other parts. Ask again with sub_index=<one of "
"those> before concluding it does not exist — a part with no index yet starts building "
"on that call."
if others
else "this repository is split into parts and no other part is indexed yet. Call "
"index(action='targets') to see them, and refresh one with sub_index=<name> before "
"concluding it does not exist."
)
payload["note"] = (
f"{kept} NOT DEFINITIVE FOR THE REPOSITORY: only sub-index {answered_from!r} was "
f"searched, and {where}"
)
Activity · 9 steps
Requirements
Flows
_scope_hit
None clew.mcp_server.tools_query._scope_hit(dict[str, Any] payload, str answered_from)
Say that a hit's unresolved call sites may resolve in a part this answer did not read.
clew/mcp_server/tools_query.py:391
Source · 18 lines
def _scope_hit(payload: dict[str, Any], answered_from: str) -> None:
"""ONLY WHEN THERE IS AN EDGE TO EXPLAIN. A first-party hit whose every callee resolved is
complete as far as the question goes, and annotating it would be the over-hedging gh#393
reverted. `external_callees` being non-empty is the measured signal that something this
reply names is defined somewhere it did not look.
@brief Annotate a hit whose unresolved edges may cross into an unread index.
@return None.
@version 1
"""
external = payload.get("external_callees")
if payload.get("found") is False or not external:
return
payload["scope_note"] = _UNRESOLVED_ACROSS_INDEXES.format(
count=len(external), name=answered_from
)
Activity · 4 steps
Requirements
Flows
_search_threads
dict[str, Any] clew.mcp_server.tools_query.QueryTools._search_threads(self, str text, int limit, str|None target, str|None sub_index=None)
The thread corpus: every thread, with the origin split beside the count.
clew/mcp_server/tools_query.py:2094
Source · 16 lines
def _search_threads(
self, text: str, limit: int, target: str | None, sub_index: str | None = None
) -> dict[str, Any]:
"""Through `wire.one` and NOT `_many`, as the former `thread_roster` tool was: the
answer is a single object carrying `origin` and the sentence that says whose
threads the count counts. `_many` would flatten both away, and it would replace a
pre-35 index's "this build recorded no spawn sites" with the definitive-sounding
"the database records none" — turning an unattributable index into a claim about
the code.
@brief Enumerate the thread roster.
@return Serialized ThreadInventory.
@version 1
"""
return self._corpus("threads", text, limit, target, sub_index)
Activity · 1 steps
Requirements
_shrink_to_budget
dict[str, int] clew.mcp_server.tools_query._shrink_to_budget(dict[str, Any] payload, tuple[str,...] list_keys, int|None ceiling=None)
Spend chain DEPTH, then halve the largest list, until the payload fits.
clew/mcp_server/tools_query.py:533
Called by _budget_batch, _budgeted_dossier, _lock_inventory, _many, test_a_depth_one_chain_is_never_stripped_to_nothing
Tested by
Calls _step_chain_depth
Source · 69 lines
def _shrink_to_budget(
payload: dict[str, Any], list_keys: tuple[str, ...], ceiling: int | None = None
) -> dict[str, int]:
"""SELF-LIMITING, AND IT SAYS SO. A silent truncation is the worst option
available: a model handed 82 of 331 rows with no indication believes it has the
whole picture and reasons confidently from a quarter of the evidence. That is the
same failure class as every silent-degradation bug recorded here — an empty layer
read as "no dataflow", a refused judge verdict read as "not measured".
CONVERGES ON THE ACTUAL SERIALIZED SIZE by halving the largest list until the
payload fits. An earlier version estimated from a 5-row sample and multiplied,
which failed twice: the estimate ran UNDER, so the response stayed above the cap;
and spending the budget list-by-list in declaration order charged small lists for
what large ones had consumed, cutting a 2-element list to 1 while reporting "full
response would be about 540 bytes" against a 32 KB cap. Measuring beats
estimating when the measurement is one `json.dumps` away.
Halving rather than computing an exact keep-count is deliberate: row sizes vary by
an order of magnitude within one list, so any arithmetic on a mean is a guess.
Halving converges in at most ~log2(n) passes and each pass is measured.
`ceiling` IS A PARAMETER BECAUSE A BATCH SHARES ONE RESPONSE. When several dossiers
travel in one reply they must divide the 32,768 bytes between them, not each claim
it — five dossiers trimmed to the whole-response ceiling would produce a 160 KB
reply that respects the cap five times over and exceeds it once. The default is the
single-payload ceiling, so every existing caller is unchanged.
@brief Halve the largest list until the payload fits, reporting what was cut.
@return Mapping of field name to its ORIGINAL length, for fields that were cut.
@version 2
"""
original = {
key: len(payload[key])
for key in list_keys
if isinstance(payload.get(key), list) and payload[key]
}
if ceiling is None:
ceiling = RESPONSE_BUDGET_BYTES - _LIMITED_BLOCK_ALLOWANCE
## DEPTH FIRST, ROWS SECOND (gh#383). The outermost chain ring is the cheapest content
## in the payload and the immediate neighbours are the dearest, so they are spent in
## that order. Recorded under a reserved key rather than mixed into `original`, because
## "depth reduced 3 -> 1" and "callers 331 -> 82" are DIFFERENT FACTS and collapsing
## them into one number is how a caller comes to think it has the whole graph.
stepped: list[int] = []
while len(json.dumps(payload, default=str)) > ceiling:
dropped = _step_chain_depth(payload)
if dropped is None:
break
stepped.append(dropped)
for _ in range(64):
if len(json.dumps(payload, default=str)) <= ceiling:
break
biggest = max(
original,
key=lambda k: len(payload.get(k) or []),
default=None,
)
if biggest is None or len(payload.get(biggest) or []) <= 1:
break # nothing left to give; the non-list fields alone exceed the cap
payload[biggest] = payload[biggest][: max(1, len(payload[biggest]) // 2)]
cut = {k: was for k, was in original.items() if was > len(payload.get(k) or [])}
if stepped:
cut[CHAIN_DEPTH_CUT] = max(stepped)
return cut
Activity · 20 steps
Flows
_staleness
list[dict[str, str]] clew.mcp_server.tools_query.QueryTools._staleness(self, dict[str, Any] payload, Answering|None answering=None)
The staleness axes to attach to this reply, sized to fit.
clew/mcp_server/tools_query.py:1455
Source · 24 lines
def _staleness(
self, payload: dict[str, Any], answering: Answering | None = None
) -> list[dict[str, str]]:
"""NON-RAISING, like `_target_name`, and for the same reason: it runs on the way
out of every reply including the ones that succeeded. A tool set bound without a
provider — the test-only shape, and the pre-gh#2 behaviour — annotates nothing.
A ROUTED REPLY IS ANNOTATED FOR THE REPOSITORY IT READ, never for the derived one.
Reporting the derived target's staleness beside another repository's data would be
a warning about a database this reply never opened, which is worse than silence:
the caller would act on it.
@brief Measure and size this reply's staleness annotation.
@return Notices sized to the remaining budget, possibly empty.
@version 2
"""
if answering is not None:
found = answering.staleness
elif self._staleness_provider is not None:
found = self._staleness_provider()
else:
return []
return _staleness_within_budget(payload, found) if found else []
Activity · 7 steps
Flows
_staleness_within_budget
list[dict[str, str]] clew.mcp_server.tools_query._staleness_within_budget(dict[str, Any] payload, list[dict[str, str]] found)
Fit a staleness block into whatever budget the payload left.
clew/mcp_server/tools_query.py:200
Source · 36 lines
def _staleness_within_budget(
payload: dict[str, Any], found: list[dict[str, str]]
) -> list[dict[str, str]]:
"""MEASURED AGAINST THE REAL PAYLOAD rather than reserved up front, and the choice
matters. Reserving headroom the way `_LIMITED_BLOCK_ALLOWANCE` does would lower the
trim ceiling for EVERY response including the overwhelming majority that carry no
annotation at all, changing how much data a current index returns because a stale one
might have needed the room. This spends only what is actually free.
Compacting rather than dropping, because a warning that disappears exactly when the
answer is largest inverts the point: a big payload is a lot of reasoning to do on a
possibly-outdated graph.
THREE TIERS, BECAUSE TWO WERE NOT ENOUGH AND A CONTROL PROVED IT. The first version
fell back to the compact form and returned it unconditionally — but the compact form
is ~170 bytes PER AXIS, so three axes beside a payload with 190 bytes free still went
over the very cap this function exists to respect. A fallback that is merely smaller
is not bounded. The last tier is ~40 bytes per axis and is taken unconditionally,
which is safe rather than lucky: `_shrink_to_budget` trims to
`RESPONSE_BUDGET_BYTES - _LIMITED_BLOCK_ALLOWANCE`, so a real reply arrives here with
most of 1,800 bytes free and never reaches the third tier at all.
@brief Choose the largest staleness block that fits.
@return Notices sized to fit.
@version 2
"""
room = RESPONSE_BUDGET_BYTES - len(json.dumps(payload))
tiers = (
found,
[{"axis": n["axis"], "message": _STALENESS_COMPACT_MESSAGE} for n in found],
[{"axis": n["axis"], "message": _STALENESS_MINIMAL_MESSAGE} for n in found],
)
fitting = (t for t in tiers if len(json.dumps({"staleness": t})) <= room)
return next(fitting, tiers[-1])
Activity · 4 steps
Flows
_step_chain_depth
int | None clew.mcp_server.tools_query._step_chain_depth(dict[str, Any] payload)
Drop the outermost ring of a payload's causal chain, if it has one.
clew/mcp_server/tools_query.py:478
Source · 48 lines
def _step_chain_depth(payload: dict[str, Any]) -> int | None:
"""gh#383. THE CHAIN WAS NEVER BUDGETED AT ALL, which is a sharper statement than the
plan's "step depth before halving". `_DOSSIER_LISTS` holds TOP-LEVEL keys and
`payload["chain"]` is a nested dict of `nodes`/`hops`, so `_shrink_to_budget` could
not see it: an oversized chain was carried in full while the IMMEDIATE neighbours —
`callers`, `callees`, the highest-value rows in the reply — were halved to pay for it.
Depth 1 is adjacency, which the populated section already carries; depth 2+ is
traversal. So the outermost ring is the cheapest thing in the payload to lose and the
immediate neighbours are the dearest, and the old order spent them in exactly the wrong
sequence. Fan-out is roughly geometric, so one ring usually frees more than several
halvings of a neighbour list would.
NODES CARRY THEIR OWN `depth` and hops reference nodes BY NAME, so a ring can be
removed exactly rather than estimated: drop every node at the maximum depth, then every
hop that touches a name no longer present. A hop kept after its endpoint left would
assert an edge into nothing.
Returns the depth removed so the caller can disclose it. Stops at depth 1 — stripping
that too would leave a `chain` block claiming a traversal with no reachable nodes, which
is worse than a smaller chain.
@brief Remove the outermost depth ring from the chain.
@return The dropped depth, or None.
@version 1
"""
chain = payload.get("chain")
if not isinstance(chain, dict):
return None
nodes = chain.get("nodes")
if not isinstance(nodes, list) or not nodes:
return None
depths = [n.get("depth", 0) for n in nodes if isinstance(n, dict)]
deepest = max(depths, default=0)
if deepest <= 1:
return None
chain["nodes"] = [n for n in nodes if not (isinstance(n, dict) and n.get("depth") == deepest)]
kept = {n.get("name") for n in chain["nodes"] if isinstance(n, dict)}
hops = chain.get("hops")
if isinstance(hops, list):
chain["hops"] = [
h
for h in hops
if isinstance(h, dict) and h.get("from_name") in kept and h.get("to_name") in kept
]
return deepest
Activity · 16 steps
Flows
_target_name
str clew.mcp_server.tools_query.QueryTools._target_name(self, Answering|None answering)
The repository this reply answered from, for attribution.
clew/mcp_server/tools_query.py:1228
Source · 22 lines
def _target_name(self, answering: Answering | None) -> str:
"""Non-raising by contract, unlike `repo()`. It is called on the way OUT of
every reply, including replies that succeeded, so it must never be the thing
that turns a good answer into an error. A tool set constructed without a repo
provider is a test-only shape; naming the database there is still a truthful
answer to "what answered this?".
REPORTS THE REPO ROOT ONLY, deliberately, which is now shared by every sub-index of one
repository — a reply from `extern-llama.cpp` names the same root a reply from
`first-party` would. `_answered` stamps `sub_index` as its own key for exactly the reason
this docstring's sibling warns about: two different databases must not produce
indistinguishable `target` fields, or a reply from the wrong sub-index reads as correct.
@brief Name the repository (or database) that answered.
@return Target name.
@version 3
"""
if answering is not None:
return str(answering.repo)
provider = self._repo_provider if self._repo_provider is not None else self._db_provider
return str(provider())
Activity · 4 steps
Flows
_unresolved_for
tuple[str, ...] clew.mcp_server.tools_query.QueryTools._unresolved_for(self, str|None subject, str|None target, str|None sub_index=None)
Unsupported kinds this index holds for a name that failed to resolve.
clew/mcp_server/tools_query.py:1285
Source · 20 lines
def _unresolved_for(
self, subject: str | None, target: str | None, sub_index: str | None = None
) -> tuple[str, ...]:
"""NEVER RAISES ON THE MISS PATH. This runs while building an answer that has already
failed to find something, so a database that cannot be opened — the very case
`unbuilt_index_message` exists for — must not turn a clean negative into a traceback.
A probe that cannot run contributes no clause, which is the same discipline as
`doxygen_supports_sqlite3` returning None rather than False.
@brief Probe the unsupported kinds behind a miss, tolerating any failure.
@return The kinds, or ().
@version 2
"""
if not subject:
return ()
try:
return q.unresolved_kinds(self.db(target, sub_index), subject)
except Exception:
return ()
Activity · 6 steps
Flows
_wire_shape
dict[str, Any] | None clew.mcp_server.tools_query._wire_shape(dict[str, Any]|None doss)
Apply the compact neighbour shape when the server was asked for it.
clew/mcp_server/tools_query.py:811
Source · 17 lines
def _wire_shape(doss: dict[str, Any] | None) -> dict[str, Any] | None:
"""AFTER THE BUDGET AND THE CAP, because compaction only ever shrinks a payload: the trimmers
keep counting flat rows, `_limited` keeps reporting row counts, and a payload that fitted
flat fits compact. Read from the environment PER CALL, so a test or a host can switch it
without restarting anything.
@brief Opt-in compaction at the MCP boundary.
@return The payload.
@version 2
"""
import os
if doss is None or os.environ.get(WIRE_ENV) != WIRE_COMPACT:
return doss
return compact_docs(compact_neighbours(doss))
Activity · 4 steps
Requirements
Flows
_with_wiki_url
dict[str, Any] clew.mcp_server.tools_query.QueryTools._with_wiki_url(self, dict[str, Any] reply)
Add the hub URL of a found function's symbol section, while the hub runs.
clew/mcp_server/tools_query.py:1747
Source · 20 lines
def _with_wiki_url(self, reply: dict[str, Any]) -> dict[str, Any]:
"""ADDITIVE AND ONLY WHILE SERVING: no linker, no key; a miss or a non-function subject
gets none. A linker that fails costs the link, never the answer.
@brief wiki_url.
@return Reply.
"""
if self.wiki_linker is None or reply.get("found") is False:
return reply
if reply.get("subject_kind") != "function" or not reply.get("file"):
return reply
try:
url = self.wiki_linker(str(reply.get("target")), str(reply["name"]), str(reply["file"]))
except Exception:
logger.debug("wiki link failed for %s", reply.get("name"))
url = None
if url:
reply["wiki_url"] = url
return reply
Activity · 12 steps
Flows
_withdraw_definitive
None clew.mcp_server.tools_query._withdraw_definitive(dict[str, Any] payload, list[dict[str, str]] staleness)
Withdraw an unearned definitive-negative claim when the index is schema-stale.
clew/mcp_server/tools_query.py:322
Called by _answered
Tested by 5 tests
test_a_data_stale_subject_miss_withdraws_the_definitive_claim, test_a_definitive_empty_is_withdrawn_on_a_partial_index, test_a_definitive_negative_is_withdrawn_while_layers_are_derived_stale, test_data_staleness_does_not_hedge_an_empty_row_list, test_schema_staleness_still_withdraws_with_the_missing_layer_wording
Calls none
Source · 31 lines
def _withdraw_definitive(payload: dict[str, Any], staleness: list[dict[str, str]]) -> None:
"""@brief Withdraw a definitive-negative claim a stale index cannot earn. @version 3"""
note = payload.get("note")
if not isinstance(note, str):
return
axes = {n.get("axis") for n in staleness}
## Two different unearned-ness conditions, and they need different sentences: `schema` means a
## layer may be MISSING, `data` means the symbol may POSTDATE the build (gh#12). The data case
## is restricted to a subject miss — see `_DATA_AXIS`.
replacement = None
if _SCHEMA_AXIS in axes:
replacement = _UNEARNED_DEFINITIVE
elif _PARTIAL_AXIS in axes:
replacement = _UNEARNED_BY_PARTIAL
elif _DERIVED_AXIS in axes:
replacement = _UNEARNED_BY_DERIVED
elif _DATA_AXIS in axes and payload.get("found") is False:
replacement = _UNEARNED_BY_DRIFT
if replacement is None:
return
lowered = note.lower()
if not any(claim in lowered for claim in _DEFINITIVE_CLAIMS):
return
## Rewritten rather than appended-to: leaving "this is a definitive empty result" in place and
## adding "not definitive" after it is two claims again, in one sentence.
## The split DROPS the old advice as well as the old claim, which is the point: the reported
## note spent its second half telling the reader to check `target`, and `target` was right.
kept = re.split(r"(?i)this is a definitive|do not retry", note)[0].rstrip()
payload["note"] = f"{kept}{replacement}"
Activity · 20 steps
Requirements
Flows
db
Path clew.mcp_server.tools_query.QueryTools.db(self, str|None target=None, str|None sub_index=None)
The database path this call reads.
clew/mcp_server/tools_query.py:1131
Called by __call__, _batched_dossiers, _config_space, _corpus, _files_context, _lock_inventory, _recovery_for, _unresolved_for, dossier, graph_stats, own_reqs, via
Calls _route, unbuilt_index_message
Source · 29 lines
def db(self, target: str | None = None, sub_index: str | None = None) -> Path:
"""Resolve the db path for this call: the routed target when one was named, else
the derived one. Omitting `target` reproduces the previous behaviour exactly.
`sub_index` NAMES THE PART, not a suffix on `target`. A composite string a caller has to
construct (`f"{target}#{name}"`) has no schema of its own for a model to read; a second
parameter does — `list_targets` reports the legal names, and the tool's own schema says
the parameter exists.
@brief Resolve this call's database path.
@return clew.db path.
@version 4
"""
if target is not None:
return self._route(target, sub_index).db
if sub_index is not None:
raise RuntimeError(
f"sub_index={sub_index!r} was given without target — a sub-index belongs to a "
"named repository, so target= must be stated too."
)
## GUARDED HERE, NOT ONLY ON THE ROUTED PATH. Every tier-1 tool funnels through this
## method, so one check covers the whole surface; the routed branch above already refuses
## inside `resolve_target`. Without this, a derived target with no database reached
## sqlite3 and surfaced `unable to open database file`.
db = Path(self._db_provider())
if not db.is_file():
raise RuntimeError(unbuilt_index_message())
return db
Activity · 8 steps
Requirements
Flows
dossier
dict[str, Any] clew.mcp_server.tools_query.QueryTools.dossier(self, Annotated[str|list[str], Field(description=("One name, or a list of up to 8: a function, variable, typedef, macro, class, " "enumeration, lock, thread, requirement id, config symbol, or a " "repo-relative FILE PATH (`harvested: false` when the file was not read).")),] subject, *Annotated[str|None, Field(description="Narrow to one kind when a name resolves to several."),] kind=None, Annotated[int, Field(description=("1 is the symbol and its neighbours; 2-6 also returns `chain`, a bounded " "walk over call and shared-key edges (6 is the maximum). Only a function " "has edges; other kinds return `depth_note`.")),] depth=1, Annotated[str, Field(description="'forward' for downstream, 'back' for upstream, on depth >= 2.")] direction="forward", Annotated[int|None, Field(description=("Callers/callees listed per symbol: 25 at depth 1, 8 per hop deeper. A cut " "list shows in `_limited` with `total_available`. Rows may arrive grouped " "by `file`, with `edge_defaults` holding the `source`/`confidence`/" "`edge_class` a row leaves out.")),] max_neighbors=None, Annotated[str|None, Field(description=("A `qualified` value from a previous reply (`Owner::method`), NOT a " "`signature`. Selects one identity; keep `subject` bare; single name only.")),] qualified=None, Annotated[str|None, Field(description="Repo root or slug; omit for the default."),] target=None, Annotated[str|None, Field(description=("One PART of a repository split into several indexes (first-party plus one " "per vendored dependency); omit for the whole repository. The reply's " "`sub_index` names the part that answered, `not_searched` the parts not read.")),] sub_index=None, Annotated[int, Field(description=("Lines of VERBATIM SOURCE in `body`; raise it when `truncated: true`.")),] max_body_lines=q.DEFAULT_BODY_LINES)Full multi-layer dossier for one subject of ANY kind, or for several at once.
clew/mcp_server/tools_query.py:1567
Called by none
Calls _accepted_batch, _answered, _batched_dossiers, _budgeted_dossier, _capped_neighbors, _repo_or_none, _wire_shape, _with_wiki_url, db, disclose_overflow, subject_payload
Source · 120 lines
def dossier(
self,
subject: Annotated[
str | list[str],
Field(
description=(
"One name, or a list of up to 8: a function, variable, typedef, macro, class, "
"enumeration, lock, thread, requirement id, config symbol, or a "
"repo-relative FILE PATH (`harvested: false` when the file was not read)."
)
),
],
*,
kind: Annotated[
str | None,
Field(description="Narrow to one kind when a name resolves to several."),
] = None,
depth: Annotated[
int,
Field(
description=(
"1 is the symbol and its neighbours; 2-6 also returns `chain`, a bounded "
"walk over call and shared-key edges (6 is the maximum). Only a function "
"has edges; other kinds return `depth_note`."
)
),
] = 1,
direction: Annotated[
str, Field(description="'forward' for downstream, 'back' for upstream, on depth >= 2.")
] = "forward",
max_neighbors: Annotated[
int | None,
Field(
description=(
"Callers/callees listed per symbol: 25 at depth 1, 8 per hop deeper. A cut "
"list shows in `_limited` with `total_available`. Rows may arrive grouped "
"by `file`, with `edge_defaults` holding the `source`/`confidence`/"
"`edge_class` a row leaves out."
)
),
] = None,
qualified: Annotated[
str | None,
Field(
description=(
"A `qualified` value from a previous reply (`Owner::method`), NOT a "
"`signature`. Selects one identity; keep `subject` bare; single name only."
)
),
] = None,
target: Annotated[
str | None,
Field(description="Repo root or slug; omit for the default."),
] = None,
sub_index: Annotated[
str | None,
Field(
description=(
"One PART of a repository split into several indexes (first-party plus one "
"per vendored dependency); omit for the whole repository. The reply's "
"`sub_index` names the part that answered, `not_searched` the parts not read."
)
),
] = None,
max_body_lines: Annotated[
int,
Field(
description=("Lines of VERBATIM SOURCE in `body`; raise it when `truncated: true`.")
),
] = q.DEFAULT_BODY_LINES,
) -> dict[str, Any]:
"""A LIST IN THE SAME ARGUMENT, NOT A SECOND ARGUMENT. The alternative — keeping
`function: str` and adding `functions: list[str]` — puts two ways to name a symbol
in one schema, and the failure mode is a model passing both, or passing the list
to the parameter it already knows and getting a type error on the one call this
change exists to encourage. One parameter has one meaning: the symbols you want.
The cost is an `anyOf` in the generated schema, which is a shape every MCP client
already handles for optional arguments.
`qualified` IS REFUSED WITH A LIST rather than ignored. It selects ONE identity
among namesakes, so against five symbols there is no honest interpretation: it
cannot say which one it disambiguates, and silently applying it to all five would
scope four dossiers by a qualified name that belongs to a different function.
Ignoring it would be worse still — the caller asked for a specific identity and
would receive an arbitrary one, labelled as if it had been disambiguated.
THE LIST IS CAPPED AND THE CAP REFUSES. `MAX_BATCH_SYMBOLS` names it; going over
raises rather than answering for the first eight, because a truncated request
answered as if complete is the failure this whole surface's `_limited` disclosure
exists to prevent.
Duplicates are collapsed HERE and not in R2. A repeated name costs a full dossier
of the shared budget to say the same thing twice, and the entry it would have
occupied is better spent on a symbol that was actually asked about; R2 stays
positional because a library caller has no budget to protect.
`qualified` is OPTIONAL and additive (gh#37) — omitting it reproduces the
previous behaviour exactly. `subject` stays BARE even when `qualified` is
supplied: they are two different columns, and passing a qualified spelling as
`subject` matches nothing.
EVERYTHING AFTER `subject` IS KEYWORD-ONLY, and that is a correctness measure
rather than a style one. `qualified` used to be the second POSITIONAL parameter;
`kind` is now in that slot, and both take a string. A caller that had learned
`dossier(name, qualified_spelling)` would have had its identity selector read as a
subject-kind filter — which raises on a qualified name and would SILENTLY filter
for any value that happens to be a kind. The bare `*` makes every such call a
TypeError at the call site instead.
THE ONE-SHOT. The working tree is resolved from the SAME `target` as the
database, exactly as the deleted `source` tool did — this payload quotes bytes off
disk using line numbers out of an index, and a mismatch between the two would show
one repository's text under another's symbol. Resolved non-raising, so a tool set
with no working tree bound still answers with every index-only panel.
`max_body_lines` EXISTS BECAUSE `source` IS GONE, and it is the one thing that tool
could do that this panel could not. Measured on mbedtls:
`mbedtls_x509_crt_parse_path` is a 139-line function, so the 120-line default
returns `truncated: true` and the tail was reachable only through `source`'s
`max_lines`. Deleting the tool without this argument would have made a long body's55 more lines, not shown
Activity · 9 steps
Requirements
REQ-DDB-MCP-003 REQ-DDB-QUERY-010
Flows
graph_stats
dict[str, Any] clew.mcp_server.tools_query.QueryTools.graph_stats(self, str|None target=None, str|None sub_index=None)
Whole-graph trust aggregate: edge counts, coverage, per-layer state.
clew/mcp_server/tools_query.py:1862
Source · 26 lines
def graph_stats(
self, target: str | None = None, sub_index: str | None = None
) -> dict[str, Any]:
"""Returned through `wire.one` and NOT through `_many`, for the same reason
`kconfig` is: this is an ENVELOPE, not a list. Every one of its keys must reach
the caller even at zero — an aggregate that elided `pairs_without_nonfuzzy: 0`
would make a perfectly-resolved graph indistinguishable from an unmeasured one,
which is the precise misreading the payload exists to prevent.
Narrows nothing but the repository. The subject is the whole index, and
`_answered` still stamps the target, which matters more here than anywhere: an
aggregate is the reply most likely to be quoted as a headline number, and a
headline number about the wrong repository is how a 36-cell benchmark run was
voided.
@brief Aggregate the graph so a consumer can calibrate how much to trust it.
@return Serialized GraphStats.
@version 2
"""
return self._answered(
wire.one(q.graph_stats(self.db(target, sub_index))),
kind="graph statistics",
target=target,
sub_index=sub_index,
)
Activity · 1 steps
Requirements
repo
Path clew.mcp_server.tools_query.QueryTools.repo(self, str|None target=None, str|None sub_index=None)
The working-tree root this call reads source from.
clew/mcp_server/tools_query.py:1166
Source · 24 lines
def repo(self, target: str | None = None, sub_index: str | None = None) -> Path:
"""Resolve the working tree the recorded paths are relative to. The model is
NEVER asked for it as a filesystem path — it names a repository and the server
resolves it, or it names none and the server's derived target answers.
A SUB-INDEX SHARES ITS PARENT'S WORKING TREE. Every sub-index of one repository is built
with `repo_root` set to the same root (Phase 1), so recorded paths are already relative to
it regardless of which sub-index answered — routing to a sub-index changes the DATABASE,
never the tree its paths are read against.
@brief Resolve this call's repo root.
@return Repo root path.
@version 4
"""
if target is not None:
return self._route(target, sub_index).repo
if self._repo_provider is None:
raise RuntimeError(
"No repo root bound to these tools — the server has no target. It "
"derives one from --repo, $CLAUDE_PROJECT_DIR, or the client's "
"roots/list; call status to see which, or name one with target=."
)
return self._repo_provider()
Activity · 5 steps
Requirements
Flows
search
dict[str, Any] clew.mcp_server.tools_query.QueryTools.search(self, Annotated[str, Field(description=("Words to match, all in one unit; ignored by `locks` and `threads`.")),] text="", *Annotated[str, Field(description=("'symbols' (default): names and per-file docs; 'prose': markdown and " "reStructuredText; 'code': function BODIES containing the words (a literal, " "a config key); or a whole layer: 'locks', 'threads', 'files', 'config'.")),] corpus="symbols", Annotated[int, Field(description=("Maximum rows returned. A reply cut by it says so in `_limited`, with " "`total_available` counting every match.")),] limit=25, Annotated[str|None, Field(description="Repo root or slug; omit for the default."),] target=None, Annotated[str|None, Field(description=("One PART of a repository split into several indexes (first-party plus one " "per vendored dependency); omit for the whole repository. The reply's " "`sub_index` names the part that answered, `not_searched` the parts not read.")),] sub_index=None)Ranked search across ONE named corpus, or across the searchable text ones.
clew/mcp_server/tools_query.py:1897
Source · 78 lines
def search(
self,
text: Annotated[
str,
Field(
description=("Words to match, all in one unit; ignored by `locks` and `threads`.")
),
] = "",
*,
corpus: Annotated[
str,
Field(
description=(
"'symbols' (default): names and per-file docs; 'prose': markdown and "
"reStructuredText; 'code': function BODIES containing the words (a literal, "
"a config key); or a whole layer: 'locks', 'threads', 'files', 'config'."
)
),
] = "symbols",
limit: Annotated[
int,
Field(
description=(
"Maximum rows returned. A reply cut by it says so in `_limited`, with "
"`total_available` counting every match."
)
),
] = 25,
target: Annotated[
str | None,
Field(description="Repo root or slug; omit for the default."),
] = None,
sub_index: Annotated[
str | None,
Field(
description=(
"One PART of a repository split into several indexes (first-party plus one "
"per vendored dependency); omit for the whole repository. The reply's "
"`sub_index` names the part that answered, `not_searched` the parts not read."
)
),
] = None,
) -> dict[str, Any]:
"""ONE FINDER, N CORPORA — `search_prose` WAS NEVER A TOOL, IT WAS AN ARGUMENT.
The two searches differed in which table they read and in nothing a caller cares
about, so shipping them as separate tools meant a model had to know which corpus
held its answer BEFORE it could ask, which is the thing it was searching to find
out. The markdown corpus is now `corpus='prose'` and the default is unchanged.
AND THE ROSTERS ARE CORPORA TOO. `lock_roster`, `thread_roster` and the
whole-space `kconfig()` are all "list what this repository has of kind X" — the
same question `search` answers, with the filter empty. Folding them in is what
let the surface reach four tools without dropping an inventory; each keeps its
OWN envelope rather than being flattened into rows, because `distinct_mutexes`,
`row_meaning`, `origin` and `found`/`error` are precisely the fields that stop a
row count being misreported as a mutex count or a parse failure as an absence.
`kind` IS ON EVERY ROW of a text corpus, which is the field that makes the
surface navigable: a caller reads it and knows what to pass `dossier` — and since
gh#372 `dossier` accepts every one of them, so the round trip actually completes.
The `diagnose` callable rides only on the SYMBOL corpus, where the match is a
conjunction a single token can empty (gh#31). Attaching it to a prose or roster
query would word an empty result with a per-token analysis of a corpus that was
never token-matched.
@brief Search or enumerate one corpus, with the subject kind on every row.
@return The corpus's envelope.
@version 8
"""
if corpus not in CORPORA:
raise ValueError(
f"Unknown corpus {corpus!r}. Known corpora: {', '.join(CORPORA)}. "
"`symbols` and `prose` RANK against `text`; `config` FILTERS its symbol "
"names by it; `locks` and `threads` list their whole layer and ignore it."
)
return CORPORA[corpus](self, text, limit, target, sub_index)
Activity · 3 steps
Requirements
unbuilt_index_message
str clew.mcp_server.tools_query.unbuilt_index_message(str repo_path="")
The one message a caller gets when the database they need does not exist yet.
clew/mcp_server/tools_query.py:1041
Source · 25 lines
def unbuilt_index_message(repo_path: str = "") -> str:
"""SPELLED ONCE, because it was spelled twice and neither copy covered the common path. The
ROUTED path checked `is_file()` and raised this; the DERIVED path did not, so a query against
a server whose target had no database raised `sqlite3.OperationalError: unable to open
database file` — naming neither the repository, nor that an index is missing, nor the call
that builds one.
That asymmetry is why `dossier` and `search` were REGISTERED conditionally: a tool that dies
with a driver error is worse than an absent one. A tool that says what to call next is better
than both, which is what lets the registration gate go away.
SPELLED IN `routing.no_index_message` SINCE gh#48, with the split-aware refusal, so the
three wordings that had already drifted once cannot drift again. This shape has no registry
behind it — it is `QueryTools` bound to one database — so it states the sentence and no
sub-index clauses.
@brief The actionable message for an index that has not been built.
@return The message.
@version 2
"""
what = repo_path or "the repository these tools are bound to"
target = f", target={repo_path!r}" if repo_path else ""
return no_index_message(what, f"index(action='refresh'{target})")