corpus.py

clew/query/corpus.py

Repo-shape queries: the file corpus, the prose corpus, and compounds.

_collapse

str clew.query.corpus._collapse(str|None text)

Collapse whitespace runs in a prose snippet (markup is NOT stripped).

clew/query/corpus.py:122

Source · 13 lines
def _collapse(text: str | None) -> str:
    """Prose is markdown, not doxygen markup: a `<stdio.h>` or a generic
    `<T>` inside a documentation snippet is CONTENT, so only whitespace runs
    (the newlines a multi-line chunk carries) are collapsed here — deliberately
    not `strip_xml`, which would delete it.

    @brief Whitespace-collapse a prose snippet.
    @return Single-spaced snippet text.
    @version 1
    """
    return re.sub(r"\s+", " ", text or "").strip()

Activity · 1 steps
lines 132–132return re.sub(r"\s+", " ", text or "").strip()

Flows

_extensions

tuple[str, ...] clew.query.corpus._extensions(list[str] paths)

Distinct dot-prefixed extensions of a path list.

clew/query/corpus.py:874

Source · 12 lines
def _extensions(paths: list[str]) -> tuple[str, ...]:
    """Splits on the BASENAME's last dot, so a dotted directory
    (`.github/workflows/ci.yml`) contributes `.yml` and not `.github/workflows/ci`.

    @brief Derive the extension set of a path list.
    @return Sorted extensions.
    @version 1
    """
    names = [p.rsplit("/", 1)[-1] for p in paths]
    return tuple(sorted({"." + n.rsplit(".", 1)[1].lower() for n in names if "." in n[1:]}))

Activity · 2 steps
lines 882–882names = [p.rsplit("/", 1)[-1] for p in paths]lines 883–883return tuple(sorted({"." + n.rsplit(".", 1)[1].lower() for n in names if "." in n[1:]}))

Flows

_fts_match

list[tuple] clew.query.corpus._fts_match(sqlite3.Connection conn, str text, int limit)

Run one FTS5 MATCH, retrying the raw text as a quoted phrase.

clew/query/corpus.py:930

Source · 23 lines
def _fts_match(conn: sqlite3.Connection, text: str, limit: int) -> list[tuple]:
    """Execute the MATCH query. FTS5 rejects unbalanced quotes and bare
    operators with an OperationalError, so a failed query is retried once with
    the whole text quoted as a literal phrase rather than surfacing a syntax
    error to a model.

    @brief Execute an FTS5 MATCH with a quoted-phrase fallback.
    @return Result rows.
    @version 2
    """
    sql = (
        "SELECT file_path, heading, "
        "snippet(supplementary_docs, 2, '>>', '<<', '…', 20) "
        "FROM supplementary_docs WHERE supplementary_docs MATCH ? "
        "ORDER BY rank LIMIT ?"
    )
    try:
        return conn.execute(sql, (text, limit)).fetchall()
    except sqlite3.OperationalError:
        phrase = '"' + text.replace('"', " ") + '"'
        return conn.execute(sql, (phrase, limit)).fetchall()

Activity · 6 steps
lines 940–945sql = ( "SELECT file_path, heading, " "snippet(supplementary_docs, 2, '>>', '<<', '…', 20) " "FROM supplementary_docs WHERE supplementary_docs MATCH ? " "ORDER BY rank LIMIT ?" )lines 946–946trylines 947–947return conn.execute(sql, (text, limit)).fetchall()lines 948–948except sqlite3.OperationalErrorlines 949–949phrase = '"' + text.replace('"', " ") + '"'lines 950–950return conn.execute(sql, (phrase, limit)).fetchall()

Flows

_include_graph

dict[str, Any] clew.query.corpus._include_graph(sqlite3.Connection conn, str name)

One file's include graph, both directions, from ast_includes .

clew/query/corpus.py:406

Source · 28 lines
def _include_graph(conn: sqlite3.Connection, name: str) -> dict[str, Any]:
    """T3 served (2.0.0). The AST layer, not doxygen's `includes`: on mbedtls doxygen's table held 2
    includers of `constant_time_internal.h` and `ast_includes` 18 (P2 measurement). An index
    without the table returns {} so both fields stay ABSENT rather than reading as "none".

    @brief Read the include graph.
    @return Field values.
    """
    if not table_exists(conn, "ast_includes"):
        return {}
    out = conn.execute(
        "SELECT i.spec, d.name, i.line, i.local FROM ast_includes i JOIN path s ON s.rowid = i.src_id "
        "LEFT JOIN path d ON d.rowid = i.dst_id WHERE s.name = ? ORDER BY i.line",
        (name,),
    ).fetchall()
    into = conn.execute(
        "SELECT s.name, i.line FROM ast_includes i JOIN path s ON s.rowid = i.src_id "
        "JOIN path d ON d.rowid = i.dst_id WHERE d.name = ? ORDER BY s.name, i.line",
        (name,),
    ).fetchall()
    return {
        "includes": tuple(
            IncludeRef(spec=s, file=f, line=int(ln), local=bool(lo)) for s, f, ln, lo in out
        ),
        "included_by": tuple(Includer(file=str(f), line=int(ln)) for f, ln in into),
    }

Activity · 5 steps
lines 414–414◇ if not table_exists(conn, "ast_includes")lines 415–415return {}lines 416–420out = conn.execute( "SELECT i.spec, d.name, i.line, i.local FROM ast_includes i JOIN path s ON s.rowid = i.src_id " "LEFT JOIN path d ON d.rowid = i.dst_id WHERE s.name = ? ORDER BY i.line", (name,), ).fetchall()lines 421–425into = conn.execute( "SELECT s.name, i.line FROM ast_includes i JOIN path s ON s.rowid = i.src_id " "JOIN path d ON d.rowid = i.dst_id WHERE d.name = ? ORDER BY s.name, i.line", (name,), ).fetchall()lines 426–431return { "includes": tuple( IncludeRef(spec=s, file=f, line=int(ln), local=bool(lo)) for s, f, ln, lo in out ), "included_by": tuple(Includer(file=str(f), line=int(ln)) for f, ln in into), }

Requirements

REQ-DDB-QUERY-004

_indexed_paths

list[str] clew.query.corpus._indexed_paths(sqlite3.Connection conn)

Every indexed, non-synthetic file path.

clew/query/corpus.py:910

Source · 13 lines
def _indexed_paths(conn: sqlite3.Connection) -> list[str]:
    """@brief List the real indexed file paths.
    @return Repo-relative paths.
    @version 1
    """
    if not table_exists(conn, "path"):
        return []
    rows = conn.execute(
        "SELECT name FROM path WHERE type = ? AND name <> ''", (PATH_TYPE_FILE,)
    ).fetchall()
    return [name for (name,) in rows if not SYNTHETIC_PATH.match(name)]

Activity · 4 steps
lines 915–915◇ if not table_exists(conn, "path")lines 916–916return []lines 917–919rows = conn.execute( "SELECT name FROM path WHERE type = ? AND name <> ''", (PATH_TYPE_FILE,) ).fetchall()lines 920–920return [name for (name,) in rows if not SYNTHETIC_PATH.match(name)]

Flows

_matches

bool clew.query.corpus._matches(str path, str pattern)

Whether a repo-relative path matches a * -glob pattern.

clew/query/corpus.py:85

Show on the map →

Called by list_files

Calls none

Source · 32 lines
def _matches(path: str, pattern: str) -> bool:
    """Match the FULL repo-relative path first (so `app/src/*` and `*.cpp`
    both work), then fall back to the basename (so a bare `Battery*` finds a
    nested file). Case-sensitive, like the paths themselves.

    **v2: A PATTERN WITH NO GLOB METACHARACTER IS TREATED AS A SUBSTRING.** This corpus takes a
    glob while `symbols`, `prose` and `config` all take substrings, so a caller passes a bare term
    here too and gets a confident empty. Measured on a graded cell:
    `search(corpus="files", text="llama")` returned **count=0** against a repository holding seven
    indexed `llama_cpp_*` source files, and the answer went on to conclude the dependency was
    contained in one directory — the exact error the question was built to catch.

    The reply made it worse by leading with the wrong reason: *"This corpus holds INDEXED SOURCE
    FILES only, so a build script ... is absent here BY CONSTRUCTION"*, true in general and false
    here, with "Re-glob more broadly" buried last.

    **NOTHING THAT MATCHED BEFORE CAN CHANGE.** A bare word is never a valid repo-relative path,
    so a metacharacter-free pattern previously matched a whole path or a whole basename or
    nothing; substring matching is a strict superset of those two. A pattern containing `*`, `?`
    or `[` is taken at its word and globs exactly as before.

    @brief Glob-match a path or its basename, or substring-match a bare term.
    @return Whether the pattern matches.
    @version 2
    """
    if not any(ch in pattern for ch in "*?["):
        return pattern in path
    return fnmatch.fnmatchcase(path, pattern) or fnmatch.fnmatchcase(
        path.rsplit("/", 1)[-1], pattern
    )

Activity · 3 steps
lines 110–110◇ if not any(ch in pattern for ch in "*?[")lines 111–111return pattern in pathlines 112–114return fnmatch.fnmatchcase(path, pattern) or fnmatch.fnmatchcase( path.rsplit("/", 1)[-1], pattern )

Flows

_not_indexed

