payload.py

clew/query/payload.py

The answer-content transforms a dossier or search reply carries on every surface.

_accepted_batch

tuple[list[str], list[str]] clew.query.payload._accepted_batch(list[str] names, str|None qualified)

Validate and normalise a batch request: de-duplicate, split off what is over the cap.

clew/query/payload.py:651

Source · 28 lines
def _accepted_batch(names: list[str], qualified: str | None) -> tuple[list[str], list[str]]:
    """TWO REFUSALS REMAIN, one rule changed. An empty list would answer `count: 0` to a request
    that asked for something, and `qualified` beside a list would scope every dossier by one
    identity key that belongs to at most one of them — both still raise.

    OVER THE CAP NO LONGER RAISES (owner, 2026-11-13). The refusal cost a second call every time
    an agent asked for nine; the answer for the first eight plus `not_answered` naming the rest
    keeps what the refusal protected — a truncated request never reads as a complete one —
    without the round trip.

    De-duplication removes no information: the same name twice has one answer.

    @brief Normalise a batch request or raise.
    @return (answered, not answered).
    @version 2
    """
    if qualified is not None:
        raise ValueError(
            "`qualified` selects ONE identity among same-named functions, so it cannot "
            "be combined with a list of symbols. Call dossier with that single name and "
            "its qualified spelling, then batch the rest."
        )
    unique = list(dict.fromkeys(names))
    if not unique:
        raise ValueError("dossier needs at least one function name.")
    return unique[: q.MAX_BATCH_SYMBOLS], unique[q.MAX_BATCH_SYMBOLS :]

Activity · 6 steps
lines 667–667◇ if qualified is not Nonelines 668–672raise ValueError( "`qualified` selects ONE identity among same-named functions, so it cannot " "be combined with a list of symbols. Call dossier with that single name and " "its qualified spelling, then batch the rest." )lines 673–673unique = list(dict.fromkeys(names))lines 674–674◇ if not uniquelines 675–675raise ValueError("dossier needs at least one function name.")lines 676–676return unique[: q.MAX_BATCH_SYMBOLS], unique[q.MAX_BATCH_SYMBOLS :]

Flows

_ambiguity_block

dict[str, Any] | None clew.query.payload._ambiguity_block(Path db, Any built)

The same-name ambiguity behind a function subject's neighbour lists, or None.

clew/query/payload.py:41

Source · 50 lines
def _ambiguity_block(db: Path, built: Any) -> dict[str, Any] | None:
    """`candidates` DISAMBIGUATES THE IDENTITY; NOTHING DISAMBIGUATES THE EDGES. That
    sentence is this repo's own recorded finding (gh#26): `dossier('_classify')` names
    three same-named functions in `candidates` and then lists the UNION of all three
    functions' neighbours, at `confidence: exact`, because corroboration means three
    layers agreed and all three resolve by name. A reader who checks `candidates` and
    then reads `callers` is still misled.

    So the block ships on the composite payload, where it never used to be. It was on the
    deleted `callers`/`callees` tools only — i.e. on the two surfaces a model reaches for
    SECOND — while the tool it is told to call FIRST said nothing. Folding those tools in
    without their disclosure would have removed the warning from the whole surface.

    IT DISCLOSES, IT DOES NOT TRIM. The standalone tools capped an ambiguous list at a
    sample; the composite dossier never did, and adding a cap here would change what a
    call returns in order to deliver a warning about it. The budget trimmer is the only
    thing that removes rows, and it says so separately.

    @brief Disclose same-name edge ambiguity on a function subject.
    @return {direction: block} for each ambiguous direction, or None.
    @version 1
    """
    if built.function is None:
        return None
    blocks: dict[str, Any] = {}
    for field_name, want_callers in (("callers", True), ("callees", False)):
        found = q.name_ambiguity(db, built.function.name, want_callers=want_callers)
        if found is None:
            continue
        blocks[field_name] = {
            "name": found.name,
            "candidates": found.candidates,
            "shared_rows": found.shared_rows,
            "why": (
                f"'{found.name}' matches {found.candidates} distinct function "
                f"signatures. {found.shared_rows} of the {field_name} rows were "
                "recovered from member calls that name only the unqualified tail, so the "
                "receiver's type was never checked and the SAME rows belong to every one "
                "of those functions. At most one per call site is real."
            ),
            "how_to_narrow": (
                "`candidates` in this same payload carries a `qualified` per identity; re-ask "
                "dossier with `qualified=` set to the one you mean — that field, not the "
                f"`signature`. Do NOT report these as {field_name} of a specific overload "
                f"until you have."
            ),
        }
    return blocks or None

Activity · 9 steps
lines 63–63◇ if built.function is Nonelines 64–64return Nonelines 65–65blocks: dict[str, Any] = {}lines 66–66◇ for field_name, want_callers in (("callers", True), ("callees", False))lines 67–67found = q.name_ambiguity(db, built.function.name, want_callers=want_callers)lines 68–68◇ if found is Nonelines 69–69continuelines 70–87blocks[field_name] = { "name": found.name, "candidates": found.candidates, "shared_rows": found.shared_rows, "why": ( f"'{found.name}' matches {found.candidates} distinct function " f"signatures. {found.shared_rows} of the {field_name} rows were " "recovered from member calls that name only the unqualified tail, so the " "receiver's type was never checked and the SAME rows belong to every one " "of those functions. At most one per call site is real." ), "how_to_narrow": ( "`candidates` in this same payload carries a `qualified` per identity; re-ask " "dossier with `qualified=` set to the one you mean — that field, not the " f"`signature`. Do NOT report these as {field_name} of a specific overload " f"until you have." ), }lines 88–88return blocks or None

Flows

_batch_miss

dict[str, Any] clew.query.payload._batch_miss(str name, tuple[str,...] unresolved=(), str hint="")

The reply for a batched name that resolves to nothing.

clew/query/payload.py:618

