subject.py

clew/query/subject.py

Subject-agnostic lookup: point the composite dossier at ANYTHING the index holds.

_chain_for

_chain_for(
    db: DbSource,
    kind: str,
    name: str,
    depth: int,
    direction: str,
    max_neighbors: int,
    qualified: str | None = None,
)

clew/query/subject.py:913

Source · 36 lines
def _chain_for(
    db: DbSource,
    kind: str,
    name: str,
    depth: int,
    direction: str,
    max_neighbors: int,
    qualified: str | None = None,
) -> Chain | None:
    """REUSES `chain_trace` RATHER THAN WALKING AGAIN. Its fan-out taper, its cycle
    handling and its non-fuzzy-edges-only rule are the bounds that keep a depth-3 walk
    from returning a hub's whole component, and a second traversal here would be a
    second set of bounds to get wrong.

    ONLY A FUNCTION HAS A SEED. `chain_trace` starts from a function name and follows
    call and shared-key edges; a lock, a requirement and a config symbol are not
    endpoints of those edges, so there is nothing to walk from. Returning None is the
    honest answer and the MCP layer discloses it — a depth argument that silently did
    nothing would be worse than one that refused.

    @brief Traverse from the subject when it has a traversal seed.
    @return Chain or None.
    @version 1
    """
    if depth <= 1 or kind != "function":
        return None
    ## THE SELECTOR REACHES THE WALK (1.4.0, W1): with it the chain follows this identity's
    ## edges, not its namesakes'.
    return chain_trace(
        db,
        name,
        direction=direction,
        max_depth=depth,
        max_neighbors=max_neighbors,
        qualified=qualified,
    )
Activity · 3 steps
lines 937–937◇ if depth <= 1 or kind != "function"lines 938–938return Nonelines 941–948return chain_trace( db, name, direction=direction, max_depth=depth, max_neighbors=max_neighbors, qualified=qualified, )

Flows

_chosen_kind

_chosen_kind(kinds: tuple[str, ...], wanted: str | None)

clew/query/subject.py:763

Show on the map →

Called by dossier, test_enum_on_a_name_that_is_neither_still_refuses, test_enum_still_prefers_the_compound_when_the_name_is_one

Calls none

Source · 30 lines
def _chosen_kind(kinds: tuple[str, ...], wanted: str | None) -> str | None:
    """AN EXPLICIT KIND IS A FILTER, NOT AN OVERRIDE. Asking for `kind='variable'` on a
    name that is only a function returns nothing, rather than the function relabelled —
    a caller that disambiguated deliberately must not be handed the thing it ruled out.

    A SEARCH ROW'S `kind` IS ACCEPTED HERE (gh#404), because `search`'s description promises it
    is: "READ `kind` ON EVERY ROW: it is what you pass back". `_KIND_ALIASES` makes that promise
    true for the five kinds that name a subject, and `_KIND_NO_SUBJECT` makes the refusal useful
    for the three that do not. The alias is applied BEFORE the filter, so aliasing cannot smuggle
    in a kind the name does not actually resolve to.

    @brief Select which resolved kind to build.
    @return The kind, or None.
    @version 3
    """
    if wanted is None:
        return kinds[0] if kinds else None
    ## THE FIRST CANDIDATE THE NAME IS, else the first candidate — which then fails the
    ## membership test below and returns None, preserving "a kind is a filter, not an override".
    candidates = _KIND_ALIASES.get(wanted, (wanted,))
    wanted = next((c for c in candidates if c in kinds), candidates[0])
    if wanted in _KIND_NO_SUBJECT:
        raise ValueError(
            f"Subject kind {wanted!r} names no dossier subject: {_KIND_NO_SUBJECT[wanted]}."
        )
    if wanted not in SUBJECT_KINDS:
        raise ValueError(
            f"Unknown subject kind {wanted!r}. Known kinds: {', '.join(SUBJECT_KINDS)}."
        )
    return wanted if wanted in kinds else None
Activity · 9 steps
lines 778–778◇ if wanted is Nonelines 779–779return kinds[0] if kinds else Nonelines 782–782candidates = _KIND_ALIASES.get(wanted, (wanted,))lines 783–783wanted = next((c for c in candidates if c in kinds), candidates[0])lines 784–784◇ if wanted in _KIND_NO_SUBJECTlines 785–787raise ValueError( f"Subject kind {wanted!r} names no dossier subject: {_KIND_NO_SUBJECT[wanted]}." )lines 788–788◇ if wanted not in SUBJECT_KINDSlines 789–791raise ValueError( f"Unknown subject kind {wanted!r}. Known kinds: {', '.join(SUBJECT_KINDS)}." )lines 792–792return wanted if wanted in kinds else None