tuple[str, ...] clew.query.corpus._not_indexed(dict[str, str] meta)

The build's record of file types it had in scope and holds no rows for.

clew/query/corpus.py:832

Show on the map →

Called by index_scope

Calls none

Source · 17 lines
def _not_indexed(meta: dict[str, str]) -> tuple[str, ...]:
    """READ, NOT DERIVED. The comparison belongs to the build, which had the tree it
    walked; the working copy at query time is a different tree. An index built before the
    row existed reports () — "not recorded" — and never a synthesised empty set, which
    would read as "nothing was missed".

    Already capped and ordered by the build (`cli._not_indexed_scope`), so this splits and
    does not re-rank: re-sorting here would quietly change which entries survived the cap.

    @brief Split the stamped not-indexed report.
    @return The entries.
    @version 1
    """
    recorded = meta.get("not_indexed", "")
    return tuple(part.strip() for part in recorded.split(",") if part.strip())

Activity · 2 steps
lines 845–845recorded = meta.get("not_indexed", "")lines 846–846return tuple(part.strip() for part in recorded.split(",") if part.strip())

Requirements

REQ-DDB-QUERY-007

Flows

_query_tokens

tuple[str, ...] clew.query.corpus._query_tokens(str text)

The query's tokens, stripped of FTS5 operator syntax.

clew/query/corpus.py:958

Source · 18 lines
def _query_tokens(text: str) -> tuple[str, ...]:
    """Each token is re-quoted as a literal phrase before it reaches FTS5, so the
    characters stripped here are the ones that would otherwise be read as OPERATORS
    (`*` prefix, `^` anchor, `-` NOT, parentheses, colons) or terminate the quoting.
    Dropping them is not a loss: FTS5's `unicode61` tokenizer already splits on every
    one of them when it builds the index, so a stripped token matches exactly what a
    stored token can be.

    @brief Split a query into FTS5-safe literal tokens.
    @return Sanitised tokens in query order.
    @version 1
    """
    cleaned = "".join(ch if ch.isalnum() or ch in "_'" else " " for ch in text)
    ## A token of pure punctuation ("_", "'") survives the split but tokenizes to NOTHING,
    ## and an empty FTS5 phrase is a syntax error rather than a harmless no-op.
    return tuple(token for token in cleaned.lower().split() if any(c.isalnum() for c in token))

Activity · 2 steps
lines 970–970cleaned = "".join(ch if ch.isalnum() or ch in "_'" else " " for ch in text)lines 973–973return tuple(token for token in cleaned.lower().split() if any(c.isalnum() for c in token))

Flows

_scope_provenance

dict[str, str] clew.query.corpus._scope_provenance(sqlite3.Connection conn)

The scope.

clew/query/corpus.py:891

Source · 14 lines
def _scope_provenance(conn: sqlite3.Connection) -> dict[str, str]:
    """{} rather than an exception on an older index, matching the query layer's
    standing rule that a degraded database answers thinly instead of failing.

    @brief Read the stored scope provenance.
    @return Prefix-stripped mapping.
    @version 1
    """
    if not table_exists(conn, "build_meta"):
        return {}
    rows = conn.execute("SELECT key, value FROM build_meta WHERE key LIKE 'scope.%'").fetchall()
    return {key.split(".", 1)[1]: value for key, value in rows}

Activity · 4 steps
lines 899–899◇ if not table_exists(conn, "build_meta")lines 900–900return {}lines 901–901rows = conn.execute("SELECT key, value FROM build_meta WHERE key LIKE 'scope.%'").fetchall()lines 902–902return {key.split(".", 1)[1]: value for key, value in rows}

Flows

class_rows

list[tuple[str, str, str, str]] clew.query.corpus.class_rows(sqlite3.Connection conn, list[str] tokens)

Compound rows matching EVERY token, or [] when compounds are unindexed.

clew/query/corpus.py:1074

Source · 47 lines
def class_rows(conn: sqlite3.Connection, tokens: list[str]) -> list[tuple[str, str, str, str]]:
    """gh#315, THE THIRD SEARCH CORPUS. `search` read function `memberdef` rows and
    file-level documentation, and nothing else — so a class name produced a confident
    EMPTY result, which a caller cannot distinguish from a measured negative. That is
    the worst failure mode this project has, and it is the one the graded agent hits:
    `search("WritePlan")` on this repository returned the `mcp_config.py` file doc and
    not the class defined in it.

    Classes were ABSENT from the searched set rather than outranked or filtered, so
    the fix is a corpus and not a weight. Matching is the same conjunction over name
    and brief the other two corpora use, so one query keeps one meaning whichever
    half answers it.

    STL COMPOUNDS ARE EXCLUDED HERE, unlike in `lookup_class` where they are merely
    demoted, and the asymmetry is deliberate. doxygen registers hundreds of `std::`
    compounds against its synthetic path row; ranking those into a DISCOVERY surface
    lets system headers crowd out the repository the caller asked about — the same
    reasoning that already excludes them from `list_files`. Demotion-not-exclusion
    still holds wherever a caller can name what they want: `lookup_class` answers for
    a `std::` name.

    @brief Match compound names and briefs against all query tokens.
    @return List of (name, kind, file, brief) tuples.
    @version 1
    """
    if not tokens or not table_exists(conn, "compounddef"):
        return []
    placeholders = ",".join("?" * len(CLASS_KINDS))
    clause = " AND ".join(
        ["(LOWER(c.name) LIKE ? OR LOWER(COALESCE(c.briefdescription,'')) LIKE ?)"] * len(tokens)
    )
    params: list[str] = list(CLASS_KINDS)
    for token in tokens:
        params += [f"%{token}%", f"%{token}%"]
    rows = conn.execute(
        "SELECT c.name, c.kind, COALESCE(p.name,''), COALESCE(c.briefdescription,'') "
        "FROM compounddef c LEFT JOIN path p ON p.rowid = c.file_id "
        f"WHERE c.kind IN ({placeholders}) AND {clause} ORDER BY c.name",
        params,
    ).fetchall()
    return [
        (name, kind, file, strip_xml(brief))
        for name, kind, file, brief in rows
        if not SYNTHETIC_PATH.match(file)
    ]

Activity · 9 steps
lines 1099–1099◇ if not tokens or not table_exists(conn, "compounddef")lines 1100–1100return []lines 1101–1101placeholders = ",".join("?" * len(CLASS_KINDS))lines 1102–1104clause = " AND ".join( ["(LOWER(c.name) LIKE ? OR LOWER(COALESCE(c.briefdescription,'')) LIKE ?)"] * len(tokens) )lines 1105–1105params: list[str] = list(CLASS_KINDS)lines 1106–1106◇ for token in tokenslines 1107–1107params += [f"%{token}%", f"%{token}%"]lines 1108–1113rows = conn.execute( "SELECT c.name, c.kind, COALESCE(p.name,''), COALESCE(c.briefdescription,'') " "FROM compounddef c LEFT JOIN path p ON p.rowid = c.file_id " f"WHERE c.kind IN ({placeholders}) AND {clause} ORDER BY c.name", params, ).fetchall()lines 1114–1118return [ (name, kind, file, strip_xml(brief)) for name, kind, file, brief in rows if not SYNTHETIC_PATH.match(file) ]

Requirements

REQ-DDB-QUERY-007

Flows

directory_rollup

DirectoryInventory clew.query.corpus.directory_rollup(DbSource db)

The indexed file set rolled up by top-level directory.

clew/query/corpus.py:1472

Source · 50 lines
def directory_rollup(db: DbSource) -> DirectoryInventory:
    """WHAT IS IN HERE, BY DIRECTORY. `list_files` has always answered this per FILE and no MCP
    surface could reach it — the `list_files` TOOL was deleted in the four-tool consolidation, so
    a working capability became unreachable. Measured on mbedtls 2026-08-14: Q4 replaced it with
    six `find … | wc -l` shell calls, which is 6 of its 11 fallbacks, and still missed the four
    marks it was computing them for.

    ROLLED UP RATHER THAN LISTED, because 450 file rows is the reply that made the config corpus
    unusable. The glob route (`text`) reaches the files themselves when a caller wants them.

    @brief Roll the indexed files up by top-level directory.
    @return The inventory.
    @version 1
    """
    with connect(db) as conn:
        owner = (
            f"p.{EXTERNAL_ROOT_COLUMN}" if has_columns(conn, "path", EXTERNAL_ROOT_COLUMN) else "''"
        )
        ## `dg_unresolved` is selected only when present, on the same absent-column contract the
        ## external tag uses: an index built before it reads 0, which is what that index knew.
        unresolved = "p.dg_unresolved" if has_columns(conn, "path", "dg_unresolved") else "0"
        rows = conn.execute(
            f"SELECT CASE WHEN instr(p.name, '/') > 0 "
            f"       THEN substr(p.name, 1, instr(p.name, '/') - 1) ELSE '.' END AS dir, "
            f"       COUNT(DISTINCT p.rowid), COUNT(DISTINCT m.name), "
            f"       SUM(CASE WHEN COALESCE({owner}, '') <> '' THEN 1 ELSE 0 END), "
            f"       SUM(CASE WHEN COALESCE({unresolved}, 0) <> 0 THEN 1 ELSE 0 END) "
            "FROM path p LEFT JOIN memberdef m ON m.file_id = p.rowid "
            "WHERE p.type = ? AND p.name <> '' AND p.name NOT LIKE '[%' "
            "GROUP BY dir ORDER BY 2 DESC, dir",
            (PATH_TYPE_FILE,),
        ).fetchall()
    entries = tuple(
        DirectoryEntry(
            directory=name,
            indexed_files=files,
            symbols=symbols,
            external_files=external or 0,
            unresolved_files=unresolved_count or 0,
        )
        for name, files, symbols, external, unresolved_count in rows
    )
    indexed = sum(e.indexed_files for e in entries)
    return DirectoryInventory(
        directories=entries[:_DIR_CAP],
        indexed_files=indexed,
        rollup_meaning=rollup_meaning(indexed, min(len(entries), _DIR_CAP), len(entries)),
    )