Source · 25 lines
def _batch_miss(name: str, unresolved: tuple[str, ...] = (), hint: str = "") -> dict[str, Any]:
    """PER SYMBOL, NEVER PER CALL. One unresolvable name in a batch of five must not
    fail the other four, and it must not vanish either: a dropped entry would silently
    re-align the reader's mapping from names to answers, which is a worse error than the
    miss it is hiding.

    Wording is the short form of `_answered`'s miss note. The long one repeats the
    target-and-staleness advice, which is already stamped ONCE on the batch envelope
    rather than eight times inside it.

    @brief Miss envelope for one name in a batch.
    @return The miss entry.
    @version 2
    """
    return {
        "name": name,
        "found": False,
        "note": (
            "Not indexed in this repository. A definitive negative from the database, "
            "not an error — check the envelope's `target` before concluding it does not "
            "exist." + _kind_limitation_clause(unresolved) + hint
        ),
    }

Activity · 1 steps
lines 632–640return { "name": name, "found": False, "note": ( "Not indexed in this repository. A definitive negative from the database, " "not an error — check the envelope's `target` before concluding it does not " "exist." + _kind_limitation_clause(unresolved) + hint ), }

Flows

_candidates_capped

dict[str, Any] | None clew.query.payload._candidates_capped(Path|None db, dict[str, Any] payload)

Disclose that the candidate list hit its cap, and how many identities really exist.

clew/query/payload.py:247

Source · 42 lines
def _candidates_capped(db: Path | None, payload: dict[str, Any]) -> dict[str, Any] | None:
    """SILENT TRUNCATION ON THE ONE FIELD WHOSE JOB IS DISAMBIGUATION. `MAX_CANDIDATES` is 8 and
    `candidate_rows` slices to it with no disclosure, so `dossier("main")` on mbedtls returned 8 of
    **143** `main` rows and the one that mattered — the stub `main` in `ssl_pthread_server.c` that
    a non-threading build compiles — was not among them. There was no `_limited` entry, no count,
    nothing to say a choice had been made: `candidates` reads as "the identities this name has".
    That is the failure every other cap on this surface refuses or discloses to avoid.

    NOT `_limited_block`, deliberately. That block states "the full response exceeded the
    65,536-byte cap", which is a different and here FALSE reason — this list is capped by policy
    regardless of size, and a disclosure that misattributes its own cause sends a reader to shrink
    a payload that was never too big.

    COUNTED, NOT ESTIMATED. `total_available` is the whole point: "this name has 143 signatures" is
    more useful than the eight rows, and it is what tells a reader that `qualified=` is now
    mandatory rather than optional.

    @brief Say the candidate list was capped and how many identities exist.
    @return The disclosure, or None.
    @version 1
    """
    shown = payload.get("candidates")
    if db is None or not isinstance(shown, list) or len(shown) < _MAX_CANDIDATES:
        return None
    total = _distinct_identities(db, str(payload.get("subject") or ""))
    if total <= len(shown):
        return None
    return {
        "reason": (
            f"`candidates` is capped at {_MAX_CANDIDATES} identities by policy, not by response "
            f"size"
        ),
        "adjusted": {"candidates": f"{total} -> {len(shown)}"},
        "total_available": total,
        "how_to_narrow": (
            "The listed rows are a SAMPLE, not the identity set. Re-ask with `qualified=` set to "
            "a `candidates[i].qualified` — the qualified name, not the signature; `search` can "
            "enumerate the rest."
        ),
    }

Activity · 7 steps
lines 268–268shown = payload.get("candidates")lines 269–269◇ if db is None or not isinstance(shown, list) or len(shown) < _MAX_CANDIDATESlines 270–270return Nonelines 271–271total = _distinct_identities(db, str(payload.get("subject") or ""))lines 272–272◇ if total <= len(shown)lines 273–273return Nonelines 274–286return { "reason": ( f"`candidates` is capped at {_MAX_CANDIDATES} identities by policy, not by response " f"size" ), "adjusted": {"candidates": f"{total} -> {len(shown)}"}, "total_available": total, "how_to_narrow": ( "The listed rows are a SAMPLE, not the identity set. Re-ask with `qualified=` set to " "a `candidates[i].qualified` — the qualified name, not the signature; `search` can " "enumerate the rest." ), }

Flows

_compact_gate_panel

dict[str, Any] clew.query.payload._compact_gate_panel(dict[str, Any] payload)

State a gate panel's invariant fields once instead of once per row.

clew/query/payload.py:712

Show on the map →

Called by _config_found_on_the_wire, test_a_single_row_still_round_trips, test_a_varying_field_stays_on_the_rows, test_invariant_fields_are_hoisted_off_the_rows, test_nothing_to_compact_is_left_untouched, test_the_panel_gets_materially_smaller

Calls none

Source · 48 lines
def _compact_gate_panel(payload: dict[str, Any]) -> dict[str, Any]:
    """MEASURED on the rebuilt mbedtls index: `dossier("MBEDTLS_THREADING_C")` serves 154 gate
    rows at 39,884 bytes, and `symbol`, `macro`, `form`, `default_state` and `default_site` each
    hold ONE distinct value across all 154. Only `file_path` varies, over 31 files. The panel
    repeats ~185 bytes of invariant text 154 times.

    WHY BYTES HERE COST MORE THAN THEY LOOK. `cache_read` is 98% of the tokens this harness
    spends — 3,470,671 against 62,559 output on the `index_only` arm — because every byte served
    sits in the context and is re-read on each later turn. A 40 KB reply at turn 3 of 20 costs
    roughly 800 KB of `cache_read` by itself. Gate panels are 11.8% of all `dossier` reply bytes
    across the grid.

    NOTHING IS REMOVED, WHICH IS THE WHOLE POINT. A cost win that drops evidence trades one axis
    for the other, and a gain on one axis only counts if the other holds. Every value a reader
    could have read off a row is still in the reply — once rather than N times.

    PER FIELD, NOT ALL-OR-NOTHING, AND NEVER A FIELD THAT VARIES. Two sites of one symbol can
    genuinely disagree — a macro defined in one profile and undefined in another — and hoisting
    the majority value would state as settled a thing the index reports as varying. A field is
    hoisted only when every row carries the identical value.

    THE WIRE ONLY. `KconfigGate` keeps every field, so the library API and the tests reading
    `gates[0].default_state` are untouched. Same placement as the `found`/`kconfig_found`
    reconciliation above, for the same reason: the dataclass is right, the serialization was
    wasteful.

    @brief Hoist invariant gate fields to the panel.
    @return The compacted payload.
    @version 1
    """
    rows = payload.get("gates")
    if not isinstance(rows, list) or not rows:
        return payload
    shared = {}
    for field in _GATE_INVARIANTS:
        values = {json.dumps(r.get(field)) for r in rows if isinstance(r, dict)}
        if len(values) == 1 and field in rows[0]:
            shared[field] = rows[0][field]
    if not shared:
        return payload
    out = dict(payload)
    out["gates_shared"] = shared
    out["gates"] = [
        {k: v for k, v in r.items() if k not in shared} if isinstance(r, dict) else r for r in rows
    ]
    return out

