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).
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
Flows
_extensions
tuple[str, ...] clew.query.corpus._extensions(list[str] paths)
Distinct dot-prefixed extensions of a path list.
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
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.
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
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 .
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
Requirements
_indexed_paths
list[str] clew.query.corpus._indexed_paths(sqlite3.Connection conn)
Every indexed, non-synthetic file path.
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
Flows
_matches
bool clew.query.corpus._matches(str path, str pattern)
Whether a repo-relative path matches a * -glob pattern.
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
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.
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
Requirements
Flows
_query_tokens
tuple[str, ...] clew.query.corpus._query_tokens(str text)
The query's tokens, stripped of FTS5 operator syntax.
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
Flows
_scope_provenance
dict[str, str] clew.query.corpus._scope_provenance(sqlite3.Connection conn)
The scope.
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
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.
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
Requirements
Flows
directory_rollup
DirectoryInventory clew.query.corpus.directory_rollup(DbSource db)
The indexed file set rolled up by top-level directory.
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
Requirements
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.
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
Requirements
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.
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
Requirements
Flows
file_license
LicenseRef | None clew.query.corpus.file_license(sqlite3.Connection conn, str name)
The SPDX licence one file declares.
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
Requirements
file_owners
tuple[OwnerRef, ...] | None clew.query.corpus.file_owners(sqlite3.Connection conn, str name)
Who owns one file, from the ownership layer.
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
Requirements
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.
Called by none
Tested by 7 tests
test_a_generated_file_says_so, test_a_hand_written_file_has_no_generated_by, test_long_file_documentation_is_capped_with_an_explicit_notice, test_the_file_probe_degrades_on_a_minimal_path_table, test_the_generator_lists_what_it_produces, test_the_inputs_are_listed_and_a_variable_stays_unresolved, test_the_registered_file_answers_as_a_file_subject
Calls _file_documentation, _file_members, _include_graph, _one_file_clause, _was_harvested, file_license, file_owners, generates_files, generation_rule, has_columns, is_indexed_file
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
Requirements
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.
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
Requirements
Flows
generates_files
tuple[str, ...] clew.query.corpus.generates_files(sqlite3.Connection conn, str name)
The files this file produces, by basename.
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
Requirements
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.
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
Requirements
has_file_docs
bool clew.query.corpus.has_file_docs(DbSource db)
Whether this index carries a file-level documentation corpus at all.
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
Requirements
Flows
has_prose_corpus
bool clew.query.corpus.has_prose_corpus(DbSource db)
Whether this index carries an ingested markdown corpus at all.
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
Requirements
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.
Called by search_emptiness
Tested by
Calls _extensions, _indexed_paths, _not_indexed, _scope_provenance, connect
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
Requirements
Flows
indexed_extensions
tuple[str, ...] clew.query.corpus.indexed_extensions(DbSource db)
Every file extension present in the indexed set, uncapped.
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
Requirements
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.
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
Requirements
list_files
list[FileEntry] clew.query.corpus.list_files(DbSource db, str|None pattern=None)
The indexed source files, with documented-symbol counts.
Called by _files_corpus
Tested by 8 tests
test_a_bare_term_finds_the_files_containing_it, test_a_shared_path_prefix_does_not_misattribute_a_sibling_tree, test_a_term_that_matches_nothing_still_returns_nothing, test_an_explicit_glob_is_unchanged, test_list_files_inventory, test_list_files_pattern_is_a_glob_over_path_or_filename, test_list_files_returns_external_files_annotated_not_filtered, test_the_registered_file_answers_as_a_file_subject
Calls _matches, connect, has_columns, table_exists
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
Requirements
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 ).
Called by none
Tested by 11 tests
test_a_merged_interface_and_class_are_both_candidates, test_lookup_class_lists_candidates_when_the_name_is_ambiguous, test_lookup_class_members_and_hierarchy, test_lookup_class_members_carry_their_documentation, test_lookup_class_members_degrade_when_the_description_columns_are_absent, test_lookup_class_prefers_project_over_std, test_lookup_class_std_is_still_reachable, test_lookup_class_unambiguous_name_has_no_candidates, test_lookup_class_unknown_is_none, test_search_excludes_stl_compounds_but_lookup_class_still_reaches_them, test_the_class_subject_matches_the_r2_library
Calls _class_rank, _compound_candidates, _hierarchy, _members, _merged, compound_declaration, connect, strip_xml, table_exists
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
Requirements
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.
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
Requirements
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.
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
Requirements
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.
Called by none
Tested by 8 tests
test_a_limitation_documented_only_in_help_is_searchable, test_kconfig_prose_must_be_ingested_after_the_markdown_ingest, test_prompt_and_symbol_name_both_reach_the_prose_corpus, test_search_prose_absent_table_is_empty, test_search_prose_limit_and_bad_expression, test_search_prose_returns_a_snippet, test_search_prose_widens_to_or_when_one_absent_word_empties_the_and, test_the_class_subject_matches_the_r2_library
Calls search_prose_graded
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
Requirements
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.
Called by _prose_corpus, search_prose
Tested by 5 tests
test_prose_search_reaches_documentation_attached_to_a_member, test_search_prose_does_not_widen_a_query_that_already_matched, test_search_prose_punctuation_only_tokens_never_reach_fts5, test_search_prose_single_token_miss_reports_no_widening, test_search_prose_widens_to_or_when_one_absent_word_empties_the_and
Calls _collapse, _fts_match, _query_tokens, connect, list, member_doc_rows, strip_xml, table_exists
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
Requirements
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.
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)]