Activity · 7 steps
lines 1486–1486with connect(db) as connlines 1487–1489owner = ( f"p.{EXTERNAL_ROOT_COLUMN}" if has_columns(conn, "path", EXTERNAL_ROOT_COLUMN) else "''" )lines 1492–1492unresolved = "p.dg_unresolved" if has_columns(conn, "path", "dg_unresolved") else "0"lines 1493–1503rows = conn.execute( f"SELECT CASE WHEN instr(p.name, '/') > 0 " f" THEN substr(p.name, 1, instr(p.name, '/') - 1) ELSE '.' END AS dir, " f" COUNT(DISTINCT p.rowid), COUNT(DISTINCT m.name), " f" SUM(CASE WHEN COALESCE({owner}, '') <> '' THEN 1 ELSE 0 END), " f" SUM(CASE WHEN COALESCE({unresolved}, 0) <> 0 THEN 1 ELSE 0 END) " "FROM path p LEFT JOIN memberdef m ON m.file_id = p.rowid " "WHERE p.type = ? AND p.name <> '' AND p.name NOT LIKE '[%' " "GROUP BY dir ORDER BY 2 DESC, dir", (PATH_TYPE_FILE,), ).fetchall()lines 1504–1513entries = tuple( DirectoryEntry( directory=name, indexed_files=files, symbols=symbols, external_files=external or 0, unresolved_files=unresolved_count or 0, ) for name, files, symbols, external, unresolved_count in rows )lines 1514–1514indexed = sum(e.indexed_files for e in entries)lines 1515–1519return DirectoryInventory( directories=entries[:_DIR_CAP], indexed_files=indexed, rollup_meaning=rollup_meaning(indexed, min(len(entries), _DIR_CAP), len(entries)), )

Requirements

REQ-DDB-QUERY-002

Flows

doc_scope

dict[str, str] clew.query.corpus.doc_scope(DbSource db)

What the repository DECLARES about its own doc build and its vendored trees.

clew/query/corpus.py:1539

Source · 37 lines
def doc_scope(db: DbSource) -> dict[str, str]:
    """THE INDEX KNEW THIS AND NO QUERY RETURNED IT. `scope.doxyfile_*` has been stamped since the
    `doxyfile:` declaration key landed, and it was reachable only through `index(action='status')`
    on the DERIVED target — which refuses a named one. Measured on mbedtls 2026-08-14: the Q4 cell
    ran `find -iname "Doxyfile*"`, `find -iname "*doxygen*"`, an `ls`, and finally a
    `grep -E "^(INPUT|RECURSIVE|EXCLUDE|FILE_PATTERNS...)"` OF THE DOXYFILE — reading by hand the
    three values sitting in `build_meta` the whole time.

    A PLAIN MAPPING, NOT A MODEL, and deliberately: every value is a string copied verbatim out of
    `build_meta`, the key set is the storage's own, and a dataclass here would add a second place
    for the key names to drift from the writer. `doc_scope_meaning` carries the one thing a reader
    cannot get from the values.

    RETURNS {} WHEN NOTHING IS DECLARED, which is a different fact from "this repo has no Doxyfile"
    — the caller is told which, rather than being left to infer absence from emptiness.

    @brief Read the declared documentation scope and vendored roots.
    @return Declared-scope mapping, empty when the repository states none.
    @version 1
    """
    with connect(db) as conn:
        stated = {k: v for k, v in _scope_provenance(conn).items() if k in _DECLARED_SCOPE_KEYS}
    if not stated:
        return {}
    parts = []
    if "doxyfile_path" in stated:
        parts.append(
            f"`{stated['doxyfile_path']}` is the doc build THIS REPOSITORY declares, and "
            f"`doxyfile_input`/`doxyfile_file_patterns` are ITS scope — which is NOT this index's "
            f"scope. A doc build is a publishing target; the index covers the whole repository."
        )
    if "vendored_roots" in stated:
        parts.append(
            f"`{stated['vendored_roots']}` is declared vendored: committed into this repository "
            f"but not written by it."
        )
    return {**stated, "doc_scope_meaning": " ".join(parts)}

1 more lines, not shown

Activity · 10 steps
lines 1559–1559with connect(db) as connlines 1560–1560stated = {k: v for k, v in _scope_provenance(conn).items() if k in _DECLARED_SCOPE_KEYS}lines 1561–1561◇ if not statedlines 1562–1562return {}lines 1563–1563parts = []lines 1564–1564◇ if "doxyfile_path" in statedlines 1565–1569parts.append( f"`{stated['doxyfile_path']}` is the doc build THIS REPOSITORY declares, and " f"`doxyfile_input`/`doxyfile_file_patterns` are ITS scope — which is NOT this index's " f"scope. A doc build is a publishing target; the index covers the whole repository." )lines 1570–1570◇ if "vendored_roots" in statedlines 1571–1574parts.append( f"`{stated['vendored_roots']}` is declared vendored: committed into this repository " f"but not written by it." )lines 1575–1575return {**stated, "doc_scope_meaning": " ".join(parts)}

Requirements

REQ-DDB-QUERY-007

Flows

file_doc_rows

list[tuple[str, str]] clew.query.corpus.file_doc_rows(sqlite3.Connection conn, list[str] tokens)

File-level documentation rows matching EVERY token, or [] when unindexed.

clew/query/corpus.py:600

Source · 30 lines
def file_doc_rows(conn: sqlite3.Connection, tokens: list[str]) -> list[tuple[str, str]]:
    """The gh#10 half of `search`: a module docstring or a file-level `@file`
    comment is a searchable unit, and the FILE is the hit.

    Deliberately NOT an FTS5 query even though the same text is also in
    `supplementary_docs`. `search` promises a CONJUNCTION over tokens with its own
    ranking, and reusing FTS5 here would give one tool two different matching
    semantics depending on which half of it answered — the sort of split that
    makes a result impossible to reason about. `file_docs` is one row per file, so
    a LIKE scan over it is cheap.

    An older index has no `file_docs` table; [] is the honest answer and the
    caller's note says the corpus was absent rather than that nothing matched.

    @brief Match file-level documentation against all query tokens.
    @return List of (path, documentation) pairs.
    @version 2
    """
    if not tokens or not table_exists(conn, "file_docs"):
        return []
    clause = " AND ".join(["(LOWER(file_path) LIKE ? OR LOWER(doc) LIKE ?)"] * len(tokens))
    params: list[str] = []
    for token in tokens:
        params += [f"%{token}%", f"%{token}%"]
    return conn.execute(
        f"SELECT file_path, doc FROM file_docs WHERE {clause} ORDER BY file_path",
        params,
    ).fetchall()

Activity · 7 steps
lines 618–618◇ if not tokens or not table_exists(conn, "file_docs")lines 619–619return []lines 620–620clause = " AND ".join(["(LOWER(file_path) LIKE ? OR LOWER(doc) LIKE ?)"] * len(tokens))lines 621–621params: list[str] = []lines 622–622◇ for token in tokenslines 623–623params += [f"%{token}%", f"%{token}%"]lines 624–627return conn.execute( f"SELECT file_path, doc FROM file_docs WHERE {clause} ORDER BY file_path", params, ).fetchall()

Requirements

REQ-DDB-QUERY-007

Flows

file_license

LicenseRef | None clew.query.corpus.file_license(sqlite3.Connection conn, str name)

The SPDX licence one file declares.

clew/query/corpus.py:385

Source · 14 lines
def file_license(conn: sqlite3.Connection, name: str) -> LicenseRef | None:
    """2.0.0 (S5 served). P2 built `file_licenses` (475 rows on entropic) and nothing served it.

    @brief Read a file's licence.
    @return The licence or None.
    """
    if not table_exists(conn, "file_licenses"):
        return None
    row = conn.execute(
        "SELECT license, line FROM file_licenses WHERE file_path = ?", (name,)
    ).fetchone()
    return LicenseRef(expression=str(row[0]), line=int(row[1])) if row else None

Activity · 4 steps
lines 391–391◇ if not table_exists(conn, "file_licenses")lines 392–392return Nonelines 393–395row = conn.execute( "SELECT license, line FROM file_licenses WHERE file_path = ?", (name,) ).fetchone()lines 396–396return LicenseRef(expression=str(row[0]), line=int(row[1])) if row else None

Requirements

REQ-DDB-QUERY-004

file_owners

tuple[OwnerRef, ...] | None clew.query.corpus.file_owners(sqlite3.Connection conn, str name)

Who owns one file, from the ownership layer.