Activity · 14 steps
lines 742–742rows = payload.get("gates")lines 743–743◇ if not isinstance(rows, list) or not rowslines 744–744return payloadlines 745–745shared = {}lines 746–746◇ for field in _GATE_INVARIANTSlines 747–747values = {json.dumps(r.get(field)) for r in rows if isinstance(r, dict)}lines 748–748◇ if len(values) == 1 and field in rows[0]lines 749–749shared[field] = rows[0][field]lines 750–750◇ if not sharedlines 751–751return payloadlines 752–752out = dict(payload)lines 753–753out["gates_shared"] = sharedlines 754–756out["gates"] = [ {k: v for k, v in r.items() if k not in shared} if isinstance(r, dict) else r for r in rows ]lines 757–757return out

Flows

_config_found_on_the_wire

dict[str, Any] clew.query.payload._config_found_on_the_wire(dict[str, Any] payload)

Re-key a config payload so found means what it means everywhere else.

clew/query/payload.py:767

Source · 31 lines
def _config_found_on_the_wire(payload: dict[str, Any]) -> dict[str, Any]:
    """Split out of `_search_config` so the re-keying is testable without a tool set, and so the
    one place the two meanings are reconciled is named rather than inline.

    `found` BECOMES A STATEMENT ABOUT THIS REPLY: did it carry any symbol names. That is what the
    rest of the surface means by the word and what `_verdict` tests for. A corpus that genuinely
    matched nothing still reports False, so this trades no false negative for a false positive —
    which would be the worse direction, because a reader cannot check a false positive.

    THE DISCOVERY FACT IS MOVED, NOT DROPPED. "No Kconfig in this repository" and "a Kconfig that
    failed to parse" are different facts, `error` carries the second and `kconfig_found` now
    carries the first. Deleting it to resolve the collision would be fixing a misleading field by
    removing a true one.

    @brief Reconcile the two meanings of `found` on the config reply.
    @return The re-keyed payload.
    @version 1
    """
    if "found" not in payload:
        return payload
    out = dict(payload)
    out["kconfig_found"] = out["found"]
    names = out.get("gate_symbol_names") or ()
    symbols = out.get("symbols") or ()
    gates = out.get("gates") or ()
    out["found"] = bool(names or symbols or gates)
    ## COMPACTED HERE so all three routes that serialize a `KconfigSpace` inherit it, which is the
    ## lesson of the `found` collision one function up: fixing one route left two broken.
    return _compact_gate_panel(out)

Activity · 9 steps
lines 785–785◇ if "found" not in payloadlines 786–786return payloadlines 787–787out = dict(payload)lines 788–788out["kconfig_found"] = out["found"]lines 789–789names = out.get("gate_symbol_names") or ()lines 790–790symbols = out.get("symbols") or ()lines 791–791gates = out.get("gates") or ()lines 792–792out["found"] = bool(names or symbols or gates)lines 795–795return _compact_gate_panel(out)

Flows

_constructor_note

str clew.query.payload._constructor_note(tuple[str,...] also)

Note for an empty caller list on a name that is also a class.

clew/query/payload.py:175

Source · 26 lines
def _constructor_note(also: tuple[str, ...]) -> str:
    """gh#4's rule, kept because it answers on an index that carries no measurement — and
    because it names a DIFFERENT missing thing: not a call whose receiver went unresolved, but a
    construction the grammar records no call for at all.

    NARROWED BY gh#15. `std::make_unique<T>` and `make_shared<T>` now DO resolve to the
    constructor, and a direct `T(...)` always did, so the blanket "construction is not modelled"
    is no longer true and would send a reader looking for a gap that has been closed. What
    remains unmodelled is brace initialisation, which is what gh#4 was reported against.

    @brief Say that an empty caller list may be a missing brace-initialised construction.
    @return The note, or "".
    @version 1
    """
    if "class" not in also:
        return ""
    return (
        "`callers` is EMPTY and this name also resolves to a class, so this is very likely a "
        "constructor. Brace-initialised construction (`T x{...}`) is NOT modelled as a call "
        "edge, so an empty list here does NOT mean nothing constructs this type — though "
        "`T(...)` and `std::make_unique<T>` / `make_shared<T>` do resolve. Ask `dossier` for the "
        "CLASS (kind='class') and read `candidates`, or `search` the type name, before "
        "concluding it has no users."
    )

Activity · 3 steps
lines 189–189◇ if "class" not in alsolines 190–190return ""lines 191–198return ( "`callers` is EMPTY and this name also resolves to a class, so this is very likely a " "constructor. Brace-initialised construction (`T x{...}`) is NOT modelled as a call " "edge, so an empty list here does NOT mean nothing constructs this type — though " "`T(...)` and `std::make_unique<T>` / `make_shared<T>` do resolve. Ask `dossier` for the " "CLASS (kind='class') and read `candidates`, or `search` the type name, before " "concluding it has no users." )

Flows

_distinct_identities

int clew.query.payload._distinct_identities(Path db, str name)

How many distinct function identities a bare name really has.

clew/query/payload.py:212

Source · 23 lines
def _distinct_identities(db: Path, name: str) -> int:
    """COUNTED FROM THE SAME PREDICATE `candidate_rows` SLICES, so the total and the sample cannot
    describe different sets. Tolerates any failure with 0, because this runs while decorating an
    answer that already succeeded and a disclosure must never be the thing that breaks a reply.

    @brief Count same-named function rows.
    @return The count, or 0.
    @version 1
    """
    if not name:
        return 0
    try:
        with _common.connect(db) as conn:
            if not _common.table_exists(conn, "memberdef"):
                return 0
            row = conn.execute(
                "SELECT COUNT(*) FROM memberdef WHERE name=? AND kind='function'", (name,)
            ).fetchone()
    except Exception:
        return 0
    return int(row[0]) if row else 0