Flows

_class_side_is_only_enum_mirrors

_class_side_is_only_enum_mirrors(conn: sqlite3.Connection, name: str)

clew/query/subject.py:827

Source · 21 lines
def _class_side_is_only_enum_mirrors(conn: sqlite3.Connection, name: str) -> bool:
    """MATCHES WHAT `_is_compound` MATCHED, exact-or-qualified-tail, so the set tested here
    is the set that made `class` resolve in the first place. A different match rule would
    let the tie-break fire on compounds the classifier never saw.

    EVERY match, not any: one hand-written class sharing the name is enough to keep the
    class reading, because then the name really does denote a class somebody wrote.

    @brief Test the whole class-side candidate set.
    @return True when the class reading is nothing but enum mirrors.
    @version 1
    """
    if not (table_exists(conn, "compounddef") and table_exists(conn, "compoundref")):
        return False
    placeholders = ",".join("?" * len(CLASS_KINDS))
    rows = conn.execute(
        f"SELECT rowid FROM compounddef WHERE kind IN ({placeholders}) "  # noqa: S608
        "AND (name = ? OR name LIKE '%::' || ?)",
        (*CLASS_KINDS, name, name),
    ).fetchall()
    return bool(rows) and all(_derives_from_py_enum(conn, rowid) for (rowid,) in rows)