clew/query/corpus.py:360

Source · 19 lines
def file_owners(conn: sqlite3.Connection, name: str) -> tuple[OwnerRef, ...] | None:
    """2.0.0 (S2/S3 served). P2 built `owners` (656 rows on entropic) and nothing served it.

    @brief Read a file's owners.
    @return Owners or None.
    """
    if not table_exists(conn, "owners"):
        return None
    rows = conn.execute(
        "SELECT o.owner, o.role, o.source, o.rule_line, o.stanza FROM owners o "
        "JOIN path p ON p.rowid = o.path_rowid WHERE p.name = ? ORDER BY o.rowid",
        (name,),
    ).fetchall()
    return tuple(
        OwnerRef(owner=o, role=r, source=s, rule_line=int(ln), stanza=st or "")
        for o, r, s, ln, st in rows
    )

Activity · 4 steps
lines 366–366◇ if not table_exists(conn, "owners")lines 367–367return Nonelines 368–372rows = conn.execute( "SELECT o.owner, o.role, o.source, o.rule_line, o.stanza FROM owners o " "JOIN path p ON p.rowid = o.path_rowid WHERE p.name = ? ORDER BY o.rowid", (name,), ).fetchall()lines 373–376return tuple( OwnerRef(owner=o, role=r, source=s, rule_line=int(ln), stanza=st or "") for o, r, s, ln, st in rows )

Requirements

REQ-DDB-QUERY-004

Flows

file_subject

FileSubject | None clew.query.corpus.file_subject(sqlite3.Connection conn, str name)

Everything this index holds about ONE file, as a dossier subject.

clew/query/corpus.py:306

Source · 48 lines
def file_subject(conn: sqlite3.Connection, name: str) -> FileSubject | None:
    """C1 of the 1.1.0 acceptance review, and the single largest item in it: 48 of 237 missed
    `dossier` subjects were file paths, and five graded clusters carrying 31 weight lost marks
    that are file-level claims.

    THE DOCUMENTATION IS THE POINT. `file_docs` held 2,794 characters about `clew/tiers.py`
    and the only route to it was `search`, whose file half is a token CONJUNCTION — a caller
    had to guess words appearing in the prose it was trying to read, and its hit was ranked
    against member and markdown hits. Read HERE by exact path, which is the lookup the caller
    was actually trying to express.

    `file_docs` IS OPTIONAL and its absence is not an empty document. An index built before
    gh#10 has no such table, so `documentation` is `''` — and `has_file_docs` is what
    distinguishes that from a file carrying no comment. Reported once for the index rather
    than repeated on every file, because it is a fact about the build.

    @brief Build the file subject by exact path.
    @return FileSubject or None.
    @version 4
    """
    if not is_indexed_file(conn, name):
        return None
    owner = f"p.{EXTERNAL_ROOT_COLUMN}" if has_columns(conn, "path", EXTERNAL_ROOT_COLUMN) else "''"
    where, params = _one_file_clause(conn, name)
    root = conn.execute(
        f"SELECT COALESCE({owner}, '') FROM path p WHERE {where} LIMIT 1",  # noqa: S608
        params,
    ).fetchone()
    members = _file_members(conn, name)
    return FileSubject(
        path=name,
        documentation=_file_documentation(conn, name),
        ## COUNTED OFF THE SAME ROWS THE LIST IS BUILT FROM, so the two cannot disagree —
        ## and counted before the cap, so a truncated list still reports the true total.
        symbol_count=len(members),
        members=tuple(members[:_FILE_MEMBER_CAP]),
        harvested=_was_harvested(conn, name),
        external_root=(root[0] if root else "") or "",
        ## BOTH DIRECTIONS, because both are asked of a file and neither answers the other.
        generated_by=generation_rule(conn, name),
        generates=generates_files(conn, name),
        members_truncated=len(members) > _FILE_MEMBER_CAP,
        **_include_graph(conn, name),
        owners=file_owners(conn, name),
        license=file_license(conn, name),
    )