Activity · 10 steps
lines 221–221◇ if not namelines 222–222return 0lines 223–223trylines 224–224with _common.connect(db) as connlines 225–225◇ if not _common.table_exists(conn, "memberdef")lines 226–226return 0lines 227–229row = conn.execute( "SELECT COUNT(*) FROM memberdef WHERE name=? AND kind='function'", (name,) ).fetchone()lines 230–230except Exceptionlines 231–231return 0lines 232–232return int(row[0]) if row else 0

Flows

_edge_defaults

dict[str, Any] clew.query.payload._edge_defaults(list[dict[str, Any]] rows)

The value of each defaultable field that every row carries and at least two share.

clew/query/payload.py:840

Source · 14 lines
def _edge_defaults(rows: list[dict[str, Any]]) -> dict[str, Any]:
    """@brief Pick per-field modal values. @return Defaults."""
    from collections import Counter

    defaults: dict[str, Any] = {}
    for field in _DEFAULTABLE:
        if not all(field in r for r in rows):
            continue
        value, count = Counter(str(r[field]) for r in rows).most_common(1)[0]
        if count >= 2:
            defaults[field] = next(r[field] for r in rows if str(r[field]) == value)
    return defaults

Activity · 9 steps
lines 842–842from collections import Counterlines 844–844defaults: dict[str, Any] = {}lines 845–845◇ for field in _DEFAULTABLElines 846–846◇ if not all(field in r for r in rows)lines 847–847continuelines 848–848value, count = Counter(str(r[field]) for r in rows).most_common(1)[0]lines 849–849◇ if count >= 2lines 850–850defaults[field] = next(r[field] for r in rows if str(r[field]) == value)lines 851–851return defaults

Flows

_empty_callers_note

str clew.query.payload._empty_callers_note(dict[str, Any] payload, tuple[str,...] also)

Warn when an empty callers is a modelling gap rather than a real absence.

clew/query/payload.py:108

Show on the map →

Called by _flatten_subject, test_a_measured_refusal_is_named_in_the_note, test_a_measured_zero_gets_no_note, test_an_empty_caller_list_on_a_constructor_is_qualified, test_an_unmeasured_index_falls_back_to_the_constructor_rule, test_the_measured_note_wins_over_the_constructor_heuristic

Calls _constructor_note, _refusal_note

Source · 35 lines
def _empty_callers_note(payload: dict[str, Any], also: tuple[str, ...]) -> str:
    """gh#4, AND IT CHANGED A REAL DECISION. A reporter asked `dossier("ProgressBar")`, got the
    constructor with `callers: []`, and reported the class as having two production callers in a
    commit message. It has one. Four brace-initialised construction sites existed; none was a call
    edge.

    "HOW MANY CALLERS DOES THIS HAVE" IS THE QUESTION THAT DECIDES WHETHER A SHARED PRIMITIVE CAN
    BE CHANGED, so an empty list there is not a neutral fact — it is a green light. Everything else
    in that same reply was right: free functions returned their callers at `confidence: "exact"`,
    a constexpr variable returned its declaration site. It is specifically the CONSTRUCTOR edge
    that is absent.

    THE SIGNAL IS `also`. A name that resolves as BOTH a function and a class is a constructor in
    every case this can see, and that is a fact already on the payload rather than a new
    extraction — which is why this is a wording fix and not a pipeline change.

    NOT A DISCLAIMER ON EVERY EMPTY LIST. A free function with no callers genuinely has none, and
    annotating that would train a reader to ignore the annotation. The reporter's own words: option
    (3) alone would have prevented the error.

    gh#15 MADE THE SIGNAL A MEASUREMENT. `also` says what KIND of symbol this is; the build now
    records what it actually REFUSED, per symbol, so the strong case no longer has to be inferred
    from a category. The measured branch therefore wins where both apply — it is a fact about
    this symbol, where `also` is a fact about its name — and a measured ZERO says nothing at all,
    which is what lets an ordinary empty list keep its full confidence.

    @brief Say that an empty caller list may be a missing construction edge.
    @return The note, or "".
    @version 2
    """
    if payload.get("subject_kind") != "function" or payload.get("callers"):
        return ""
    return _refusal_note(payload.get("callers_unresolved")) or _constructor_note(also)

Activity · 3 steps
lines 138–138◇ if payload.get("subject_kind") != "function" or payload.get("callers")lines 139–139return ""lines 140–140return _refusal_note(payload.get("callers_unresolved")) or _constructor_note(also)

Flows

_flatten_subject

dict[str, Any] | None clew.query.payload._flatten_subject(Any built, Path|None db=None, int depth=1)

Flatten a SubjectDossier to the wire shape: envelope keys plus the one section.

clew/query/payload.py:301

