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

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
lines 1366–1366answering = self._route(target, sub_index) if target is not None else self._default()lines 1367–1397out = ( 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) ), } )lines 1401–1401out["target"] = self._target_name(answering)lines 1406–1406◇ if answering is not None and answering.sub_index is not Nonelines 1407–1407out["sub_index"] = answering.sub_indexlines 1408–1408◇ if answering.not_searchedlines 1409–1409out["not_searched"] = _bounded_names(answering.not_searched)lines 1412–1412staleness = self._staleness(out, answering)lines 1413–1413◇ if stalenesslines 1414–1414out["staleness"] = stalenesslines 1415–1415_withdraw_definitive(out, staleness)lines 1416–1416◇ if answering is not None and answering.sub_index is not Nonelines 1419–1419others = bool(answering.not_searched)lines 1420–1420◇ if others or answering.splitlines 1421–1421_scope_definitive(out, answering.sub_index, others)lines 1422–1422_scope_hit(out, answering.sub_index)lines 1423–1423◇ for entry in out.get("results") or []lines 1424–1424◇ if isinstance(entry, dict)lines 1425–1425_scope_definitive(entry, answering.sub_index, others)lines 1426–1426_scope_hit(entry, answering.sub_index)lines 1427–1427return out

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

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
lines 1525–1532out = _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, )lines 1533–1533entries = out["results"]lines 1537–1537overhead = len(json.dumps({**out, "results": []})) + 2 * len(entries)lines 1538–1538limited = _budget_batch(entries, overhead)lines 1539–1539◇ for entry in entrieslines 1540–1540wire.prune_absent_keys(entry, _DOSSIER_OPTIONAL)lines 1541–1541_wire_shape(entry)lines 1542–1542◇ if limited is not Nonelines 1543–1543out["_limited"] = limitedlines 1544–1544return self._answered(out, kind="dossiers", target=target, sub_index=sub_index)

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
lines 365–365shown = list(names[:MAX_LISTED_SIBLINGS])lines 366–366◇ if len(names) > MAX_LISTED_SIBLINGSlines 367–369shown.append( f"+{len(names) - MAX_LISTED_SIBLINGS} more — index(action='targets') lists them" )lines 370–370return shown

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

Show on the map →

Called by _batched_dossiers, test_the_small_symbol_in_a_batch_is_not_starved_by_the_large_one

Tested by

1 teststest_n_dossiers_share_the_budget_instead_of_each_claiming_it

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
lines 970–970available = RESPONSE_BUDGET_BYTES - _BATCH_LIMITED_ALLOWANCE - overheadlines 971–971sizes = [len(json.dumps(e, default=str)) for e in entries]lines 972–972adjusted: dict[str, str] = {}lines 973–973◇ for entry, share in zip(entries, _fair_shares(sizes, available), strict=True)lines 974–974cut = _shrink_to_budget(entry, _DOSSIER_LISTS, ceiling=share)lines 975–975◇ for field_name, was in cut.items()lines 976–978adjusted[f"{entry.get('name', '?')}.{field_name}"] = ( f"{was} -> {len(entry.get(field_name) or [])}" )lines 979–979◇ if not adjustedlines 980–980return Nonelines 981–991return { "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" ), }

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
lines 856–856◇ if doss is Nonelines 857–857return Nonelines 858–858cut = _shrink_to_budget(doss, _DOSSIER_LISTS)lines 859–859◇ if cutlines 864–864depth = cut.pop(CHAIN_DEPTH_CUT, None)lines 865–877doss["_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() }lines 878–878◇ if depth is not Nonelines 879–890doss["_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" ), }lines 891–891return wire.prune_absent_keys(doss, _DOSSIER_OPTIONAL)

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
lines 618–618◇ if doss is None or cap < 1lines 619–619return dosslines 620–620◇ for field_name in ("callers", "callees")lines 621–621rows = doss.get(field_name)lines 622–622◇ if not isinstance(rows, list) or len(rows) <= caplines 623–623continuelines 624–624doss[field_name] = rows[:cap]lines 625–630block = _limited_block( field_name, len(rows), cap, f"raise `max_neighbors` (currently {cap}) to list more of the {len(rows)} {field_name}", )lines 631–631block["reason"] = f"`max_neighbors` lists at most {cap} {field_name} per symbol"lines 632–632limited = doss.setdefault("_limited", {})lines 633–633◇ if field_name in limitedlines 634–636limited[field_name]["total_available"] = max( limited[field_name].get("total_available", 0), len(rows) )lines 637–637elselines 638–638limited[field_name] = blocklines 639–639return doss

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
lines 1847–1855return 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, )

