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.

clew/prose.py:371

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
lines 389–389found: list[Path] = []lines 390–390seen: set[Path] = set()lines 391–391◇ for pattern in patternslines 392–392◇ for path in sorted(repo_root.glob(pattern))lines 393–393◇ if path not in seenlines 394–394seen.add(path)lines 395–395found.append(path)lines 396–396◇ for rel in sorted(files or ())lines 397–397◇ if not rel.lower().endswith(PROSE_EXTS)lines 398–398continuelines 399–399path = repo_root / rellines 400–400◇ if path not in seenlines 401–401seen.add(path)lines 402–402found.append(path)lines 403–403return found

Requirements

REQ-DDB-PIPE-001

chunk_markdown

list[tuple[str, str]] clew.prose.chunk_markdown(str text, str file_path)

Split markdown into sections by heading.

clew/prose.py:68

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
lines 84–84from lang_parsing_substrate import markdown_sectionslines 86–86data = text.encode("utf-8")lines 87–87heads = [s for s in markdown_sections(text) if 1 <= s.level <= _MAX_CHUNK_LEVEL]lines 89–89spans = [(Path(file_path).name, 0, heads[0].start_byte if heads else len(data))]lines 90–90◇ for i, head in enumerate(heads)lines 91–91end = heads[i + 1].start_byte if i + 1 < len(heads) else len(data)lines 92–92spans.append((head.heading_text.strip(), head.heading_end_byte, end))lines 94–94chunks: list[tuple[str, str]] = []lines 95–95◇ for heading, start, end in spanslines 96–96content = data[start:end].decode("utf-8").strip()lines 97–97◇ if contentlines 98–98chunks.append((heading, content))lines 99–99return chunks

Requirements

REQ-DDB-PIPE-001

chunk_rst

list[tuple[str, str]] clew.prose.chunk_rst(str text, str file_path)

Split reStructuredText into sections by title.

clew/prose.py:133

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
lines 153–153from .substrate import has_languagelines 155–155name = Path(file_path).namelines 156–156◇ if not has_language(_RST_KEY)lines 157–157whole = text.strip()lines 158–158return [(name, whole)] if whole else []lines 159–159from .tsnode import Parserlines 161–161data = text.encode("utf-8")lines 162–162root = Parser(_RST_KEY).parse(data).root_nodelines 163–163heads = [s for s, level in _rst_levels(root) if level <= _MAX_CHUNK_LEVEL]lines 164–164starts = [_labelled_start(s) for s in heads]lines 165–165chunks = [(name, _span_text(data, 0, starts[0] if heads else len(data)))]lines 166–166◇ for i, section in enumerate(heads)lines 167–167end = starts[i + 1] if i + 1 < len(heads) else len(data)lines 168–168labels = _span_text(data, starts[i], section.start_byte)lines 169–169body = _span_text(data, _heading_end(section), end)lines 170–170chunks.append((_rst_title(section), "\n\n".join(p for p in (labels, body) if p)))lines 171–171return [(heading, content) for heading, content in chunks if content]

Requirements

REQ-DDB-PIPE-001

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.

clew/prose.py:410

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_chunks

1 more lines, not shown

Activity · 23 steps
lines 426–426◇ if patterns is Nonelines 427–427patterns = SUPPLEMENTARY_PATTERNSlines 429–429conn = sqlite3.connect(str(db_path))lines 430–435conn.execute( """ CREATE VIRTUAL TABLE IF NOT EXISTS supplementary_docs USING fts5(file_path, heading, content) """, )lines 436–436conn.execute("DELETE FROM supplementary_docs")lines 437–437conn.commit()lines 439–439total_chunks = 0lines 440–440seen_files: set[str] = set()lines 442–442resolved: dict[str, str] = {}lines 443–443◇ for file_path in _candidate_docs(repo_root, patterns, files)lines 444–444◇ if not file_path.is_file()lines 445–445continuelines 451–453◇ if (lines 455–455continuelines 456–456rel_path = str(file_path.relative_to(repo_root))lines 457–457◇ if rel_path in seen_fileslines 458–458continuelines 459–459seen_files.add(rel_path)lines 460–460total_chunks += _ingest_one_doc_file(conn, file_path, rel_path, cache)lines 462–462conn.commit()lines 463–463conn.close()lines 464–468logger.info( "Ingested %d chunks from %d supplementary files", total_chunks, len(seen_files), )lines 469–469return total_chunks

Requirements

REQ-DDB-PIPE-001