Source · 66 lines
def _flatten_subject(built: Any, db: Path | None = None, depth: int = 1) -> dict[str, Any] | None:
    """FLAT, NOT NESTED, and the reason is the budget rather than taste. Every trimmer on
    this surface — `_DOSSIER_LISTS`, `_shrink_to_budget`, `_budget_batch` — addresses
    TOP-LEVEL keys, so a payload that buried `callers` one level down under a `function`
    key would have silently stopped being budgeted at all: the 125,559-byte reply that
    motivated the cap would have come back, with the cap still in the code and still
    passing its tests.

    It is also the better shape for a reader. `subject_kind` names what resolved and the
    section's own fields sit beside it, so a variable payload has `sites` and simply has
    no `callers` key — which is what "say so by ABSENCE" means in practice.

    `also` and `chain` are elided when empty, like every other added key on this surface;
    `subject` and `subject_kind` are always present because a consumer branches on them.

    @brief Serialize a subject dossier to its flat wire form.
    @return Flat payload dict, or None.
    @version 6
    """
    if built is None:
        return None
    section = wire.one(built.section)
    if section is None:
        return None
    payload: dict[str, Any] = {"subject": built.subject, "subject_kind": built.kind, **section}
    ## THE CONFIG SECTION BRINGS ITS OWN `found`, meaning "a Kconfig FILE was located", which
    ## collides with what `found` means everywhere else on this surface. Replayed against the
    ## frozen mbedtls index: `dossier("MBEDTLS_THREADING_C")` served 154 gate rows,
    ## `gate_symbols: 1107` and `found: false` in one reply. Reconciled by the same helper
    ## `_search_config` uses — one rule wherever that dataclass reaches the wire, because fixing
    ## the search route alone is exactly how this one stayed broken.
    if built.kind == "config":
        payload = _config_found_on_the_wire(payload)
    ## AN INDEX THAT NEVER SCANNED FOR MENTIONS has no field, not a null one: `mentioned_in: []`
    ## and `mentioned_in: null` would both read as "nothing names this requirement".
    ## Same rule for the GH #68 links: an index from before `requirement_links` has neither key,
    ## and for `failure_modes` (2.2): a requirement that declares none has no key.
    if built.kind == "requirement":
        for key in ("mentioned_in", "satisfies", "satisfied_by", "failure_modes"):
            if payload.get(key) is None:
                payload.pop(key, None)
    if built.also:
        payload["also"] = list(built.also)
    if built.chain is not None:
        payload["chain"] = wire.one(built.chain)
    elif depth > 1:
        payload["depth_note"] = _NO_SEED_NOTE
    ambiguity = None if db is None else _ambiguity_block(db, built)
    if ambiguity:
        payload["ambiguous"] = ambiguity
    gates, gate_gaps = (None, None) if db is None else _gate_definitions(db, payload)
    if gates:
        payload["gate_definitions"] = gates
    if gate_gaps:
        payload["gate_definitions_limited"] = gate_gaps
    ## PRESENT ONLY WHEN IT APPLIES, like every other added key here — an annotation on every
    ## empty list is one a reader learns to skip.
    callers_note = _empty_callers_note(payload, built.also or ())
    if callers_note:
        payload["callers_note"] = callers_note
    capped = _candidates_capped(db, payload)
    if capped:
        payload["candidates_limited"] = capped
    return payload

Activity · 33 steps
lines 320–320◇ if built is Nonelines 321–321return Nonelines 322–322section = wire.one(built.section)lines 323–323◇ if section is Nonelines 324–324return Nonelines 325–325payload: dict[str, Any] = {"subject": built.subject, "subject_kind": built.kind, **section}lines 332–332◇ if built.kind == "config"lines 333–333payload = _config_found_on_the_wire(payload)lines 338–338◇ if built.kind == "requirement"lines 339–339◇ for key in ("mentioned_in", "satisfies", "satisfied_by", "failure_modes")lines 340–340◇ if payload.get(key) is Nonelines 341–341payload.pop(key, None)lines 342–342◇ if built.alsolines 343–343payload["also"] = list(built.also)lines 344–344◇ if built.chain is not Nonelines 345–345payload["chain"] = wire.one(built.chain)lines 346–346◇ elif depth > 1lines 347–347payload["depth_note"] = _NO_SEED_NOTElines 348–348ambiguity = None if db is None else _ambiguity_block(db, built)lines 349–349◇ if ambiguitylines 350–350payload["ambiguous"] = ambiguitylines 351–351gates, gate_gaps = (None, None) if db is None else _gate_definitions(db, payload)lines 352–352◇ if gateslines 353–353payload["gate_definitions"] = gateslines 354–354◇ if gate_gapslines 355–355payload["gate_definitions_limited"] = gate_gapslines 358–358callers_note = _empty_callers_note(payload, built.also or ())lines 359–359◇ if callers_notelines 360–360payload["callers_note"] = callers_notelines 361–361capped = _candidates_capped(db, payload)lines 362–362◇ if cappedlines 363–363payload["candidates_limited"] = cappedlines 364–364return payload

Flows

_gate_definition_gaps

dict[str, Any] | None clew.query.payload._gate_definition_gaps(list[str] no_sites, list[str] not_attempted)

Disclose which gate symbols were not resolved, and why each was not.

clew/query/payload.py:423

Source · 42 lines
def _gate_definition_gaps(no_sites: list[str], not_attempted: list[str]) -> dict[str, Any] | None:
    """TWO GAPS THAT LOOKED IDENTICAL AND MEAN OPPOSITE THINGS.

    `no_definition_site` is a FACT ABOUT THE REPOSITORY, and often it is the answer: a
    `//#define MBEDTLS_THREADING_C` is a definition the preprocessor never sees, so it produces no
    `memberdef` row and the index holds none. "This gate is nowhere actively defined" is exactly
    what a reader asking about the shipped default needs.

    `not_attempted` is a fact about THIS TOOL — the cap ran out. It promises more exists; it claims
    nothing about the repository.

    Collapsing both into one absent key made a real answer indistinguishable from a truncation.

    NAMED, NEVER COUNTED. A count leaves a reader unable to ask for the one they care about, which
    is exactly how the cap hurt: the symbol two graded marks ask about was tenth alphabetically and
    silently vanished.

    @brief Say which gates did not resolve and which were never tried.
    @return The disclosure, or None.
    @version 1
    """
    if not no_sites and not not_attempted:
        return None
    gaps: dict[str, Any] = {}
    if no_sites:
        gaps["no_definition_site"] = no_sites
        gaps["no_definition_site_means"] = (
            "The index holds NO definition site for these. That is usually a fact about the "
            "repository rather than a gap: a commented-out `//#define` is not a definition the "
            "preprocessor sees, so it produces no row. Read the header named in `config_header` "
            "to confirm the shipped default."
        )
    if not_attempted:
        gaps["not_attempted"] = not_attempted
        gaps["not_attempted_means"] = (
            f"More than {_GATE_DEFINITION_CAP} distinct gates guard this code, so these were not "
            f"looked up. Ask `dossier` for one by name. Their absence above is this tool's cap, "
            f"NOT a statement about the repository."
        )
    return gaps

