prose.py¶
clew/prose.py
Supplementary-doc ingestion: every markdown and reStructuredText file the build scanned → FTS5.
_candidate_docs
list[Path] clew.prose._candidate_docs(Path repo_root, list[str] patterns, list[str]|None files)
The scanned set now contributes reStructuredText as well as markdown.
Source · 35 lines
def _candidate_docs(
repo_root: Path,
patterns: list[str],
files: list[str] | None,
) -> list[Path]:
"""WHY THE SCANNED SET RATHER THAN A WIDER GLOB. `**/*.md` from the repo root reads
every vendored and build-output markdown file on disk — `node_modules`, a cargo
registry copy, `.venv/share/doc`. The scanned set is the build's own answer to what is
in scope: it already honours the declared scope, the operator's excludes, the
toolchain's ignores and binary classification. Taking markdown from it means prose
coverage and symbol coverage cannot disagree about what this repository contains.
The globs are still read. They name `README` with no extension, `README.rst` and
`README.txt` — prose that no markdown rule would find.
@brief The ordered candidate set.
@return Paths, deduplicated, globs first.
"""
found: list[Path] = []
seen: set[Path] = set()
for pattern in patterns:
for path in sorted(repo_root.glob(pattern)):
if path not in seen:
seen.add(path)
found.append(path)
for rel in sorted(files or ()):
if not rel.lower().endswith(PROSE_EXTS):
continue
path = repo_root / rel
if path not in seen:
seen.add(path)
found.append(path)
return found
Activity · 15 steps
Requirements
chunk_markdown
list[tuple[str, str]] clew.prose.chunk_markdown(str text, str file_path)
Split markdown into sections by heading.
Called by none
Tested by
Calls none
Source · 34 lines
def chunk_markdown(text: str, file_path: str) -> list[tuple[str, str]]:
"""Split markdown into sections by heading.
Each chunk is a (heading, content) pair. Content between the start
of the file and the first heading uses the filename as the heading,
and includes any front matter. Headings of level 1-3 trigger splits;
deeper headings stay inside their section.
THE HEADINGS ARE THE GRAMMAR'S, NOT A REGEX'S. lang-parsing-substrate's
`markdown_sections` parses the file, so a `#` line inside a code fence
(a shell comment, a C preprocessor line) no longer splits a section,
and setext headings (`Title` over `=====`) now do.
@brief Chunk a markdown file by heading into (heading, content) pairs.
@version 3
"""
from lang_parsing_substrate import markdown_sections
data = text.encode("utf-8")
heads = [s for s in markdown_sections(text) if 1 <= s.level <= _MAX_CHUNK_LEVEL]
## (heading, body start byte, body end byte); each body runs to the next split heading.
spans = [(Path(file_path).name, 0, heads[0].start_byte if heads else len(data))]
for i, head in enumerate(heads):
end = heads[i + 1].start_byte if i + 1 < len(heads) else len(data)
spans.append((head.heading_text.strip(), head.heading_end_byte, end))
chunks: list[tuple[str, str]] = []
for heading, start, end in spans:
content = data[start:end].decode("utf-8").strip()
if content:
chunks.append((heading, content))
return chunks
Activity · 13 steps
Requirements
chunk_rst
list[tuple[str, str]] clew.prose.chunk_rst(str text, str file_path)
Split reStructuredText into sections by title.
Called by _headings
Tested by 7 tests
test_a_named_target_opens_the_section_it_labels, test_a_target_with_a_link_stays_with_the_paragraph_it_serves, test_a_title_shaped_line_inside_a_literal_block_does_not_split, test_an_anonymous_target_stays_with_the_paragraph_it_serves, test_content_before_the_first_title_is_headed_by_the_file_name, test_levels_follow_the_order_styles_first_appear, test_without_the_grammar_the_file_is_one_chunk
Calls _heading_end, _labelled_start, _rst_levels, _rst_title, _span_text, has_language
Source · 41 lines
def chunk_rst(text: str, file_path: str) -> list[tuple[str, str]]:
"""THE SAME SHAPE AS `chunk_markdown`, so the corpus reads one way whatever wrote it:
the content before the first title is headed by the file name, levels 1-3 split, a
deeper section stays inside its parent's chunk, and an empty section is dropped.
A LEVEL IS AN ORDER OF APPEARANCE, NOT A CHARACTER. reStructuredText has no fixed
`=`-is-level-1 rule: docutils gives each adornment style a level in the order the
document first uses it, and a title with an overline is a different style from one
underlined with the same character. `_rst_levels` applies that rule.
AN EXPLICIT TARGET BELONGS TO THE SECTION IT LABELS. `.. _install:` directly above a
title is how `:ref:` reaches that section, so the target opens the section's chunk
rather than closing the previous one, and a search for the label lands on the text it
names.
WITHOUT THE GRAMMAR (a substrate built without `lang-rst`) the file is one chunk under
its name: still searchable, and never split by a guess at what a title looks like.
@brief Chunk a reStructuredText file by section title into (heading, content) pairs.
"""
from .substrate import has_language
name = Path(file_path).name
if not has_language(_RST_KEY):
whole = text.strip()
return [(name, whole)] if whole else []
from .tsnode import Parser
data = text.encode("utf-8")
root = Parser(_RST_KEY).parse(data).root_node
heads = [s for s, level in _rst_levels(root) if level <= _MAX_CHUNK_LEVEL]
starts = [_labelled_start(s) for s in heads]
chunks = [(name, _span_text(data, 0, starts[0] if heads else len(data)))]
for i, section in enumerate(heads):
end = starts[i + 1] if i + 1 < len(heads) else len(data)
labels = _span_text(data, starts[i], section.start_byte)
body = _span_text(data, _heading_end(section), end)
chunks.append((_rst_title(section), "\n\n".join(p for p in (labels, body) if p)))
return [(heading, content) for heading, content in chunks if content]
Activity · 17 steps
Requirements
ingest_supplementary_docs
int clew.prose.ingest_supplementary_docs(Path db_path, Path repo_root, list[str]|None patterns=None, list[str]|None files=None, IndexCache|None cache=None)
Scan repo for markdown/text docs, chunk by heading, insert into FTS5.
Called by _build_stages, run_real_stages
Tested by 10 tests
test_a_file_both_a_glob_and_the_scan_name_is_ingested_once, test_a_limitation_documented_only_in_help_is_searchable, test_a_markdown_file_the_old_globs_never_named_is_ingested, test_a_scanned_rst_file_is_ingested_as_prose, test_a_symlinked_doc_outside_the_repository_is_not_ingested, test_kconfig_prose_must_be_ingested_after_the_markdown_ingest, test_markdown_outside_the_scanned_set_is_not_ingested, test_readme_rst_is_split_by_the_rst_grammar_not_markdown, test_the_dotmarkdown_spelling_counts, test_the_named_globs_still_hold_when_no_file_set_is_given
Calls _candidate_docs, _ingest_one_doc_file, within_repo
Source · 60 lines
def ingest_supplementary_docs(
db_path: Path,
repo_root: Path,
patterns: list[str] | None = None,
files: list[str] | None = None,
cache: IndexCache | None = None,
) -> int:
"""Scan repo for markdown/text docs, chunk by heading, insert into FTS5.
Recreates the supplementary_docs FTS5 virtual table on every run
so the result is idempotent. Skip-list dedupes files matched by
multiple patterns (e.g. README.md AND docs/**/*.md).
@brief Scan a repo for supplementary docs and insert into FTS5 table.
@version 3
"""
if patterns is None:
patterns = SUPPLEMENTARY_PATTERNS
conn = sqlite3.connect(str(db_path))
conn.execute(
"""
CREATE VIRTUAL TABLE IF NOT EXISTS supplementary_docs
USING fts5(file_path, heading, content)
""",
)
conn.execute("DELETE FROM supplementary_docs")
conn.commit()
total_chunks = 0
seen_files: set[str] = set()
## One resolution memo for this loop (see `within_repo`): the root and each directory once.
resolved: dict[str, str] = {}
for file_path in _candidate_docs(repo_root, patterns, files):
if not file_path.is_file():
continue
## `glob` FOLLOWS SYMLINKS and git tracks them, so a committed
## `README.md -> /proc/self/environ` was read, chunked, and served as this
## repository's prose under an in-repo path (1.1.0 audit, H2). The relative path is
## taken from the UNRESOLVED entry on purpose: it is what the index calls the file,
## and only files that survive the check get that far.
if (
within_repo(file_path, repo_root, setting="supplementary document", memo=resolved)
is None
):
continue
rel_path = str(file_path.relative_to(repo_root))
if rel_path in seen_files:
continue
seen_files.add(rel_path)
total_chunks += _ingest_one_doc_file(conn, file_path, rel_path, cache)
conn.commit()
conn.close()
logger.info(
"Ingested %d chunks from %d supplementary files",
total_chunks,
len(seen_files),
)
return total_chunks1 more lines, not shown