Activity · 5 steps
lines 839–839◇ if not (table_exists(conn, "compounddef") and table_exists(conn, "compoundref"))lines 840–840return Falselines 841–841placeholders = ",".join("?" * len(CLASS_KINDS))lines 842–846rows = conn.execute( f"SELECT rowid FROM compounddef WHERE kind IN ({placeholders}) " # noqa: S608 "AND (name = ? OR name LIKE '%::' || ?)", (*CLASS_KINDS, name, name), ).fetchall()lines 847–847return bool(rows) and all(_derives_from_py_enum(conn, rowid) for (rowid,) in rows)

Flows

_derives_from_py_enum

_derives_from_py_enum(conn: sqlite3.Connection, rowid: int)

clew/query/subject.py:807

Source · 12 lines
def _derives_from_py_enum(conn: sqlite3.Connection, rowid: int) -> bool:
    """@brief Read one compound's bases and test them against `_PY_ENUM_BASES`.
    @return True when it subclasses a Python enum.
    @version 1
    """
    rows = conn.execute(
        "SELECT b.name FROM compoundref r JOIN compounddef b ON b.rowid = r.base_rowid "
        "WHERE r.derived_rowid = ?",
        (rowid,),
    ).fetchall()
    bases = [str(name).split("::")[-1].split(".")[-1] for (name,) in rows if name]
    return bool(bases) and all(base in _PY_ENUM_BASES for base in bases)
Activity · 3 steps
lines 812–816rows = conn.execute( "SELECT b.name FROM compoundref r JOIN compounddef b ON b.rowid = r.base_rowid " "WHERE r.derived_rowid = ?", (rowid,), ).fetchall()lines 817–817bases = [str(name).split("::")[-1].split(".")[-1] for (name,) in rows if name]lines 818–818return bool(bases) and all(base in _PY_ENUM_BASES for base in bases)

Flows

_qualified_reread

_qualified_reread(
    db: DbSource, subject: str, kinds: tuple[str, ...], kind: str | None
)

clew/query/subject.py:1054

Source · 29 lines
def _qualified_reread(
    db: DbSource, subject: str, kinds: tuple[str, ...], kind: str | None
) -> tuple[str, str | None, tuple[str, ...]]:
    """TWO CASES, ONE TRANSFORMATION (C7, then T6).

    NOTHING RESOLVED (C7): the qualified spelling is re-read as bare tail plus selector.

    SOMETHING RESOLVED, BUT NOT A FUNCTION (T6, entropic F3): a `threads` row is NAMED by the
    qualified entry (`HealthMonitor::monitor_loop`), so that string resolved as a thread and the
    re-read never ran. The dossier was a 371-byte stub with no body and no `also`, while the
    function the thread runs, whose body and callers a reader came for, sat one re-read away.
    When the re-read finds a function, the function is the subject and the kinds the spelling
    matched as given are kept, after it, so `also` names them.

    NOT WHEN THE CALLER ASKED FOR ANOTHER KIND: `kind='thread'` with the qualified spelling must
    still reach the thread, which the original subject, not the tail, names.

    @brief Apply the qualified re-read.
    @return The triple.
    """
    settled = bool(kinds) and ("function" in kinds or kind not in (None, "function"))
    split = None if settled else _split_qualified(db, subject)
    reread = None
    if split is not None:
        tail_kinds = _rank_enum_over_mirror(db, split[0], resolve_subject(db, split[0]))
        if not kinds or "function" in tail_kinds:
            merged = tail_kinds + tuple(k for k in kinds if k not in tail_kinds)
            reread = (split[0], split[1], merged)
    return reread or (subject, None, kinds)
Activity · 9 steps
lines 1074–1074settled = bool(kinds) and ("function" in kinds or kind not in (None, "function"))lines 1075–1075split = None if settled else _split_qualified(db, subject)lines 1076–1076reread = Nonelines 1077–1077◇ if split is not Nonelines 1078–1078tail_kinds = _rank_enum_over_mirror(db, split[0], resolve_subject(db, split[0]))lines 1079–1079◇ if not kinds or "function" in tail_kindslines 1080–1080merged = tail_kinds + tuple(k for k in kinds if k not in tail_kinds)lines 1081–1081reread = (split[0], split[1], merged)lines 1082–1082return reread or (subject, None, kinds)

Flows

_qualified_suffix_matches

_qualified_suffix_matches(conn: sqlite3.Connection, tail: str, subject: str)

clew/query/subject.py:1186

Source · 44 lines
def _qualified_suffix_matches(conn: sqlite3.Connection, tail: str, subject: str) -> list[str]:
    """A SUFFIX MATCH, BECAUSE TWO QUALIFIED SPELLINGS ARE IN CIRCULATION AND ONLY ONE WAS
    ACCEPTED. Found by replaying C7's first version against the live entropic index, where it
    resolved 3 of the 12 measured misses:

        qualified_name_of  ->  entropic::HealthMonitor::monitor_loop   (what the index holds)
        threads[].name     ->  HealthMonitor::monitor_loop             (what clew SERVES)

    Nine of those twelve omitted the namespace. That is the spelling the thread corpus hands a
    reader and the spelling a reader writes unprompted, so accepting only the fully-qualified form
    fixes the minority of a defect whose majority is the form clew itself prints.

    ALIGNED TO A SEPARATOR, never a bare string suffix. `Monitor::monitor_loop` is a plain-string
    suffix of `entropic::HealthMonitor::monitor_loop` because `HealthMonitor` ends in `Monitor`,
    and resolving it would describe `HealthMonitor` under a class name this index does not hold —
    the confidently-wrong-symbol failure in its most literal form.

    DERIVED FROM `qualified_name_of`, the same function the `qualified` selector compares against,
    so this can only ever name a form the selector then accepts. Narrowed in SQL by the bare tail
    first: that column is indexed and the candidate set is the handful of rows sharing one member
    name, not the whole table.

    @brief Match a partial qualification against indexed identities.
    @return The qualified names it identifies.
    @version 1
    """
    if not table_exists(conn, "memberdef"):
        return []
    rows = conn.execute(
        "SELECT DISTINCT name, COALESCE(definition, name) FROM memberdef WHERE name = ?", (tail,)
    ).fetchall()
    out: list[str] = []
    for row_name, definition in rows:
        full = qualified_name_of(str(row_name), str(definition))
        if full == subject or not full.endswith(subject):
            if full == subject and full not in out:
                out.append(full)
            continue
        ## The character before the match must be the end of a separator, so the boundary falls
        ## between identifiers rather than inside one.
        boundary = full[: len(full) - len(subject)]
        if boundary.endswith(("::", ".")) and full not in out:
            out.append(full)
    return out
Activity · 14 steps
lines 1212–1212◇ if not table_exists(conn, "memberdef")lines 1213–1213return []lines 1214–1216rows = conn.execute( "SELECT DISTINCT name, COALESCE(definition, name) FROM memberdef WHERE name = ?", (tail,) ).fetchall()lines 1217–1217out: list[str] = []lines 1218–1218◇ for row_name, definition in rowslines 1219–1219full = qualified_name_of(str(row_name), str(definition))lines 1220–1220◇ if full == subject or not full.endswith(subject)lines 1221–1221◇ if full == subject and full not in outlines 1222–1222out.append(full)lines 1223–1223continuelines 1226–1226boundary = full[: len(full) - len(subject)]lines 1227–1227◇ if boundary.endswith(("::", ".")) and full not in outlines 1228–1228out.append(full)lines 1229–1229return out

Flows

_rank_enum_over_mirror

_rank_enum_over_mirror(db: DbSource, name: str, kinds: tuple[str, ...])

clew/query/subject.py:857

Source · 42 lines
def _rank_enum_over_mirror(db: DbSource, name: str, kinds: tuple[str, ...]) -> tuple[str, ...]:
    """gh#29. `dossier("AgentState")` returned the generated ctypes `IntEnum` in
    `python/src/entropic/_bindings.py` and not the C++ `enum class` in
    `include/entropic/core/engine_types.h` — the derivative of the two, on a codebase whose
    architecture rule makes the C one authoritative.

    NOT THE RULE THAT WAS ASKED FOR, and the measurement is why. The request was to
    deprioritise the generated FILE, the way `SYNTHETIC_PATH` deprioritises `std::`
    compounds. Over the three indexed targets — 2,174 class-kind compounds, 308 enum names —
    the collision occurs TWICE and only one is a mirror; `_bindings.py` holds 15 compounds,
    so ranking by that file would re-rank 15 resolutions to correct 1, and the marker that
    identifies it also matches a hand-written `__init__.py` in the same package. That is the
    `macro_collision` objection exactly: the available structural rule fires on legitimate
    cases too.

    SO THE TRIGGER IS INHERITANCE, WHICH THE INDEX ALREADY HOLDS. `compoundref` says the
    mirror subclasses `enum::IntEnum`; all 8 of entropic's mirrors do and nothing else in any
    of the three indexes subclasses an enum base. It is a statement about the symbol, not a
    guess about its file, and it fires on exactly the one name measured.

    IT MUST STAY CONDITIONAL ON THE COLLISION. A plain `class Color(Enum)` produces no
    `memberdef kind='enumeration'` row, so the enumeration probe never fires for it — and
    declining its class reading outright would resolve `dossier("Color")` to NOTHING on
    every Python-only repository. A name only loses the class reading when a real enumeration
    reading is there to take it.

    ONLY `class` IS OUTRANKED. `enumeration` moves directly above it rather than to the
    front, so a name that is also a function or a lock keeps that reading first — this
    settles one ambiguity and must not silently settle the others.

    @brief Rank a real enumeration above a Python class that merely mirrors one.
    @return The reordered kinds.
    @version 1
    """
    if not ("class" in kinds and "enumeration" in kinds):
        return kinds
    with connect(db) as conn:
        if not _class_side_is_only_enum_mirrors(conn, name):
            return kinds
    order = [k for k in kinds if k != "enumeration"]
    at = order.index("class")
    return tuple(order[:at] + ["enumeration"] + order[at:])
Activity · 8 steps
lines 891–891◇ if not ("class" in kinds and "enumeration" in kinds)lines 892–892return kindslines 893–893with connect(db) as connlines 894–894◇ if not _class_side_is_only_enum_mirrors(conn, name)lines 895–895return kindslines 896–896order = [k for k in kinds if k != "enumeration"]lines 897–897at = order.index("class")lines 898–898return tuple(order[:at] + ["enumeration"] + order[at:])

Flows

_selector_from_signature

_selector_from_signature(subject: str, selector: str)

clew/query/subject.py:1092

Source · 33 lines
def _selector_from_signature(subject: str, selector: str) -> str:
    """EVERY `qualified` VALUE THE 1.1.0 AGENTS PASSED WAS A SIGNATURE — twelve distinct pairs
    across the frozen grid, all carrying a return type, every one resolving to nothing. They were
    obeying the served text, which then read *"The exact signature from a previous reply's
    `candidates`."* 655952c corrected that sentence; this accepts the string the surface spent a
    release advertising, because the wasted calls are already measured and the correction cannot
    reach a model that learned the old wording.

    THE ARGUMENT LIST IS STRIPPED FIRST, and that order is the whole implementation.
    `qualified_name_of` already scans tokens from the right for one whose tail is `name` at a
    `::` or `.` boundary — but an argument list contains spaces and colons, so it returns the bare
    name when one is present. Cutting at the first `(` leaves `<return type> <qualified name>`,
    which is the shape that function was written for. Trailing `const` / `override` / `noexcept`
    fall away with the parenthesis.

    REUSING THAT FUNCTION RATHER THAN PARSING A SIGNATURE HERE is deliberate: it is the rule the
    selector compares against, so a value recovered by it can only ever be a value the selector
    then accepts. Deriving advice from one rule and acceptance from another is how the served
    text came to advertise `signature` in the first place.

    EMPTY WHEN NOTHING IS RECOVERED, including when the result is just the bare subject — a free
    function has no qualification, so the honest outcome is to drop the selector rather than to
    pass the subject back as its own identity.

    @brief Extract a usable selector from a signature.
    @return The qualified name, or "".
    @version 1
    """
    head = selector.split("(", 1)[0].strip()
    if not head:
        return ""
    recovered = qualified_name_of(subject, head)
    return recovered if recovered and recovered != subject else ""
Activity · 5 steps
lines 1120–1120head = selector.split("(", 1)[0].strip()lines 1121–1121◇ if not headlines 1122–1122return ""lines 1123–1123recovered = qualified_name_of(subject, head)lines 1124–1124return recovered if recovered and recovered != subject else ""

Flows

_split_qualified

_split_qualified(db: DbSource, subject: str)

clew/query/subject.py:1134

Source · 43 lines
def _split_qualified(db: DbSource, subject: str) -> tuple[str, str] | None:
    """clew SERVED THE SPELLING AND THEN REFUSED IT (C7).

    MEASURED by replaying all 48 frozen `index_only` transcripts from the 1.1.0 grid: of 157
    `dossier` subjects that came back `found: false`, **147 — 93.6% — were strings clew itself had
    put in front of the model in an earlier reply.** 75 were file paths (C1), 33 were qualified
    C++ names (this), and 49 were bare names with no row at all.

    The 33 sit in entropic Q1, Q3 and Q4 — three of the six worst clusters. The source is exact:
    `search(corpus="threads")` serves `{"name": "HealthMonitor::monitor_loop", "entry":
    "monitor_loop"}` and the tool's prose says a row's name is what goes back to `dossier`. The
    model obeyed, three cells of three, and spent two of six calls on refusals. Making the row's
    `name` bare is not available — `UNIQUE(name, entry, kind)` is what stops four distinct threads
    collapsing into one row — so this side gives.

    THE REWRITE IS NOT NEW JUDGEMENT. `recovery._hint_from` already tells the caller, in words, to
    pass `subject="<tail>", qualified="<whole>"`. This repo therefore already holds the
    transformation correct and was charging a round trip to have the model type it.

    LAST RESORT, AND THAT IS THE WHOLE SAFETY ARGUMENT. It runs only after `resolve_subject` has
    returned nothing for the string as given, so no subject that resolves today can change
    meaning — a file path still resolves as a file (C1), and a dotted name the index holds whole
    still wins. It also cannot invent a hit: `identity_rowids` must select at least one row for
    the ORIGINAL spelling as the qualified selector, so `Nonexistent::monitor_loop` stays a miss
    even though its tail is indexed.

    @brief Resolve a qualified spelling to (bare, selector).
    @return The pair, or None.
    @version 1
    """
    tail = bare_tail(subject)
    if tail == subject or not tail:
        return None
    with connect(db) as conn:
        ## THE EXACT SPELLING FIRST, which is the cheap case and the one `candidates[i].qualified`
        ## produces: the caller copied the selector verbatim and merely put it in the wrong slot.
        if identity_rowids(conn, tail, subject):
            return tail, subject
        matches = _qualified_suffix_matches(conn, tail, subject)
    ## EXACTLY ONE, OR NOTHING. A partial qualification matching two identities names neither, and
    ## answering it would be the arbitrary pick reported as the answer that `also` exists to
    ## prevent. The recovery hint remains the right reply for an ambiguous one.
    return (tail, matches[0]) if len(matches) == 1 else None
Activity · 8 steps
lines 1164–1164tail = bare_tail(subject)lines 1165–1165◇ if tail == subject or not taillines 1166–1166return Nonelines 1167–1167with connect(db) as connlines 1170–1170◇ if identity_rowids(conn, tail, subject)lines 1171–1171return tail, subjectlines 1172–1172matches = _qualified_suffix_matches(conn, tail, subject)lines 1176–1176return (tail, matches[0]) if len(matches) == 1 else None

Flows

dossier

dossier(
    db: DbSource,
    subject: str,
    kind: str | None = None,
    qualified: str | None = None,
    repo_root: Path | str | None = None,
    max_body_lines: int = DEFAULT_BODY_LINES,
    depth: int = 1,
    direction: str = "forward",
    max_neighbors: int = 8,
)

clew/query/subject.py:973

Show on the map →

Called by one, subject_payload

Tested by

46 teststest_a_bare_name_prefers_the_cpp_enum_over_its_python_mirror, test_a_callee_row_publishes_the_short_form_and_the_selector_follows_it, test_a_caller_row_names_its_file, test_a_collided_callee_row_carries_its_qualified_identity, test_a_colliding_class_that_is_not_an_enum_keeps_the_class_reading, test_a_documented_file_path_is_a_subject_and_carries_its_documentation, test_a_file_path_asked_for_as_a_function_resolves_to_nothing, test_a_file_path_is_not_mistaken_for_a_qualified_name, test_a_file_row_in_compounddef_does_not_classify_as_a_class, test_a_file_subject_lists_the_symbols_it_defines, test_a_free_function_publishes_an_empty_identity, test_a_free_functions_signature_resolves
34 moretest_a_known_file_with_no_harvested_content_is_distinguishable_from_an_unknown_one, test_a_partially_qualified_spelling_resolves, test_a_python_enum_with_no_cpp_namesake_is_still_a_class, test_a_qualified_spelling_for_an_absent_owner_still_misses, test_a_qualified_subject_resolves_to_that_identity, test_a_selector_naming_nothing_is_disclosed_not_silently_ignored, test_a_selector_naming_one_declaration_narrows_the_sites, test_a_signature_for_an_absent_owner_is_still_refused, test_a_signature_passed_as_the_selector_still_selects, test_an_empty_callers_list_reports_what_was_refused, test_an_endpoint_with_no_resolvable_file_reports_empty, test_an_enum_subject_has_no_caller_fields_at_all, test_an_enum_type_resolves_to_its_own_subject, test_an_explicit_selector_is_not_overridden_by_the_split, test_an_index_without_the_measurement_says_it_cannot_tell, test_an_undocumented_file_resolves_and_reports_no_documentation, test_asking_for_a_VALUE_answers_with_the_enum_that_declares_it, test_asking_for_the_enum_itself_reports_no_matched_value, test_asking_for_the_enumeration_kind_filters_rather_than_relabels, test_breadth_is_countable_without_a_second_call, test_each_owner_is_reachable_by_its_own_spelling, test_following_the_row_reaches_that_endpoint_and_not_its_namesake, test_kind_file_from_a_search_row_round_trips, test_the_bare_name_is_unchanged, test_the_body_carries_the_enumerators_verbatim, test_the_dossier_depth_walk_honours_qualified, test_the_enum_lists_the_values_the_index_holds, test_the_exported_dossier_answers_about_a_non_function_subject, test_the_mirror_stays_disclosed_and_reachable, test_the_natural_word_enum_reaches_a_C_enum, test_the_published_identity_is_accepted_by_the_selector, test_the_suffix_must_align_to_a_separator, test_the_synthetic_stl_path_is_not_a_file_subject, test_without_a_selector_every_site_is_reported

Calls _chain_for, _chosen_kind, _qualified_reread, _rank_enum_over_mirror, _selector_from_signature, connect, identity_rowids, resolve_subject

Source · 70 lines
def dossier(
    db: DbSource,
    subject: str,
    kind: str | None = None,
    qualified: str | None = None,
    repo_root: Path | str | None = None,
    max_body_lines: int = DEFAULT_BODY_LINES,
    depth: int = 1,
    direction: str = "forward",
    max_neighbors: int = 8,
) -> SubjectDossier | None:
    """ONE SUBJECT, ONE POPULATED SECTION, AND THE OTHER KINDS NAMED. See
    `SubjectDossier` for why absence rather than an empty field carries "does not apply".

    THE FUNCTION PATH IS THE OLD PATH, byte for byte: `_dossier_conn` is called with the
    same arguments the function-only `dossier` passed it, so nothing about the common
    case changes except that it now travels inside an envelope that says what kind of
    thing it described.

    `depth` IS REFUSED ABOVE `MAX_SUBJECT_DEPTH` rather than clamped, for the reason
    every cap on this surface refuses: a clamped depth answers three hops to a request
    for eight and reports no difference, which is the silent-degradation failure the
    `_limited` disclosures exist to convert into a measurement.

    @brief Describe one subject of any kind, with its adjacency.
    @return SubjectDossier or None.
    @version 6
    """
    if depth < 1 or depth > MAX_SUBJECT_DEPTH:
        raise ValueError(
            f"depth must be between 1 and {MAX_SUBJECT_DEPTH}; {depth} was requested. "
            "Depth 1 is the subject and its immediate adjacency; deeper walks are "
            "bounded because an unbounded one on a hub symbol returns its whole "
            "component."
        )
    ## A SIGNATURE PASSED AS THE SELECTOR is what every 1.1.0 agent passed, because the served
    ## text said to. Recovered before resolution so the rest of this function sees the selector
    ## it would have seen from a correct caller; `""` leaves it untouched.
    if qualified:
        with connect(db) as conn:
            if not identity_rowids(conn, subject, qualified):
                recovered = _selector_from_signature(subject, qualified)
                qualified = recovered or (None if "(" in qualified else qualified)
    kinds = _rank_enum_over_mirror(db, subject, resolve_subject(db, subject))
    ## C7: a QUALIFIED spelling is one clew serves and used to refuse. Re-read only when the
    ## caller supplied no selector of its own — a caller that passed `qualified=` has
    ## disambiguated deliberately and must not have its subject reinterpreted underneath it.
    if qualified is None:
        subject, qualified, kinds = _qualified_reread(db, subject, kinds, kind)
    chosen = _chosen_kind(kinds, kind)
    if chosen is None:
        return None
    with connect(db) as conn:
        section = _BUILDERS[chosen](
            _BuildContext(conn, db, subject, qualified, repo_root, max_body_lines)
        )
    ## A builder that came back empty after its probe fired is NOT a resolved subject.
    ## The probe and the builder can legitimately disagree — a compound whose ranked
    ## lookup rejected every match, a lock row whose sections were all excluded — and
    ## returning an envelope naming a kind with nothing under it would claim a
    ## description that was never produced.
    if next(iter(section.values())) is None:
        return None
    return SubjectDossier(
        subject=subject,
        kind=chosen,
        also=tuple(k for k in kinds if k != chosen),
        chain=_chain_for(db, chosen, subject, depth, direction, max_neighbors, qualified),
        **section,
    )
Activity · 18 steps
lines 1001–1001◇ if depth < 1 or depth > MAX_SUBJECT_DEPTHlines 1002–1007raise ValueError( f"depth must be between 1 and {MAX_SUBJECT_DEPTH}; {depth} was requested. " "Depth 1 is the subject and its immediate adjacency; deeper walks are " "bounded because an unbounded one on a hub symbol returns its whole " "component." )lines 1011–1011◇ if qualifiedlines 1012–1012with connect(db) as connlines 1013–1013◇ if not identity_rowids(conn, subject, qualified)lines 1014–1014recovered = _selector_from_signature(subject, qualified)lines 1015–1015qualified = recovered or (None if "(" in qualified else qualified)lines 1016–1016kinds = _rank_enum_over_mirror(db, subject, resolve_subject(db, subject))lines 1020–1020◇ if qualified is Nonelines 1021–1021subject, qualified, kinds = _qualified_reread(db, subject, kinds, kind)lines 1022–1022chosen = _chosen_kind(kinds, kind)lines 1023–1023◇ if chosen is Nonelines 1024–1024return Nonelines 1025–1025with connect(db) as connlines 1026–1028section = _BUILDERS[chosen]( _BuildContext(conn, db, subject, qualified, repo_root, max_body_lines) )lines 1034–1034◇ if next(iter(section.values())) is Nonelines 1035–1035return Nonelines 1036–1042return SubjectDossier( subject=subject, kind=chosen, also=tuple(k for k in kinds if k != chosen), chain=_chain_for(db, chosen, subject, depth, direction, max_neighbors, qualified), **section, )

Flows

dossiers

dossiers(
    db: DbSource,
    subjects: list[str],
    kind: str | None = None,
    repo_root: Path | str | None = None,
    max_body_lines: int = DEFAULT_BODY_LINES,
    depth: int = 1,
)

clew/query/subject.py:1242

Source · 36 lines
def dossiers(
    db: DbSource,
    subjects: list[str],
    kind: str | None = None,
    repo_root: Path | str | None = None,
    max_body_lines: int = DEFAULT_BODY_LINES,
    depth: int = 1,
) -> list[SubjectDossier | None]:
    """ONE CONNECTION, N SUBJECTS, and the sharing is free rather than engineered:
    `connect` yields a caller-supplied `Connection` as-is, so passing the open connection
    down as `db` makes every nested `connect` inside `dossier` a no-op. Five
    subjects used to mean five sqlite opens and five sets of `table_exists` probes
    against the same file.

    POSITIONAL, INCLUDING THE MISSES, for the same reason `dossiers` is: a dropped miss
    silently re-labels every answer after it.

    NO `qualified`, for the same reason `dossiers` refuses it: one identity selector
    cannot say which of five names it disambiguates.

    @brief Describe several subjects of any kind in one pass.
    @return One SubjectDossier-or-None per requested name, in request order.
    @version 1
    """
    with connect(db) as conn:
        return [
            dossier(
                conn,
                name,
                kind=kind,
                repo_root=repo_root,
                max_body_lines=max_body_lines,
                depth=depth,
            )
            for name in subjects
        ]
Activity · 2 steps
lines 1266–1266with connect(db) as connlines 1267–1277return [ dossier( conn, name, kind=kind, repo_root=repo_root, max_body_lines=max_body_lines, depth=depth, ) for name in subjects ]

Flows

resolve_subject

resolve_subject(db: DbSource, name: str)

clew/query/subject.py:352

Source · 17 lines
def resolve_subject(db: DbSource, name: str) -> tuple[str, ...]:
    """ALL OF THEM, NOT THE FIRST. One string genuinely can be several subjects — a
    macro and the member it wraps, a lock and the variable that declares it — and a
    classifier that returned the first match would make the arbitrary pick invisible.
    That is the gh#26 failure one level up: an arbitrary resolution reported as the
    answer, with nothing on the wire saying a choice was made.

    EVERY PROBE IS ONE INDEXED LOOKUP against a table that is small or keyed, so
    classifying costs a handful of microseconds and the hot path — a name that is a
    function — is unchanged in what it then builds.

    @brief Classify a name across every subject corpus.
    @return The kinds it resolves to, in `SUBJECT_KINDS` order.
    @version 1
    """
    with connect(db) as conn:
        return tuple(k for k in SUBJECT_KINDS if _PROBES[k](conn, name))
Activity · 2 steps
lines 367–367with connect(db) as connlines 368–368return tuple(k for k in SUBJECT_KINDS if _PROBES[k](conn, name))

Flows

unresolved_kinds

unresolved_kinds(db: DbSource, name: str)

clew/query/subject.py:377

Source · 40 lines
def unresolved_kinds(db: DbSource, name: str) -> tuple[str, ...]:
    """WHY A MISS IS NOT ALWAYS AN ABSENCE (gh#6). `SUBJECT_KINDS` did not include
    `enumeration`, so a C enum type, its enumerators and a C++ `enum class` all resolved to
    NOTHING through `dossier` — while `SEARCHED_MEMBERDEF_KINDS` did include it, so `search`
    found the very same names. A reporter asked for four enum symbols they knew existed and got
    "Not indexed in this repository. A definitive negative from the database" on all four.

    THE ENUM CASE IS FIXED AND THIS FUNCTION IS NOT OBSOLETE. `enumeration` is a subject kind
    now, so it no longer reaches here — but `typedef` and `file` still do, and the reason this
    exists is the SHAPE rather than the one kind that motivated it. A surface that describes
    some memberdef kinds and not others will always have a gap, and the gap must read as a gap.

    THE DAMAGE IS THE CONFIDENCE, NOT THE GAP. A missing row worded as a limitation costs a
    follow-up call; a missing row worded as a definitive negative reads as "this tool is wrong
    about my repo", and on a codebase whose authoritative definitions are C enums it is wrong
    about the thing that matters most. Their words: the negative "reads as 'this tool isn't
    right about my repo' rather than 'this kind isn't indexed yet'".

    So this answers the question the miss note needs: is the name ABSENT, or merely of a kind
    this surface does not describe? Those are different answers and only one of them is a
    negative.

    ONE INDEXED LOOKUP over `memberdef`, and it runs only on the miss path — the hot path never
    reaches it.

    @brief The unsupported kinds an unresolvable name is nevertheless indexed under.
    @return Sorted kinds, or () when the name is genuinely not in the index.
    @version 2
    """
    with connect(db) as conn:
        if not table_exists(conn, "memberdef"):
            return ()
        rows = conn.execute(
            "SELECT DISTINCT kind FROM memberdef WHERE name = ? AND kind IS NOT NULL",
            (name,),
        ).fetchall()
    ## `macro definition` is the memberdef spelling of the `macro` SUBJECT kind, so it must not
    ## be reported as unsupported — it resolves fine and would send a reader chasing a phantom.
    supported = set(SUBJECT_KINDS) | {"macro definition"}
    return tuple(sorted({str(k) for (k,) in rows if str(k) not in supported}))
Activity · 6 steps
lines 406–406with connect(db) as connlines 407–407◇ if not table_exists(conn, "memberdef")lines 408–408return ()lines 409–412rows = conn.execute( "SELECT DISTINCT kind FROM memberdef WHERE name = ? AND kind IS NOT NULL", (name,), ).fetchall()lines 415–415supported = set(SUBJECT_KINDS) | {"macro definition"}lines 416–416return tuple(sorted({str(k) for (k,) in rows if str(k) not in supported}))

Flows