Activity · 10 steps
lines 444–444◇ if not no_sites and not not_attemptedlines 445–445return Nonelines 446–446gaps: dict[str, Any] = {}lines 447–447◇ if no_siteslines 448–448gaps["no_definition_site"] = no_siteslines 449–454gaps["no_definition_site_means"] = ( "The index holds NO definition site for these. That is usually a fact about the " "repository rather than a gap: a commented-out `//#define` is not a definition the " "preprocessor sees, so it produces no row. Read the header named in `config_header` " "to confirm the shipped default." )lines 455–455◇ if not_attemptedlines 456–456gaps["not_attempted"] = not_attemptedlines 457–461gaps["not_attempted_means"] = ( f"More than {_GATE_DEFINITION_CAP} distinct gates guard this code, so these were not " f"looked up. Ask `dossier` for one by name. Their absence above is this tool's cap, " f"NOT a statement about the repository." )lines 462–462return gaps

Flows

_gate_definitions

dict[str, Any] clew.query.payload._gate_definitions(Any db, dict[str, Any] payload)

Resolve the symbols a payload's gated_by rows NAME to where they are defined.

clew/query/payload.py:471

Source · 61 lines
def _gate_definitions(db: Any, payload: dict[str, Any]) -> dict[str, Any]:
    """A NAMED UNKNOWN IN A PAYLOAD IS AN INSTRUCTION TO GO LOOKING. `gated_by` said the code is
    conditional on `MBEDTLS_ALLOW_PRIVATE_ACCESS` and never said where that symbol is DEFINED, so
    the reply left an open loop: a name the caller now needs and cannot resolve from what it holds.

    Measured on mbedtls 2026-08-14. The Q2 cell had the two `#if` branches of `MBEDTLS_PRIVATE` in
    hand — the whole direction-of-the-default answer — and then ran `Grep MBEDTLS_ALLOW_PRIVATE_ACCESS`
    FOUR TIMES with widening scope rather than making one more index call. Those four greps are
    half that cell's fallbacks. The three sites they were hunting are `library/common.h:132`,
    `programs/ssl/ssl_client2.c:8` and `programs/ssl/ssl_server2.c:8` — and two of them are graded
    marks, so the gap cost accuracy as well as tokens.

    THE COST ARGUMENT IS DECISIVE HERE. Resolving every distinct gate symbol adds a few hundred
    bytes; the call it removes costs a full context re-read. There is no version of this trade
    where withholding the sites wins.

    WHY IT RESOLVES RATHER THAN HINTING. `_DOSSIER_HINTS['gated_by']` already points at `kconfig`
    for the configuration SPACE, which is a different question — "what are the build variants"
    rather than "where is this one symbol written down". A hint the caller must act on is still a
    turn; the answer is not.

    DISTINCT SYMBOLS ONLY, AND SELF-REFERENCE DROPPED: a config symbol's own dossier lists itself
    among its gates, and echoing its definition sites back under a second key would be pure
    duplication of the payload it is already in.

    @brief Attach each gate symbol's definition sites, and disclose what was not resolved.
    @return (gate symbol -> definition sites, disclosure or None).
    @version 3
    """
    rows = payload.get("gated_by") or []
    subject = payload.get("name") or payload.get("subject")
    names = sorted(
        {
            str(row["symbol"])
            for row in rows
            if isinstance(row, dict) and row.get("symbol") and row["symbol"] != subject
        }
    )
    out: dict[str, Any] = {}
    ## ATTEMPTED-AND-EMPTY IS NOT NOT-ATTEMPTED. `if sites:` dropped the key for a symbol whose
    ## definition site the index genuinely does not hold — a commented-out `//#define` produces no
    ## `memberdef` row at all — so its absence from this map was indistinguishable from having been
    ## capped out. Two different answers wearing one silence. Tracked separately below.
    no_sites: list[str] = []
    for name in names[:_GATE_DEFINITION_CAP]:
        ## PROJECTED, NOT PASSED THROUGH. A full `MacroDef` carries its own `referenced_by`,
        ## `gated_by` and expansion per site, and three of those nested inside a block that exists
        ## to save one call would put the payload back in the budget the trimmer fights over. The
        ## caller needs WHERE, and the expansion only because a gate's value is usually empty and
        ## saying so is the answer.
        sites = [
            {"file": site.file, "line": site.line, "expansion": site.expansion}
            for site in q.macro_definitions(db, name)
        ]
        if sites:
            out[name] = sites
        else:
            no_sites.append(name)
    return out, _gate_definition_gaps(no_sites, names[_GATE_DEFINITION_CAP:])

Activity · 12 steps
lines 500–500rows = payload.get("gated_by") or []lines 501–501subject = payload.get("name") or payload.get("subject")lines 502–508names = sorted( { str(row["symbol"]) for row in rows if isinstance(row, dict) and row.get("symbol") and row["symbol"] != subject } )lines 509–509out: dict[str, Any] = {}lines 514–514no_sites: list[str] = []lines 515–515◇ for name in names[:_GATE_DEFINITION_CAP]lines 521–524sites = [ {"file": site.file, "line": site.line, "expansion": site.expansion} for site in q.macro_definitions(db, name) ]lines 525–525◇ if siteslines 526–526out[name] = siteslines 527–527elselines 528–528no_sites.append(name)lines 529–529return out, _gate_definition_gaps(no_sites, names[_GATE_DEFINITION_CAP:])

Flows

_grouped

list[dict[str, Any]] clew.query.payload._grouped(list[Any] rows, dict[str, Any] defaults)

One neighbour list grouped by file, defaults removed from its rows.

clew/query/payload.py:860

Source · 13 lines
def _grouped(rows: list[Any], defaults: dict[str, Any]) -> list[dict[str, Any]]:
    """@brief Group and strip. @return Groups."""
    groups: dict[str | None, list[dict[str, Any]]] = {}
    for row in rows:
        if not isinstance(row, dict):
            continue
        slim = {k: v for k, v in row.items() if k != "file" and defaults.get(k, _MISSING) != v}
        groups.setdefault(row.get("file"), []).append(slim)
    ## A ROW WITH NO FILE (an endpoint whose file did not resolve) goes in a group with no `file`
    ## key — absent, as on the flat row — rather than under an invented empty path.
    return [({"file": f} if f is not None else {}) | {"rows": rs} for f, rs in groups.items()]