Requirements

REQ-DDB-MCP-003

_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

Show on the map →

Called by _answered

Calls none

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
lines 1442–1442◇ if self._answerer is Nonelines 1443–1443return Nonelines 1444–1444trylines 1445–1445return self._answerer(None, None)lines 1446–1446except Exceptionlines 1447–1447return None

Flows

_fair_shares

list[int] clew.mcp_server.tools_query._fair_shares(list[int] sizes, int total)

Divide a byte budget between payloads so no one of them starves.

clew/mcp_server/tools_query.py:909

Show on the map →

Called by _budget_batch, test_fair_shares_gives_a_payload_that_fits_exactly_what_it_needs

Calls none

Source · 39 lines
def _fair_shares(sizes: list[int], total: int) -> list[int]:
    """MAX-MIN FAIR, not equal, and the difference is the whole point of the function.

    An equal split wastes budget: a two-field dossier for an undocumented static helper
    might serialize to 900 bytes, and handing it 6,500 anyway strands 5,600 that the
    331-caller hub in the same batch desperately needs. So every payload that fits
    inside an equal share takes exactly what it needs and RELEASES the remainder, which
    is then re-divided among the ones still over. Repeat until nobody is under.

    The failure this avoids is the one the task names: a batch where symbol 1 arrives
    complete and symbol 5 arrives empty is worse than five thin ones, because the reader
    cannot tell truncation from absence. Under max-min fairness the smallest payload is
    the LAST thing cut — no symbol is trimmed while a larger one is still above its
    share.

    Terminates: each pass either removes at least one index from `pending` or assigns
    the even share to all of them and stops.

    @brief Waterfill a byte budget across payloads.
    @return One ceiling per payload.
    @version 1
    """
    shares = [0] * len(sizes)
    pending = set(range(len(sizes)))
    remaining = total
    while pending:
        even = max(remaining // len(pending), 1)
        under = [i for i in pending if sizes[i] <= even]
        if not under:
            for i in pending:
                shares[i] = even
            break
        for i in under:
            shares[i] = sizes[i]
            remaining -= sizes[i]
            pending.discard(i)
    return shares

Activity · 15 steps
lines 931–931shares = [0] * len(sizes)lines 932–932pending = set(range(len(sizes)))lines 933–933remaining = totallines 934–934◇ while pendinglines 935–935even = max(remaining // len(pending), 1)lines 936–936under = [i for i in pending if sizes[i] <= even]lines 937–937◇ if not underlines 938–938◇ for i in pendinglines 939–939shares[i] = evenlines 940–940breaklines 941–941◇ for i in underlines 942–942shares[i] = sizes[i]lines 943–943remaining -= sizes[i]lines 944–944pending.discard(i)lines 945–945return shares

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
lines 661–666return { "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, }

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

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
lines 1807–1807out = wire.one(q.lock_roster(self.db(target, sub_index)))lines 1808–1808◇ if out is not Nonelines 1809–1809cut = _shrink_to_budget(out, ("nestings",))lines 1810–1810◇ if cutlines 1811–1818out["_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", )lines 1819–1819return self._answered(out, target=target, sub_index=sub_index)

Requirements

REQ-DDB-MCP-003

_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
lines 1271–1271◇ if not subjectlines 1272–1272return ""lines 1273–1273trylines 1274–1274return recovery_hint(self.db(target, sub_index), subject)lines 1275–1275except Exceptionlines 1276–1276return ""

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
lines 1218–1218trylines 1219–1219return self.repo(target, sub_index)lines 1220–1220except (RuntimeError, ValueError, OSError)lines 1221–1221return None

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

Show on the map →

Called by _answered, db, repo

Calls none

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
lines 1118–1118◇ if self._answerer is Nonelines 1119–1122raise RuntimeError( f"These tools cannot route to {target!r}: they are bound to a single " "repository. Call status to see which repository answers here." )lines 1123–1123return self._answerer(target, sub_index)

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

Show on the map →

Called by _answered

Calls none

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
lines 433–433note = payload.get("note")lines 434–434negative = payload.get("found") is False or payload.get("count") == 0lines 435–435◇ if not isinstance(note, str) or not negativelines 436–436returnlines 437–437◇ if not re.search(_DEFINITIVE_SPLIT, note)lines 438–438returnlines 439–439kept = re.split(_DEFINITIVE_SPLIT, note)[0].rstrip()lines 440–448where = ( "`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." )lines 449–452payload["note"] = ( f"{kept} NOT DEFINITIVE FOR THE REPOSITORY: only sub-index {answered_from!r} was " f"searched, and {where}" )

Requirements

REQ-DDB-MCP-004

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

Show on the map →

Called by _answered

Calls none

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
lines 401–401external = payload.get("external_callees")lines 402–402◇ if payload.get("found") is False or not externallines 403–403returnlines 404–406payload["scope_note"] = _UNRESOLVED_ACROSS_INDEXES.format( count=len(external), name=answered_from )

Requirements

REQ-DDB-MCP-001

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

Show on the map →

Called by none

Calls _corpus

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
lines 2108–2108return self._corpus("threads", text, limit, target, sub_index)

Requirements

REQ-DDB-QUERY-011

_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

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
lines 564–568original = { key: len(payload[key]) for key in list_keys if isinstance(payload.get(key), list) and payload[key] }lines 569–569◇ if ceiling is Nonelines 570–570ceiling = RESPONSE_BUDGET_BYTES - _LIMITED_BLOCK_ALLOWANCElines 577–577stepped: list[int] = []lines 578–578◇ while len(json.dumps(payload, default=str)) > ceilinglines 579–579dropped = _step_chain_depth(payload)lines 580–580◇ if dropped is Nonelines 581–581breaklines 582–582stepped.append(dropped)lines 584–584◇ for _ in range(64)lines 585–585◇ if len(json.dumps(payload, default=str)) <= ceilinglines 586–586breaklines 587–591biggest = max( original, key=lambda k: len(payload.get(k) or []), default=None, )lines 592–592◇ if biggest is None or len(payload.get(biggest) or []) <= 1lines 593–593breaklines 594–594payload[biggest] = payload[biggest][: max(1, len(payload[biggest]) // 2)]lines 596–596cut = {k: was for k, was in original.items() if was > len(payload.get(k) or [])}lines 597–597◇ if steppedlines 598–598cut[CHAIN_DEPTH_CUT] = max(stepped)lines 599–599return cut

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
lines 1471–1471◇ if answering is not Nonelines 1472–1472found = answering.stalenesslines 1473–1473◇ elif self._staleness_provider is not Nonelines 1474–1474found = self._staleness_provider()lines 1475–1475elselines 1476–1476return []lines 1477–1477return _staleness_within_budget(payload, found) if found else []

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

Show on the map →

Called by _staleness

Calls none

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
lines 226–226room = RESPONSE_BUDGET_BYTES - len(json.dumps(payload))lines 227–231tiers = ( found, [{"axis": n["axis"], "message": _STALENESS_COMPACT_MESSAGE} for n in found], [{"axis": n["axis"], "message": _STALENESS_MINIMAL_MESSAGE} for n in found], )lines 232–232fitting = (t for t in tiers if len(json.dumps({"staleness": t})) <= room)lines 233–233return next(fitting, tiers[-1])

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
lines 504–504chain = payload.get("chain")lines 505–505◇ if not isinstance(chain, dict)lines 506–506return Nonelines 507–507nodes = chain.get("nodes")lines 508–508◇ if not isinstance(nodes, list) or not nodeslines 509–509return Nonelines 510–510depths = [n.get("depth", 0) for n in nodes if isinstance(n, dict)]lines 511–511deepest = max(depths, default=0)lines 512–512◇ if deepest <= 1lines 513–513return Nonelines 514–514chain["nodes"] = [n for n in nodes if not (isinstance(n, dict) and n.get("depth") == deepest)]lines 515–515kept = {n.get("name") for n in chain["nodes"] if isinstance(n, dict)}lines 516–516hops = chain.get("hops")lines 517–517◇ if isinstance(hops, list)lines 518–522chain["hops"] = [ h for h in hops if isinstance(h, dict) and h.get("from_name") in kept and h.get("to_name") in kept ]lines 523–523return deepest

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

Show on the map →

Called by _answered

Calls none

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
lines 1245–1245◇ if answering is not Nonelines 1246–1246return str(answering.repo)lines 1247–1247provider = self._repo_provider if self._repo_provider is not None else self._db_providerlines 1248–1248return str(provider())

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
lines 1298–1298◇ if not subjectlines 1299–1299return ()lines 1300–1300trylines 1301–1301return q.unresolved_kinds(self.db(target, sub_index), subject)lines 1302–1302except Exceptionlines 1303–1303return ()

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
lines 821–821import oslines 823–823◇ if doss is None or os.environ.get(WIRE_ENV) != WIRE_COMPACTlines 824–824return dosslines 825–825return compact_docs(compact_neighbours(doss))

Requirements

REQ-DDB-QUERY-014

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

Show on the map →

Called by dossier

Calls none

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
lines 1754–1754◇ if self.wiki_linker is None or reply.get("found") is Falselines 1755–1755return replylines 1756–1756◇ if reply.get("subject_kind") != "function" or not reply.get("file")lines 1757–1757return replylines 1758–1758trylines 1759–1759url = self.wiki_linker(str(reply.get("target")), str(reply["name"]), str(reply["file"]))lines 1760–1760except Exceptionlines 1761–1761logger.debug("wiki link failed for %s", reply.get("name"))lines 1762–1762url = Nonelines 1763–1763◇ if urllines 1764–1764reply["wiki_url"] = urllines 1765–1765return reply

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

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
lines 324–324note = payload.get("note")lines 325–325◇ if not isinstance(note, str)lines 326–326returnlines 327–327axes = {n.get("axis") for n in staleness}lines 331–331replacement = Nonelines 332–332◇ if _SCHEMA_AXIS in axeslines 333–333replacement = _UNEARNED_DEFINITIVElines 334–334◇ elif _PARTIAL_AXIS in axeslines 335–335replacement = _UNEARNED_BY_PARTIALlines 336–336◇ elif _DERIVED_AXIS in axeslines 337–337replacement = _UNEARNED_BY_DERIVEDlines 338–338◇ elif _DATA_AXIS in axes and payload.get("found") is Falselines 339–339replacement = _UNEARNED_BY_DRIFTlines 340–340◇ if replacement is Nonelines 341–341returnlines 342–342lowered = note.lower()lines 343–343◇ if not any(claim in lowered for claim in _DEFINITIVE_CLAIMS)lines 344–344returnlines 349–349kept = re.split(r"(?i)this is a definitive|do not retry", note)[0].rstrip()lines 350–350payload["note"] = f"{kept}{replacement}"

Requirements

REQ-DDB-MCP-004

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

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
lines 1144–1144◇ if target is not Nonelines 1145–1145return self._route(target, sub_index).dblines 1146–1146◇ if sub_index is not Nonelines 1147–1150raise 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." )lines 1155–1155db = Path(self._db_provider())lines 1156–1156◇ if not db.is_file()lines 1157–1157raise RuntimeError(unbuilt_index_message())lines 1158–1158return db

Requirements

REQ-DDB-MCP-003

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

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's

55 more lines, not shown

Activity · 9 steps
lines 1714–1714◇ if not isinstance(subject, str)lines 1715–1715names, overflow = _accepted_batch(list(subject), qualified)lines 1716–1716reply = self._batched_dossiers(names, kind, target, sub_index, max_body_lines, depth)lines 1717–1717disclose_overflow(reply, overflow)lines 1718–1718return replylines 1719–1731payload = _export.subject_payload( self.db(target, sub_index), subject, kind=kind, qualified=qualified, repo_root=self._repo_or_none(target, sub_index), max_body_lines=max_body_lines, depth=depth, direction=direction, ## THE WALK KEEPS ITS OWN FAN-OUT (8 per hop) unless the caller set one: widening every ## hop of a depth-3 walk was never the point of capping the depth-1 lists. max_neighbors=max_neighbors if max_neighbors is not None else CHAIN_MAX_NEIGHBORS, )lines 1732–1732cap = max_neighbors if max_neighbors is not None else DEFAULT_MAX_NEIGHBORSlines 1733–1739reply = self._answered( _wire_shape(_capped_neighbors(_budgeted_dossier(payload), cap)), kind="dossier", subject=subject, target=target, sub_index=sub_index, )lines 1740–1740return self._with_wiki_url(reply)

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
lines 1881–1886return self._answered( wire.one(q.graph_stats(self.db(target, sub_index))), kind="graph statistics", target=target, sub_index=sub_index, )

Requirements

REQ-DDB-MCP-003

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
lines 1180–1180◇ if target is not Nonelines 1181–1181return self._route(target, sub_index).repolines 1182–1182◇ if self._repo_provider is Nonelines 1183–1187raise 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=." )lines 1188–1188return self._repo_provider()

Requirements

REQ-DDB-MCP-003

Flows

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})")

Activity · 3 steps
lines 1061–1061what = repo_path or "the repository these tools are bound to"lines 1062–1062target = f", target={repo_path!r}" if repo_path else ""lines 1063–1063return no_index_message(what, f"index(action='refresh'{target})")

Requirements

REQ-DDB-MCP-003