Activity · 7 steps
lines 326–326◇ if not is_indexed_file(conn, name)lines 327–327return Nonelines 328–328owner = f"p.{EXTERNAL_ROOT_COLUMN}" if has_columns(conn, "path", EXTERNAL_ROOT_COLUMN) else "''"lines 329–329where, params = _one_file_clause(conn, name)lines 330–333root = conn.execute( f"SELECT COALESCE({owner}, '') FROM path p WHERE {where} LIMIT 1", # noqa: S608 params, ).fetchone()lines 334–334members = _file_members(conn, name)lines 335–351return FileSubject( path=name, documentation=_file_documentation(conn, name), ## COUNTED OFF THE SAME ROWS THE LIST IS BUILT FROM, so the two cannot disagree — ## and counted before the cap, so a truncated list still reports the true total. symbol_count=len(members), members=tuple(members[:_FILE_MEMBER_CAP]), harvested=_was_harvested(conn, name), external_root=(root[0] if root else "") or "", ## BOTH DIRECTIONS, because both are asked of a file and neither answers the other. generated_by=generation_rule(conn, name), generates=generates_files(conn, name), members_truncated=len(members) > _FILE_MEMBER_CAP, **_include_graph(conn, name), owners=file_owners(conn, name), license=file_license(conn, name), )

Requirements

REQ-DDB-QUERY-004

gate_symbol_rows

list[tuple[str, int, str, str]] clew.query.corpus.gate_symbol_rows(sqlite3.Connection conn, list[str] tokens)

Gating-symbol rows matching EVERY token, with their gate-site counts.

clew/query/corpus.py:1127

Source · 40 lines
def gate_symbol_rows(
    conn: sqlite3.Connection, tokens: list[str]
) -> list[tuple[str, int, str, str]]:
    """gh#394, THE EIGHTH SEARCH CORPUS, and the fourth instance of one recurring defect:
    a layer present in the index that `search` never read, so its names came back a
    confident zero rather than being outranked. Variables were gh#372, macros gh#373,
    typedefs and enumerations gh#374; this is the CONFIGURATION SPACE.

    THE MEASUREMENT. After gh#390 the mbedtls index holds 10,861 gating sites over 1,327
    symbols, and `search("MBEDTLS_THREADING_PTHREAD")` still returned NOTHING — `dossier`
    answered only if you already knew the name. The graded agent searched for those symbols
    BY NAME nine times across one benchmark run and was refused every time, which is the
    discovery half of the same question: "is this compiled in, and under what flag".

    NO BRIEF COLUMN, so matching is on the NAME alone. A gate row is a location, not a
    documented entity — its meaning lives in the Kconfig help text or the config header's
    comment, which `search_prose` and `kconfig_symbols` already carry. Inventing a prose
    column here would let a two-token conceptual query match a bare identifier on one word
    and rank it beside a documented symbol.

    AGGREGATED PER SYMBOL. One row per symbol with its site count, never one row per site:
    `MBEDTLS_THREADING_C` gates 151 lines, and 151 identical-looking hits would bury every
    other corpus in the reply for a query that means one thing.

    @brief Match gating symbols by name, aggregated with their site counts.
    @return (symbol, sites, first file, origin) tuples.
    @version 1
    """
    if not tokens or not table_exists(conn, "kconfig_gates"):
        return []
    origin = "origin" if has_columns(conn, "kconfig_gates", "origin") else "''"
    clause = " AND ".join(["LOWER(symbol) LIKE ?"] * len(tokens))
    rows = conn.execute(
        f"SELECT symbol, COUNT(*), MIN(file_path), MIN({origin}) FROM kconfig_gates "  # noqa: S608
        f"WHERE {clause} GROUP BY symbol ORDER BY symbol",
        [f"%{token}%" for token in tokens],
    ).fetchall()
    return [(symbol, sites, file, org) for symbol, sites, file, org in rows]

Activity · 6 steps
lines 1155–1155◇ if not tokens or not table_exists(conn, "kconfig_gates")lines 1156–1156return []lines 1157–1157origin = "origin" if has_columns(conn, "kconfig_gates", "origin") else "''"lines 1158–1158clause = " AND ".join(["LOWER(symbol) LIKE ?"] * len(tokens))lines 1159–1163rows = conn.execute( f"SELECT symbol, COUNT(*), MIN(file_path), MIN({origin}) FROM kconfig_gates " # noqa: S608 f"WHERE {clause} GROUP BY symbol ORDER BY symbol", [f"%{token}%" for token in tokens], ).fetchall()lines 1164–1164return [(symbol, sites, file, org) for symbol, sites, file, org in rows]

Requirements

REQ-DDB-QUERY-007

Flows

generates_files

tuple[str, ...] clew.query.corpus.generates_files(sqlite3.Connection conn, str name)

The files this file produces, by basename.

clew/query/corpus.py:570

Source · 24 lines
def generates_files(conn: sqlite3.Connection, name: str) -> tuple[str, ...]:
    """THE OTHER DIRECTION, asked by a different reader. mbedtls Q4 asks "what a contributor has
    to do to add a new one", and a contributor editing `generate_errors.pl` needs to know what
    regenerates — which is how they check they edited the right input rather than the output.

    A file named in a rule's COMMAND is a producer; one named only in DEPENDS is an input, and
    `error.fmt` must not be reported as generating `error.c`. The role distinction is the whole
    reason it is stored.

    @brief What this file produces.
    @return Output basenames.
    @version 1
    """
    if not table_exists(conn, "generated_files"):
        return ()
    base = name.rsplit("/", 1)[-1]
    rows = conn.execute(
        "SELECT DISTINCT output_name FROM generated_files "
        "WHERE role = 'command' AND arg_name = ? AND output_name <> '' ORDER BY output_name",
        (base,),
    ).fetchall()
    return tuple(str(n) for (n,) in rows)

Activity · 5 steps
lines 583–583◇ if not table_exists(conn, "generated_files")lines 584–584return ()lines 585–585base = name.rsplit("/", 1)[-1]lines 586–590rows = conn.execute( "SELECT DISTINCT output_name FROM generated_files " "WHERE role = 'command' AND arg_name = ? AND output_name <> '' ORDER BY output_name", (base,), ).fetchall()lines 591–591return tuple(str(n) for (n,) in rows)

Requirements

REQ-DDB-QUERY-004

generation_rule

GenerationRule | None clew.query.corpus.generation_rule(sqlite3.Connection conn, str name)

The build rule that produces a file, by BASENAME, or None when nothing produces it.

clew/query/corpus.py:498

Source · 66 lines
def generation_rule(conn: sqlite3.Connection, name: str) -> GenerationRule | None:
    """MATCHED ON BASENAME, AND THAT IS A STATED LIMIT RATHER THAN A SHORTCUT. A build file writes
    `${CMAKE_CURRENT_BINARY_DIR}/error.c` and the index holds `library/error.c`; neither string
    contains the other, and resolving the variable needs a configure step the index never ran.
    The basename is the only honest join available.

    ITS FAILURE MODE IS NAMED: two files of the same basename in different directories, where one
    is generated, would both match. That is a real ambiguity and it is better than the
    alternatives — resolving the variable would invent a path, and refusing to join at all leaves
    the fact mbedtls Q4's rubric calls decisive unreachable. A reader who doubts it has
    `source_file` and `source_line` to go read the rule.

    @brief Look up the rule producing this file.
    @return The GenerationRule, or None.
    @version 2
    """
    if not table_exists(conn, "generated_files"):
        return None
    columns = (
        "SELECT output_name, output_literal, kind, source_file, source_line, "
        "role, arg_name, arg_literal, unresolved, "
        f"{'arg_resolved' if has_columns(conn, 'generated_files', 'arg_resolved') else chr(39) * 2} "
        "FROM generated_files "
    )
    ## A SELF-DECLARED ROW KNOWS ITS EXACT PATH, so it is matched on it — and kept OUT of the
    ## basename join below. Joined by basename, mattermost-mobile's one generated file,
    ## `app/utils/emoji/index.ts`, would have marked every `index.ts` in the repository generated.
    rows = conn.execute(
        columns + "WHERE output_literal = ? AND kind LIKE 'self-declared:%' ORDER BY rowid",
        (name,),
    ).fetchall()
    base = name.rsplit("/", 1)[-1]
    rows = (
        rows
        or conn.execute(
            columns + "WHERE output_name = ? AND output_name <> '' "
            "AND kind NOT LIKE 'self-declared:%' ORDER BY rowid",
            (base,),
        ).fetchall()
    )
    if not rows:
        return None
    head = rows[0]
    args: dict[str, list[GenerationArg]] = {"command": [], "depends": []}
    for row in rows:
        role = str(row[5])
        if role in args:
            args[role].append(
                GenerationArg(
                    literal=str(row[7]),
                    name=str(row[6]),
                    unresolved=bool(row[8]),
                    resolved=str(row[9]) or None,
                )
            )
    return GenerationRule(
        output_name=str(head[0]),
        output_literal=str(head[1]),
        kind=str(head[2]),
        source_file=str(head[3]),
        source_line=int(head[4] or 0),
        command=tuple(args["command"]),
        depends=tuple(args["depends"]),
    )

Activity · 15 steps
lines 514–514◇ if not table_exists(conn, "generated_files")lines 515–515return Nonelines 516–521columns = ( "SELECT output_name, output_literal, kind, source_file, source_line, " "role, arg_name, arg_literal, unresolved, " f"{'arg_resolved' if has_columns(conn, 'generated_files', 'arg_resolved') else chr(39) * 2} " "FROM generated_files " )lines 525–528rows = conn.execute( columns + "WHERE output_literal = ? AND kind LIKE 'self-declared:%' ORDER BY rowid", (name,), ).fetchall()lines 529–529base = name.rsplit("/", 1)[-1]lines 530–537rows = ( rows or conn.execute( columns + "WHERE output_name = ? AND output_name <> '' " "AND kind NOT LIKE 'self-declared:%' ORDER BY rowid", (base,), ).fetchall() )lines 538–538◇ if not rowslines 539–539return Nonelines 540–540head = rows[0]lines 541–541args: dict[str, list[GenerationArg]] = {"command": [], "depends": []}lines 542–542◇ for row in rowslines 543–543role = str(row[5])lines 544–544◇ if role in argslines 545–552args[role].append( GenerationArg( literal=str(row[7]), name=str(row[6]), unresolved=bool(row[8]), resolved=str(row[9]) or None, ) )lines 553–561return GenerationRule( output_name=str(head[0]), output_literal=str(head[1]), kind=str(head[2]), source_file=str(head[3]), source_line=int(head[4] or 0), command=tuple(args["command"]), depends=tuple(args["depends"]), )

Requirements

REQ-DDB-QUERY-004

has_file_docs

bool clew.query.corpus.has_file_docs(DbSource db)

Whether this index carries a file-level documentation corpus at all.

clew/query/corpus.py:768

Source · 14 lines
def has_file_docs(db: DbSource) -> bool:
    """Exists so an empty `search` can distinguish "the documentation was searched
    and does not contain this" from "there is no documentation corpus in this
    index". Those are different claims and the second one is the caller's cue to
    rebuild, not to give up.

    @brief Report presence of the file-level documentation corpus.
    @return Whether `file_docs` exists.
    @version 1
    """
    with connect(db) as conn:
        return table_exists(conn, "file_docs")

Activity · 2 steps
lines 778–778with connect(db) as connlines 779–779return table_exists(conn, "file_docs")

Requirements

REQ-DDB-QUERY-007

Flows

has_prose_corpus

bool clew.query.corpus.has_prose_corpus(DbSource db)

Whether this index carries an ingested markdown corpus at all.

clew/query/corpus.py:746

Source · 17 lines
def has_prose_corpus(db: DbSource) -> bool:
    """The prose counterpart of `has_file_docs`, and it exists for the identical reason one corpus
    over: an empty prose reply must be able to distinguish "the documentation was read and does not
    say this" from "this index has no documentation to read". Only the first is a fact about the
    repository; the second is a fact about the build, and the caller's cue is to rebuild.

    Without it the prose corpus asserted the strong "definitive empty result" wording in both
    cases — measured on mbedtls, about a token the same index held in three `memberdef` rows.

    @brief Report presence of the ingested markdown corpus.
    @return Whether `supplementary_docs` exists.
    @version 1
    """
    with connect(db) as conn:
        return table_exists(conn, "supplementary_docs")

Activity · 2 steps
lines 759–759with connect(db) as connlines 760–760return table_exists(conn, "supplementary_docs")

Requirements

REQ-DDB-QUERY-007

Flows

index_scope

IndexScope clew.query.corpus.index_scope(DbSource db, int cap=12)

A has_gate_layer helper lived here for gh#393 and is deliberately gone with the verdict change it existed to serve.

clew/query/corpus.py:794

Source · 33 lines
def index_scope(db: DbSource, cap: int = 12) -> IndexScope:
    """gh#21. An empty answer used to assert a definitive negative without naming
    the scope that produced it: `list_files("*.c")` reported "the database records
    none" from a checkout containing 53 `.c` files, every clause true of the
    database and the whole effect a false statement about the repository.

    What the caller needed was the scope, which `build_meta` has carried since
    build 17 — and which only `status` read, a separate call the caller had no
    reason to make. This is the SUMMARY form: counts, top-level directories and
    extensions, capped. `status` keeps its own raw read (`state._scope_meta`)
    because the two answer different questions — status reports the decision
    verbatim, and an empty answer needs a compact statement of what was covered.
    Ninety root paths in an empty-result note would be a token bomb.

    @brief Summarise what was indexed and why.
    @return IndexScope.
    @version 1
    """
    with connect(db) as conn:
        meta = _scope_provenance(conn)
        paths = _indexed_paths(conn)
    tops = sorted({p.split("/", 1)[0] for p in paths if "/" in p})
    return IndexScope(
        source=meta.get("source", ""),
        reason=meta.get("reason", ""),
        file_count=len(paths),
        top_levels=tuple(tops[:cap]),
        extensions=_extensions(paths)[:cap],
        not_indexed=_not_indexed(meta),
        not_indexed_count=int(meta.get("not_indexed_count") or 0),
    )

Activity · 5 steps
lines 812–812with connect(db) as connlines 813–813meta = _scope_provenance(conn)lines 814–814paths = _indexed_paths(conn)lines 815–815tops = sorted({p.split("/", 1)[0] for p in paths if "/" in p})lines 816–824return IndexScope( source=meta.get("source", ""), reason=meta.get("reason", ""), file_count=len(paths), top_levels=tuple(tops[:cap]), extensions=_extensions(paths)[:cap], not_indexed=_not_indexed(meta), not_indexed_count=int(meta.get("not_indexed_count") or 0), )

Requirements

REQ-DDB-QUERY-007

Flows

indexed_extensions

tuple[str, ...] clew.query.corpus.indexed_extensions(DbSource db)

Every file extension present in the indexed set, uncapped.

clew/query/corpus.py:854

Source · 15 lines
def indexed_extensions(db: DbSource) -> tuple[str, ...]:
    """Separate from `IndexScope.extensions`, which is CAPPED for display, because
    the caller that decides whether `*.c` can possibly match must not read a
    truncated list as a complete one. That mistake would manufacture exactly the
    false certainty gh#21 is about — a definite "no `.c` file is indexed" derived
    from a list that stopped at twelve.

    @brief List all indexed file extensions.
    @return Sorted extension tuple.
    @version 1
    """
    with connect(db) as conn:
        return _extensions(_indexed_paths(conn))

Activity · 2 steps
lines 865–865with connect(db) as connlines 866–866return _extensions(_indexed_paths(conn))

Requirements

REQ-DDB-QUERY-007

is_indexed_file

bool clew.query.corpus.is_indexed_file(sqlite3.Connection conn, str name)

True when this index holds a non-synthetic path row for exactly this name.

clew/query/corpus.py:230

Source · 25 lines
def is_indexed_file(conn: sqlite3.Connection, name: str) -> bool:
    """EXACT MATCH, NOT A SUFFIX MATCH, and that is the whole reason this probe is safe to
    run against every bare name `dossier` is given. `path.name` holds repo-relative paths, so
    no ordinary identifier equals one and adding this probe cannot change what any existing
    bare name resolves to. A suffix match would: `dm.c` would resolve as a file and shadow
    whatever symbol spells itself that way.

    The synthetic row is excluded for the reason `list_files` excludes it — `[STL]` is
    doxygen's placeholder owner for standard-library symbols, not a file anyone can open, and
    a subject whose purpose is naming a readable file must not serve one that is not.

    @brief Probe the file corpus for an exact path.
    @return Whether the path is an indexed file.
    @version 1
    """
    if not name or SYNTHETIC_PATH.match(name) or not table_exists(conn, "path"):
        return False
    where, params = _one_file_clause(conn, name)
    row = conn.execute(
        f"SELECT 1 FROM path p WHERE {where} LIMIT 1",
        params,  # noqa: S608
    ).fetchone()
    return row is not None

Activity · 5 steps
lines 245–245◇ if not name or SYNTHETIC_PATH.match(name) or not table_exists(conn, "path")lines 246–246return Falselines 247–247where, params = _one_file_clause(conn, name)lines 248–251row = conn.execute( f"SELECT 1 FROM path p WHERE {where} LIMIT 1", params, # noqa: S608 ).fetchone()lines 252–252return row is not None

Requirements

REQ-DDB-QUERY-004

list_files

list[FileEntry] clew.query.corpus.list_files(DbSource db, str|None pattern=None)

The indexed source files, with documented-symbol counts.

clew/query/corpus.py:143

Source · 47 lines
def list_files(db: DbSource, pattern: str | None = None) -> list[FileEntry]:
    """Inventory every real source file the database knows about, with the
    number of distinct documented symbols located in it, and which nested git tree
    owns it. Excludes doxygen's synthetic `[STL]` entry and directory rows.

    EXTERNAL FILES ARE LISTED, ANNOTATED, NEVER FILTERED (gh#335). The tag exists so
    that AGGREGATES can report first party by default; an inventory is not an
    aggregate, and a `list_files` that quietly omitted a submodule would be the exact
    failure the emptiness notes exist to prevent — an answer that is short because it
    was filtered, presented as an answer that is short because the repo is.

    @brief List indexed files (optionally glob-filtered) with symbol counts.
    @return List of FileEntry.
    @version 3
    """
    with connect(db) as conn:
        ## A LITERAL, NOT A QUALIFIED NAME, on an index predating the tag: `p.''` is
        ## a syntax error, so the absent-column branch has to substitute the whole
        ## select expression rather than the column name inside it.
        owner = (
            f"p.{EXTERNAL_ROOT_COLUMN}" if has_columns(conn, "path", EXTERNAL_ROOT_COLUMN) else "''"
        )
        ## THE SYMBOL JOIN IS CONDITIONAL, on the graceful-degradation contract every other
        ## query here obeys. An index can hold a `path` layer and no `memberdef` table — the
        ## parse front end's `register_paths` creates path rows before any harvest writes a
        ## symbol — and this raised `no such table: memberdef` rather than reporting the file set
        ## it demonstrably had. Found by C5's registration test, which builds exactly that index
        ## because that is the state a no-grammar file is registered into.
        join, count = (
            ("LEFT JOIN memberdef m ON m.file_id = p.rowid", "COUNT(DISTINCT m.name)")
            if table_exists(conn, "memberdef")
            else ("", "0")
        )
        rows = conn.execute(
            f"SELECT p.name, {count}, {owner} FROM path p "  # noqa: S608
            f"{join} "
            "WHERE p.type = ? AND p.name <> '' "
            "GROUP BY p.rowid ORDER BY p.name",
            (PATH_TYPE_FILE,),
        ).fetchall()
    return [
        FileEntry(path=name, symbol_count=count, external_root=owner_root or "")
        for name, count, owner_root in rows
        if not SYNTHETIC_PATH.match(name) and (pattern is None or _matches(name, pattern))
    ]

Activity · 5 steps
lines 158–158with connect(db) as connlines 162–164owner = ( f"p.{EXTERNAL_ROOT_COLUMN}" if has_columns(conn, "path", EXTERNAL_ROOT_COLUMN) else "''" )lines 171–175join, count = ( ("LEFT JOIN memberdef m ON m.file_id = p.rowid", "COUNT(DISTINCT m.name)") if table_exists(conn, "memberdef") else ("", "0") )lines 176–182rows = conn.execute( f"SELECT p.name, {count}, {owner} FROM path p " # noqa: S608 f"{join} " "WHERE p.type = ? AND p.name <> '' " "GROUP BY p.rowid ORDER BY p.name", (PATH_TYPE_FILE,), ).fetchall()lines 183–187return [ FileEntry(path=name, symbol_count=count, external_root=owner_root or "") for name, count, owner_root in rows if not SYNTHETIC_PATH.match(name) and (pattern is None or _matches(name, pattern)) ]

Requirements

REQ-DDB-QUERY-001

Flows

lookup_class

ClassEntry | None clew.query.corpus.lookup_class(DbSource db, str name, Path|str|None repo_root=None)

Version 5: names the same-name compounds of other kinds it merges with ( merged ).

clew/query/corpus.py:1323

Source · 53 lines
def lookup_class(db: DbSource, name: str, repo_root: Path | str | None = None) -> ClassEntry | None:
    """Resolve a class/struct/union name to its definition, members, and
    immediate hierarchy. Matching is exact-first then substring, and every
    project compound outranks the `std::` compounds doxygen registers against
    its synthetic `[STL]` file — so a bare project name never loses to a
    system-header namesake.

    RETURNS THE REJECTS TOO (gh#315). This function has always fetched every
    substring match and returned exactly one, discarding the rest in a `min()` —
    so a caller asking for `PolygonWidget` in a repo that also defines
    `RoundedPolygonWidget` was told about one class and given no signal that the
    other existed. Every other disambiguating surface here — `resolve_symbol`,
    `dossier`, `chain_trace`, `source` — reports its rejected candidates, and the
    inconsistency was the defect: a silent pick is only safe when the caller can
    tell a pick was made. `candidates` is capped and stays empty when the name is
    unambiguous.

    @brief Look up one class/struct with members, hierarchy and rejected candidates.
    @return ClassEntry or None.
    @version 3
    """
    with connect(db) as conn:
        if not table_exists(conn, "compounddef"):
            return None
        placeholders = ",".join("?" * len(CLASS_KINDS))
        rows = conn.execute(
            "SELECT c.rowid, c.name, c.kind, COALESCE(p.name,''), c.line, c.briefdescription "
            "FROM compounddef c LEFT JOIN path p ON p.rowid = c.file_id "
            f"WHERE c.kind IN ({placeholders}) AND c.name LIKE ?",
            (*CLASS_KINDS, f"%{name}%"),
        ).fetchall()
        if not rows:
            return None
        ranked = sorted(rows, key=lambda r: _class_rank(r, name))
        best = ranked[0]
        bases, derived = _hierarchy(conn, best[0])
        return ClassEntry(
            name=best[1],
            kind=best[2],
            file=best[3],
            line=best[4] or None,
            brief=strip_xml(best[5]),
            members=_members(conn, best[0]),
            bases=bases,
            derived=derived,
            candidates=_compound_candidates(ranked),
            declaration=(
                None if repo_root is None else compound_declaration(conn, best[0], repo_root)
            ),
            merged=_merged(conn, ranked, best, repo_root),
        )

Activity · 11 steps
lines 1344–1344with connect(db) as connlines 1345–1345◇ if not table_exists(conn, "compounddef")lines 1346–1346return Nonelines 1347–1347placeholders = ",".join("?" * len(CLASS_KINDS))lines 1348–1353rows = conn.execute( "SELECT c.rowid, c.name, c.kind, COALESCE(p.name,''), c.line, c.briefdescription " "FROM compounddef c LEFT JOIN path p ON p.rowid = c.file_id " f"WHERE c.kind IN ({placeholders}) AND c.name LIKE ?", (*CLASS_KINDS, f"%{name}%"), ).fetchall()lines 1354–1354◇ if not rowslines 1355–1355return Nonelines 1356–1356ranked = sorted(rows, key=lambda r: _class_rank(r, name))lines 1357–1357best = ranked[0]lines 1358–1358bases, derived = _hierarchy(conn, best[0])lines 1359–1373return ClassEntry( name=best[1], kind=best[2], file=best[3], line=best[4] or None, brief=strip_xml(best[5]), members=_members(conn, best[0]), bases=bases, derived=derived, candidates=_compound_candidates(ranked), declaration=( None if repo_root is None else compound_declaration(conn, best[0], repo_root) ), merged=_merged(conn, ranked, best, repo_root), )

Requirements

REQ-DDB-QUERY-001 REQ-DDB-QUERY-010

member_doc_rows

list[tuple[str, str, str]] clew.query.corpus.member_doc_rows(sqlite3.Connection conn, list[str] tokens, int limit=10)

Member documentation rows matching EVERY token, or [] when unavailable.

clew/query/corpus.py:688

Source · 53 lines
def member_doc_rows(
    conn: sqlite3.Connection, tokens: list[str], limit: int = 10
) -> list[tuple[str, str, str]]:
    """gh#404 — THE PROSE THAT ANSWERS "WHY" AND WAS NEVER SEARCHED. The prose corpus is
    markdown plus FILE-level doc comments. A doc comment attached to a MEMBER — a macro, a
    function, a field — went nowhere, and that is where C libraries put their explanations.

    MEASURED ON MBEDTLS: `search_prose("MBEDTLS_ALLOW_PRIVATE_ACCESS")` returned zero and called
    it definitive, while `memberdef.detaileddescription` held the paragraph "Although structs
    defined in header files are publicly available, their members are private and should not be
    accessed by the user" — which is verbatim the answer to a graded question. The text was
    already stored; nothing needed harvesting. A benchmark cell was told the miss was definitive
    and ran three greps to find what the index was holding.

    A LIKE SCAN, NOT FTS5, for exactly the reason `file_doc_rows` gives one line up: `search`
    promises a conjunction over tokens, and answering half a corpus with bm25 and the other half
    with a conjunction gives one tool two matching semantics depending on which half replied.

    GUARDED ON COLUMNS, not only on the table. The description columns are part of doxygen's
    schema but this repo's own minimal test indexes omit them, and `has_columns` is the
    graceful-degradation contract that keeps a thin database answering thinly rather than raising.

    LIMITED, because unlike `file_docs` this is one row per SYMBOL — mbedtls has 10,652 — and an
    unbounded prose reply is the payload this surface budgets elsewhere.

    @brief Match member documentation against all query tokens.
    @return List of (path, name, documentation) triples.
    @version 1
    """
    if not tokens or not table_exists(conn, "memberdef"):
        return []
    columns = [
        c for c in ("briefdescription", "detaileddescription") if has_columns(conn, "memberdef", c)
    ]
    if not columns:
        return []
    doc = "COALESCE(" + ", ".join(f"NULLIF(m.{c},'')" for c in columns) + ", '')"
    ## The token must appear in the symbol's NAME or in its documentation. Including the name is
    ## what makes `search_prose("MBEDTLS_ALLOW_PRIVATE_ACCESS")` reach the macro whose comment
    ## explains it, since the flag is named in the `#if` and described in the prose beside it.
    term = f"(LOWER(m.name) LIKE ? OR LOWER({doc}) LIKE ?)"
    clause = " AND ".join([term] * len(tokens))
    params: list[str] = []
    for token in tokens:
        params += [f"%{token}%", f"%{token}%"]
    return conn.execute(
        f"SELECT COALESCE(p.name,''), m.name, {doc} FROM memberdef m "  # noqa: S608
        f"LEFT JOIN path p ON p.rowid = m.file_id "
        f"WHERE {clause} AND {doc} != '' ORDER BY LENGTH({doc}) DESC, m.name LIMIT ?",
        [*params, max(1, limit)],
    ).fetchall()

Activity · 12 steps
lines 717–717◇ if not tokens or not table_exists(conn, "memberdef")lines 718–718return []lines 719–721columns = [ c for c in ("briefdescription", "detaileddescription") if has_columns(conn, "memberdef", c) ]lines 722–722◇ if not columnslines 723–723return []lines 724–724doc = "COALESCE(" + ", ".join(f"NULLIF(m.{c},'')" for c in columns) + ", '')"lines 728–728term = f"(LOWER(m.name) LIKE ? OR LOWER({doc}) LIKE ?)"lines 729–729clause = " AND ".join([term] * len(tokens))lines 730–730params: list[str] = []lines 731–731◇ for token in tokenslines 732–732params += [f"%{token}%", f"%{token}%"]lines 733–738return conn.execute( f"SELECT COALESCE(p.name,''), m.name, {doc} FROM memberdef m " # noqa: S608 f"LEFT JOIN path p ON p.rowid = m.file_id " f"WHERE {clause} AND {doc} != '' ORDER BY LENGTH({doc}) DESC, m.name LIMIT ?", [*params, max(1, limit)], ).fetchall()

Requirements

REQ-DDB-QUERY-007

Flows

rollup_meaning

str clew.query.corpus.rollup_meaning(int indexed, int shown, int total)

Say what the per-directory counts are, and what they are NOT.

clew/query/corpus.py:1420

Source · 47 lines
def rollup_meaning(indexed: int, shown: int, total: int) -> str:
    """THE COUNT IS OF INDEXED FILES AND A READER WILL TAKE IT FOR THE DIRECTORY'S SIZE. On
    mbedtls those differ enough to invert the answer: `tests/` holds 310 tracked files and 44
    indexed ones, because most are `.function` / `.data` fixtures no grammar handles, so the
    largest directory HERE is `library` (174) while the largest in the REPOSITORY is `tests`.
    A rollup offering the first as the second would argue for a wrong answer — the same class as
    the two false-count rosters and the config payload, and the reason this sentence is not
    optional.

    So it says what was counted, that files a grammar does not handle are absent, and where to
    settle a question about the repository itself.

    @brief Explain what the directory rollup counts.
    @return The sentence, or "" when nothing was indexed.
    @version 1
    """
    if not indexed:
        return ""
    parts = [
        f"{indexed} INDEXED file(s) across {total} top-level directory(ies). These are files this "
        "index HOLDS, not a census of the tree: a file whose extension no grammar handles is not "
        "indexed at all, so a directory can be large in the repository and small here."
    ]
    if shown < total:
        parts.append(f"Only the {shown} largest are listed; {total - shown} more are not shown.")
    parts.append(
        "So 'the largest directory in this index' and 'the largest directory in the repository' "
        "are different questions, and this answers only the first. For the second, count the "
        "tree. Pass a glob as `text` (e.g. `tests/*`) to list the indexed files themselves."
    )
    ## AND IT SAYS WHY IT DISAGREES WITH THE OTHER FILE COUNT IN THIS TOOL, without claiming an
    ## arithmetic it does not have. `coverage.indexed_files` is 443 where this is 527 on mbedtls,
    ## and two same-sounding figures differing for no stated reason is how a reader concludes one is
    ## wrong. It is NOT a single subtraction: coverage counts first-party RESOLVED files and also
    ## drops prose and documentation, and those categories OVERLAP — I wrote the subtraction two
    ## ways (527-41, then 527-41-259) and neither reconciled, which is exactly why this states the
    ## definitions rather than a sum.
    parts.append(
        "This counts every file row the index holds, so it is LARGER than "
        "`coverage.indexed_files`, which is a narrower set: first-party, resolved, and excluding "
        "prose and documentation. The two figures differ by construction and the difference is "
        "not one subtraction — `unresolved_files` and `external_files` below are contributors, "
        "not the whole of it."
    )
    return " ".join(parts)

Activity · 8 steps
lines 1436–1436◇ if not indexedlines 1437–1437return ""lines 1438–1442parts = [ f"{indexed} INDEXED file(s) across {total} top-level directory(ies). These are files this " "index HOLDS, not a census of the tree: a file whose extension no grammar handles is not " "indexed at all, so a directory can be large in the repository and small here." ]lines 1443–1443◇ if shown < totallines 1444–1444parts.append(f"Only the {shown} largest are listed; {total - shown} more are not shown.")lines 1445–1449parts.append( "So 'the largest directory in this index' and 'the largest directory in the repository' " "are different questions, and this answers only the first. For the second, count the " "tree. Pass a glob as `text` (e.g. `tests/*`) to list the indexed files themselves." )lines 1457–1463parts.append( "This counts every file row the index holds, so it is LARGER than " "`coverage.indexed_files`, which is a narrower set: first-party, resolved, and excluding " "prose and documentation. The two figures differ by construction and the difference is " "not one subtraction — `unresolved_files` and `external_files` below are contributors, " "not the whole of it." )lines 1464–1464return " ".join(parts)

Requirements

REQ-DDB-QUERY-002

Flows

search_prose

list[ProseHit] clew.query.corpus.search_prose(DbSource db, str text, int limit=10)

Full-text search over the ingested supplementary prose.

clew/query/corpus.py:1050

Source · 18 lines
def search_prose(db: DbSource, text: str, limit: int = 10) -> list[ProseHit]:
    """Search the markdown corpus ingested into the `supplementary_docs`
    FTS5 table, returning a `snippet()` around each match. Older databases
    predate the corpus — the absent table yields an empty list, not an error.

    KEPT AS THE LIST-RETURNING API because it is the published R2 signature and a dozen
    call sites read it as a plain sequence. It now delegates to `search_prose_graded`, so
    it inherits the AND→OR widening; what it cannot carry is `widened`, which is why the
    MCP layer calls the graded form and this one stays for library callers who only want
    rows.

    @brief Search supplementary prose, returning snippets.
    @return List of ProseHit.
    @version 2
    """
    return search_prose_graded(db, text, limit=limit).hits

Activity · 1 steps
lines 1065–1065return search_prose_graded(db, text, limit=limit).hits

Requirements

REQ-DDB-QUERY-001

search_prose_graded

ProseSearch clew.query.corpus.search_prose_graded(DbSource db, str text, int limit=10)

Full-text search over the ingested prose, widening to OR when the AND is empty.

clew/query/corpus.py:983

Source · 60 lines
def search_prose_graded(db: DbSource, text: str, limit: int = 10) -> ProseSearch:
    """THE DEFECT THIS FIXES, MEASURED ON MBEDTLS. FTS5 joins a bare token list with an
    implicit AND, so a phrase is only found when the author used every one of the reader's
    words. `private accessor` returns `docs/3.0-migration-guide.md`; `private members
    accessor` returns NOTHING, because that document says "fields". Both describe the same
    section. A graded agent tried five such phrasings in one cell, was told each empty
    result was definitive, and fell back to `Read`, `Glob` and `grep` on the very file the
    corpus already held.

    THE WIDENING IS STRICTLY A LAST RESORT — only when the AND returns ZERO, and only when
    more than one token could have emptied it. A partial result is left alone: widening a
    query that already found something would bury the exact hits under loose ones, which is
    the opposite failure and just as hard to see. bm25 (`ORDER BY rank`) then puts the
    documents matching the most, and rarest, terms first, so the OR degrades gracefully
    rather than returning the corpus.

    THE CALLER IS TOLD. `widened` is returned, not hidden, because "these matched SOME of
    your terms" is a weaker claim than "these matched all of them" and a reader who cannot
    tell the two apart has traded a false negative for a false positive.

    @brief Search prose, falling back from AND to OR and reporting which answered.
    @return Hits plus the matching mode.
    @version 2
    """
    tokens = _query_tokens(text)
    with connect(db) as conn:
        rows: list[tuple] = []
        widened = False
        if table_exists(conn, "supplementary_docs"):
            rows = _fts_match(conn, text, max(1, limit))
            if not rows and len(tokens) > 1:
                widened = True
                rows = _fts_match(conn, " OR ".join(f'"{t}"' for t in tokens), max(1, limit))
        ## THE THIRD SOURCE (gh#404), and it is not a fallback — it is searched whenever the
        ## markdown half leaves room, because a member's doc comment is prose that happens to
        ## live in a `.c` file. Appended AFTER the FTS rows rather than interleaved: bm25 ranks
        ## the markdown half against itself and a LIKE match carries no comparable score, so
        ## merging them by a fabricated rank would assert an ordering neither half computed.
        ## STRIPPED, because doxygen stores these columns as XML. The first live check returned
        ## `<para>Allow library to access its structs' private members.</para>` — tags a reader pays
        ## for and cannot use. `strip_xml` is the same helper every other description path uses.
        members = [
            (path, f"{name} — member documentation", strip_xml(doc))
            for path, name, doc in member_doc_rows(conn, list(tokens), max(1, limit))
        ]
    seen = {(row[0], row[1]) for row in rows}
    rows = [*rows, *(m for m in members if (m[0], m[1]) not in seen)][: max(1, limit)]
    return ProseSearch(
        hits=[
            ProseHit(file_path=file_path, heading=heading or "", snippet=_collapse(snip))
            for file_path, heading, snip in rows
        ],
        ## `widened` describes the MARKDOWN query only, and stays false when the markdown half
        ## found nothing but a member doc answered: nothing was relaxed in that case, so
        ## reporting a relaxation would be a disclosure of something that did not happen.
        widened=widened and bool(rows),
        tokens=tokens,
    )

Activity · 13 steps
lines 1007–1007tokens = _query_tokens(text)lines 1008–1008with connect(db) as connlines 1009–1009rows: list[tuple] = []lines 1010–1010widened = Falselines 1011–1011◇ if table_exists(conn, "supplementary_docs")lines 1012–1012rows = _fts_match(conn, text, max(1, limit))lines 1013–1013◇ if not rows and len(tokens) > 1lines 1014–1014widened = Truelines 1015–1015rows = _fts_match(conn, " OR ".join(f'"{t}"' for t in tokens), max(1, limit))lines 1024–1027members = [ (path, f"{name} — member documentation", strip_xml(doc)) for path, name, doc in member_doc_rows(conn, list(tokens), max(1, limit)) ]lines 1028–1028seen = {(row[0], row[1]) for row in rows}lines 1029–1029rows = [*rows, *(m for m in members if (m[0], m[1]) not in seen)][: max(1, limit)]lines 1030–1040return ProseSearch( hits=[ ProseHit(file_path=file_path, heading=heading or "", snippet=_collapse(snip)) for file_path, heading, snip in rows ], ## `widened` describes the MARKDOWN query only, and stays false when the markdown half ## found nothing but a member doc answered: nothing was relaxed in that case, so ## reporting a relaxation would be a disclosure of something that did not happen. widened=widened and bool(rows), tokens=tokens, )

Requirements

REQ-DDB-QUERY-001

Flows

undocumented_path_rows

list[tuple[str, str]] clew.query.corpus.undocumented_path_rows(sqlite3.Connection conn, list[str] tokens)

Registered paths matching EVERY token that carry no file-level documentation.

clew/query/corpus.py:636

Source · 45 lines
def undocumented_path_rows(conn: sqlite3.Connection, tokens: list[str]) -> list[tuple[str, str]]:
    """THE OTHER HALF OF `file_doc_rows`, and the half a C5-registered file falls into.

    `symbols._file_candidates` built the default corpus's file rows from `file_doc_rows` alone, so
    only a DOCUMENTED file could appear there. A file the index knows by name and harvested
    nothing from has no `file_docs` row by construction — which is exactly the class C5 exists to
    make nameable, so registration reached `corpus="files"` and not the corpus a reader tries
    first. Measured on an index rebuilt with C5: of the three ways the 1.1.0 agent asked for
    `generate_errors`, only `corpus="files"` answered.

    DOCUMENTED FILES ARE EXCLUDED HERE rather than merged, so the two readers cannot both emit a
    row for one path and double it in the reply. `file_doc_rows` keeps the documented ones and
    this adds only what it cannot see.

    THE DOCUMENTATION IS `""` AND THAT IS A MEASUREMENT: the file was registered and nothing was
    harvested from it. `_search_rank` scores a path where it scores a symbol's name and
    documentation where it scores a brief, so a bare path match is ranked below a documentation
    match by the same table rather than by a rule written here.

    @brief Match registered paths with no documentation against all query tokens.
    @return List of (path, "") pairs.
    @version 1
    """
    if not tokens or not table_exists(conn, "path"):
        return []
    where, params = ["p.name <> ''"], []
    if has_columns(conn, "path", "type"):
        where.append("p.type = ?")
        params.append(PATH_TYPE_FILE)
    for token in tokens:
        where.append("LOWER(p.name) LIKE ?")
        params.append(f"%{token}%")
    documented = (
        "AND NOT EXISTS (SELECT 1 FROM file_docs d WHERE d.file_path = p.name)"
        if table_exists(conn, "file_docs")
        else ""
    )
    rows = conn.execute(
        f"SELECT p.name FROM path p WHERE {' AND '.join(where)} {documented} "  # noqa: S608
        f"ORDER BY p.name",
        params,
    ).fetchall()
    return [(name, "") for (name,) in rows if not SYNTHETIC_PATH.match(name)]

Activity · 12 steps
lines 659–659◇ if not tokens or not table_exists(conn, "path")lines 660–660return []lines 661–661where, params = ["p.name <> ''"], []lines 662–662◇ if has_columns(conn, "path", "type")lines 663–663where.append("p.type = ?")lines 664–664params.append(PATH_TYPE_FILE)lines 665–665◇ for token in tokenslines 666–666where.append("LOWER(p.name) LIKE ?")lines 667–667params.append(f"%{token}%")lines 668–672documented = ( "AND NOT EXISTS (SELECT 1 FROM file_docs d WHERE d.file_path = p.name)" if table_exists(conn, "file_docs") else "" )lines 673–677rows = conn.execute( f"SELECT p.name FROM path p WHERE {' AND '.join(where)} {documented} " # noqa: S608 f"ORDER BY p.name", params, ).fetchall()lines 678–678return [(name, "") for (name,) in rows if not SYNTHETIC_PATH.match(name)]

Requirements

REQ-DDB-QUERY-007

Flows