Activity · 7 steps
lines 862–862groups: dict[str | None, list[dict[str, Any]]] = {}lines 863–863◇ for row in rowslines 864–864◇ if not isinstance(row, dict)lines 865–865continuelines 866–866slim = {k: v for k, v in row.items() if k != "file" and defaults.get(k, _MISSING) != v}lines 867–867groups.setdefault(row.get("file"), []).append(slim)lines 870–870return [({"file": f} if f is not None else {}) | {"rows": rs} for f, rs in groups.items()]

Flows

_hoist_build_wide

None clew.query.payload._hoist_build_wide(list[dict[str, Any]] entries, dict[str, Any] out)

Move build-wide fields out of every batch entry and onto the envelope, once.

clew/query/payload.py:393

Source · 24 lines
def _hoist_build_wide(entries: list[dict[str, Any]], out: dict[str, Any]) -> None:
    """FIRES ONLY ON UNANIMITY, which is the guard that makes this safe rather than merely
    smaller. If two entries disagree about a key, that key is not build-wide in this reply — it is
    subject data wearing a build-wide name — and hoisting would delete a real difference. So
    disagreement leaves every entry untouched.

    A key present on SOME entries and absent from others also fails the check: absence is
    meaningful here (`prune_absent_keys` removes what does not apply to a subject kind), and
    hoisting would assert the value for subjects that never carried it.

    @brief Deduplicate build-wide fields into the envelope.
    @version 1
    """
    for key in _BUILD_WIDE_KEYS:
        values = [entry[key] for entry in entries if key in entry]
        if len(values) < 2 or len(values) != len(entries):
            continue
        if any(value != values[0] for value in values[1:]):
            continue
        out[key] = values[0]
        for entry in entries:
            entry.pop(key, None)

Activity · 9 steps
lines 406–406◇ for key in _BUILD_WIDE_KEYSlines 407–407values = [entry[key] for entry in entries if key in entry]lines 408–408◇ if len(values) < 2 or len(values) != len(entries)lines 409–409continuelines 410–410◇ if any(value != values[0] for value in values[1:])lines 411–411continuelines 412–412out[key] = values[0]lines 413–413◇ for entry in entrieslines 414–414entry.pop(key, None)

Flows

_kind_limitation_clause

str clew.query.payload._kind_limitation_clause(tuple[str,...] unresolved)

The clause that turns a bare miss into a KIND limitation when it is one.

clew/query/payload.py:579

Source · 27 lines
def _kind_limitation_clause(unresolved: tuple[str, ...]) -> str:
    """gh#6. `SUBJECT_KINDS` has no `enumeration`, while `SEARCHED_MEMBERDEF_KINDS` does — so
    `search` finds a C enum, its enumerators and a C++ `enum class`, and `dossier` calls the same
    names "a definitive negative from the database". A reporter asked about four enum symbols they
    knew existed and got that on all four.

    THE WORDING WAS THE DAMAGE. A gap described as a gap costs one follow-up call; a gap worded as
    a definitive negative reads as "this tool is wrong about my repo" — and on a codebase whose
    authoritative definitions are C enums, wrong about the thing that matters most.

    ONE SENTENCE, AND IT ROUTES: it names the kind, says this surface does not describe it yet, and
    names the tool that can. Route, do not disclaim.

    @brief Say the name is indexed under a kind this surface cannot describe.
    @return The clause, or "" when nothing was found under any kind.
    @version 1
    """
    if not unresolved:
        return ""
    kinds = ", ".join(f"`{k}`" for k in unresolved)
    return (
        f" HOWEVER this name IS in the index, as {kinds} — a kind `dossier` does not describe "
        f"yet. So this is a COVERAGE LIMITATION of this tool, not a statement that the symbol "
        f"does not exist. Use `search` to see it."
    )

Activity · 4 steps
lines 596–596◇ if not unresolvedlines 597–597return ""lines 598–598kinds = ", ".join(f"`{k}`" for k in unresolved)lines 599–603return ( f" HOWEVER this name IS in the index, as {kinds} — a kind `dossier` does not describe " f"yet. So this is a COVERAGE LIMITATION of this tool, not a statement that the symbol " f"does not exist. Use `search` to see it." )

Flows

_refusal_note

str clew.query.payload._refusal_note(Any sites)

Note for an empty caller list the build recorded refusals against.

clew/query/payload.py:148

Source · 22 lines
def _refusal_note(sites: Any) -> str:
    """None IS NOT ZERO. An index built before the measurement existed reports None, and reading
    that as "nothing was refused" would assert a clean bill of health from a detector that could
    not look — so None returns "" and leaves the older `also` rule to answer, exactly as it did
    before this existed.

    @brief Qualify an empty caller list against the recorded refusal count.
    @return The note, or "".
    @version 1
    """
    if not isinstance(sites, int) or isinstance(sites, bool) or sites <= 0:
        return ""
    return (
        f"`callers` is EMPTY but this is NOT a measured negative: {sites} call site(s) in this "
        f"index named a function this one could be and did not resolve to a specific one, so "
        f"callers may exist that no edge records. A member call reached through a pointer or "
        f"reference receiver resolves only when the receiver's declared type pins the class. "
        f"Read the body at the reported line range, or `search` the name, before concluding "
        f"nothing calls this."
    )

Activity · 3 steps
lines 158–158◇ if not isinstance(sites, int) or isinstance(sites, bool) or sites <= 0lines 159–159return ""lines 160–167return ( f"`callers` is EMPTY but this is NOT a measured negative: {sites} call site(s) in this " f"index named a function this one could be and did not resolve to a specific one, so " f"callers may exist that no edge records. A member call reached through a pointer or " f"reference receiver resolves only when the receiver's declared type pins the class. " f"Read the body at the reported line range, or `search` the name, before concluding " f"nothing calls this." )

Flows

_uncarried_sentences

list[str] | None clew.query.payload._uncarried_sentences(str text, list[str] lines)

The sentences of a text that a body does not carry, or None when it carries none.

clew/query/payload.py:926

Source · 13 lines
def _uncarried_sentences(text: str, lines: list[str]) -> list[str] | None:
    """ORDERED CONTAINMENT, NOT OVERLAP: a sentence is carried only when its words occur, as one
    contiguous run, in the body's words — the words of a sentence that is not in the body can all
    occur somewhere in it, and that was how text the agent never saw was dropped. None when nothing
    is carried, so a detail that only shares vocabulary with its body is left exactly as it was.

    @brief Sentence-wise containment.
    @return Uncarried sentences or None.
    """
    haystack = " " + " ".join(_WORD.findall(" ".join(lines).lower())) + " "
    parts = [p.strip() for p in _SENTENCE.split(text) if _WORD.findall(p.lower())]
    rest = [p for p in parts if " " + " ".join(_WORD.findall(p.lower())) + " " not in haystack]
    return None if len(rest) == len(parts) else rest

1 more lines, not shown

Activity · 4 steps
lines 935–935haystack = " " + " ".join(_WORD.findall(" ".join(lines).lower())) + " "lines 936–936parts = [p.strip() for p in _SENTENCE.split(text) if _WORD.findall(p.lower())]lines 937–937rest = [p for p in parts if " " + " ".join(_WORD.findall(p.lower())) + " " not in haystack]lines 938–938return None if len(rest) == len(parts) else rest

Flows

compact_docs

dict[str, Any] clew.query.payload.compact_docs(dict[str, Any] payload)

v2 (1.4.0 grid): never when the served body is truncated, and only the sentences that occur in order in the served body are dropped — a word-overlap test dropped text the agent never saw.

clew/query/payload.py:893

Source · 27 lines
def compact_docs(payload: dict[str, Any]) -> dict[str, Any]:
    """1.3.9, COMPACT SHAPE ONLY (`detail` is a semver-covered key). A Python docstring sits inside
    the body excerpt and doxygen serves it again as `detail`. Each sentence of `detail` that
    occurs, in order, in the SERVED body lines (never a truncated body) is dropped from it, and
    `detail_in_body: true` says so; sentences the body does not show — the `## @param` text above
    a `def` — are still served. The marker keeps a short or absent `detail` from reading as
    "undocumented". `brief` stays: it is short, and it is what a reader scans first.

    @brief Serve a docstring once.
    @return The payload.
    @version 2
    """
    detail = payload.get("detail")
    body = payload.get("body")
    lines = body.get("lines") if isinstance(body, dict) else None
    if not isinstance(detail, str) or not detail or not lines or body.get("truncated"):
        return payload
    rest = _uncarried_sentences(detail, lines)
    if rest is not None:
        if rest:
            payload["detail"] = ". ".join(rest)
        else:
            payload.pop("detail")
        payload["detail_in_body"] = True
    return payload

Activity · 13 steps
lines 905–905detail = payload.get("detail")lines 906–906body = payload.get("body")lines 907–907lines = body.get("lines") if isinstance(body, dict) else Nonelines 908–908◇ if not isinstance(detail, str) or not detail or not lines or body.get("truncated")lines 909–909return payloadlines 910–910rest = _uncarried_sentences(detail, lines)lines 911–911◇ if rest is not Nonelines 912–912◇ if restlines 913–913payload["detail"] = ". ".join(rest)lines 914–914elselines 915–915payload.pop("detail")lines 916–916payload["detail_in_body"] = Truelines 917–917return payload

Requirements

REQ-DDB-QUERY-014

Flows

compact_neighbours

dict[str, Any] clew.query.payload.compact_neighbours(dict[str, Any] payload)

Group neighbour rows by file and state each reply's common field values once.

clew/query/payload.py:808

Source · 27 lines
def compact_neighbours(payload: dict[str, Any]) -> dict[str, Any]:
    """1.3.7 parts B and C, OPT-IN (`CLEW_WIRE=compact`, set by the clew plugin; the flat shape is
    semver-covered and stays the default). `callers`/`callees` become
    `[{"file": f, "rows": [...]}]` in first-seen file order, and each of `source`, `confidence` and
    `edge_class` whose most common value repeats is stated once in `edge_defaults` and left off the
    rows that carry it.

    LOSSLESS BY CONSTRUCTION: a field is defaulted only when EVERY neighbour row carries it, so
    re-applying the default can never invent a value a row did not have; a row whose value
    differs keeps it. `tests/test_compact_wire.py` expands the result and compares.

    @brief Compact a payload's neighbour rows.
    @return The payload.
    @version 1
    """
    rows = [r for key in _NEIGHBOUR_LISTS for r in payload.get(key) or [] if isinstance(r, dict)]
    if not rows:
        return payload
    defaults = _edge_defaults(rows)
    for key in _NEIGHBOUR_LISTS:
        if isinstance(payload.get(key), list):
            payload[key] = _grouped(payload[key], defaults)
    if defaults:
        payload["edge_defaults"] = defaults
    return payload

Activity · 10 steps
lines 823–823rows = [r for key in _NEIGHBOUR_LISTS for r in payload.get(key) or [] if isinstance(r, dict)]lines 824–824◇ if not rowslines 825–825return payloadlines 826–826defaults = _edge_defaults(rows)lines 827–827◇ for key in _NEIGHBOUR_LISTSlines 828–828◇ if isinstance(payload.get(key), list)lines 829–829payload[key] = _grouped(payload[key], defaults)lines 830–830◇ if defaultslines 831–831payload["edge_defaults"] = defaultslines 832–832return payload

Requirements

REQ-DDB-QUERY-014

Flows

disclose_overflow

None clew.query.payload.disclose_overflow(dict[str, Any] out, list[str] overflow)

Name the subjects an over-cap batch did not answer.

clew/query/payload.py:685

Source · 15 lines
def disclose_overflow(out: dict[str, Any], overflow: list[str]) -> None:
    """ABSENT WHEN NOTHING WAS LEFT OUT, so an ordinary batch carries nothing.

    @brief Add `not_answered` to a batch envelope.
    @return None.
    """
    if overflow:
        out["not_answered"] = overflow
        out["not_answered_means"] = (
            f"dossier answers at most {q.MAX_BATCH_SYMBOLS} subjects per call; these were NOT "
            "looked up — re-ask for them in another call. Nothing is implied about whether they "
            "are indexed."
        )

Activity · 3 steps
lines 691–691◇ if overflowlines 692–692out["not_answered"] = overflowlines 693–697out["not_answered_means"] = ( f"dossier answers at most {q.MAX_BATCH_SYMBOLS} subjects per call; these were NOT " "looked up — re-ask for them in another call. Nothing is implied about whether they " "are indexed." )

Flows