render.py

clew/propose/render.py

Render a Proposal as a `.clew.yaml` draft a human can audit.

_checked

list[str] clew.propose.render._checked(Mapping[str, Any] checked)

The checked counters as one wrapped line.

clew/propose/render.py:300

Source · 8 lines
def _checked(checked: Mapping[str, Any]) -> list[str]:
    """@brief Render what a detector examined, so an empty result stays legible."""
    if not checked:
        return []
    body = ", ".join(f"{key}={value}" for key, value in checked.items())
    return _wrap(body, "#  CHECKED: ", "#           ")

Activity · 4 steps
lines 302–302◇ if not checkedlines 303–303return []lines 304–304body = ", ".join(f"{key}={value}" for key, value in checked.items())lines 305–305return _wrap(body, "# CHECKED: ", "# ")

Flows

_db_line

str clew.propose.render._db_line(Mapping[str, Any] db_status)

One-line description of the index the proposal was measured against.

clew/propose/render.py:224

Show on the map →

Called by _header

Calls none

Source · 27 lines
def _db_line(db_status: Mapping[str, Any]) -> str:
    """A missing index is stated rather than implied: it is the reason a gated
    section refuses to propose, and a reader who does not see it will read the
    refusal as "clew found nothing".

    @brief Describe the measuring index and its freshness.
    @version 2
    """
    if not db_status.get("usable"):
        return (
            "NO USABLE INDEX — nothing was measured, so every dry-run-gated section "
            "refuses to propose. Build the index and re-run."
            + (
                f"  [{db_status['path']} was REJECTED: it {db_status.get('defect')}]"
                if db_status.get("exists")
                else ""
            )
        )
    line = f"{db_status['path']} (build version {db_status.get('build_version')})"
    if db_status.get("stale"):
        line += (
            f"   [STALE: current pipeline is version "
            f"{db_status.get('expected_build_version')} — rebuild for exact numbers]"
        )
    return line

Activity · 6 steps
lines 232–232◇ if not db_status.get("usable")lines 233–241return ( "NO USABLE INDEX — nothing was measured, so every dry-run-gated section " "refuses to propose. Build the index and re-run." + ( f" [{db_status['path']} was REJECTED: it {db_status.get('defect')}]" if db_status.get("exists") else "" ) )lines 242–242line = f"{db_status['path']} (build version {db_status.get('build_version')})"lines 243–243◇ if db_status.get("stale")lines 244–247line += ( f" [STALE: current pipeline is version " f"{db_status.get('expected_build_version')} — rebuild for exact numbers]" )lines 248–248return line

Flows

_entries

list[str] clew.propose.render._entries(Sequence[Entry] entries)

The evidence for every accepted entry, numbered.

clew/propose/render.py:313

Source · 16 lines
def _entries(entries: Sequence[Entry]) -> list[str]:
    """Numbered and printed BEFORE the YAML block because the block is a single
    merged section — an owner activating it is activating all of them, and needs
    to have read each one's derivation first.

    @brief Render each accepted entry's evidence.
    @version 1
    """
    lines: list[str] = []
    for index, entry in enumerate(entries, start=1):
        lines.append(f"#  ── EVIDENCE {index} of {len(entries)} " + "─" * 20)
        lines.extend(f"#     {line}" for line in entry.evidence)
        lines.append("#")
    return lines

Activity · 6 steps
lines 321–321lines: list[str] = []lines 322–322◇ for index, entry in enumerate(entries, start=1)lines 323–323lines.append(f"# ── EVIDENCE {index} of {len(entries)} " + "─" * 20)lines 324–324lines.extend(f"# {line}" for line in entry.evidence)lines 325–325lines.append("#")lines 326–326return lines

Flows

_header

list[str] clew.propose.render._header(Path repo_root, Mapping[str, Any] db_status, Mapping[str, Any] scope)

The document header: what this is, what it was measured against.

clew/propose/render.py:180

Source · 18 lines
def _header(repo_root: Path, db_status: Mapping[str, Any], scope: Mapping[str, Any]) -> list[str]:
    """@brief Render the draft's provenance header and its two contracts."""
    return [
        _TOP,
        "#  .clew.yaml — PROPOSED starter declaration (a DRAFT, not a config)",
        "#",
        f"#    repo:        {repo_root}",
        f"#    index scope: {_scope_line(scope)}",
        f"#    measured vs: {_db_line(db_status)}",
        "#",
        *_wrap(_CONTRACT, "#  "),
        "#",
        *_wrap(_ACTIVATE, "#  "),
        _TOP,
        "",
    ]

Activity · 1 steps
lines 182–195return [ _TOP, "# .clew.yaml — PROPOSED starter declaration (a DRAFT, not a config)", "#", f"# repo: {repo_root}", f"# index scope: {_scope_line(scope)}", f"# measured vs: {_db_line(db_status)}", "#", *_wrap(_CONTRACT, "# "), "#", *_wrap(_ACTIVATE, "# "), _TOP, "", ]

Flows

_notes

list[str] clew.propose.render._notes(Sequence[str] notes)

A section's free-standing notes, wrapped.

clew/propose/render.py:382

Source · 10 lines
def _notes(notes: Sequence[str]) -> list[str]:
    """@brief Render the section-level notes (NOT-DETECTED prose, conflicts)."""
    if not notes:
        return []
    lines = ["#  ── NOTES " + "─" * 30]
    for note in notes:
        lines.extend(_wrap(note, "#     ", "#     "))
    return lines

Activity · 6 steps
lines 384–384◇ if not noteslines 385–385return []lines 386–386lines = ["# ── NOTES " + "─" * 30]lines 387–387◇ for note in noteslines 388–388lines.extend(_wrap(note, "# ", "# "))lines 389–389return lines

Flows

_rejections

list[str] clew.propose.render._rejections(Sequence[Rejection] rejections)

Every refused candidate, with its reason and evidence.

clew/propose/render.py:357

Source · 20 lines
def _rejections(rejections: Sequence[Rejection]) -> list[str]:
    """Part of the deliverable, not debug output. A candidate an owner EXPECTED to
    see is the one they will go looking for, and the refusal reason is the answer
    to "why not mine?" — without it the only available conclusion is that clew
    missed it.

    @brief Render the refused candidates.
    @version 2
    """
    if not rejections:
        return []
    lines = [f"#  ── REJECTED — {len(rejections)} candidate(s) considered and REFUSED " + "─" * 6]
    for index, item in enumerate(rejections, start=1):
        lines.append(f"#     {index}. {item.name}")
        lines.extend(_wrap(item.reason, "#        WHY: ", "#             "))
        lines.extend(f"#        {line}" for line in item.evidence)
        lines.append("#")
    return lines

Activity · 9 steps
lines 366–366◇ if not rejectionslines 367–367return []lines 368–368lines = [f"# ── REJECTED — {len(rejections)} candidate(s) considered and REFUSED " + "─" * 6]lines 369–369◇ for index, item in enumerate(rejections, start=1)lines 370–370lines.append(f"# {index}. {item.name}")lines 371–371lines.extend(_wrap(item.reason, "# WHY: ", "# "))lines 372–372lines.extend(f"# {line}" for line in item.evidence)lines 373–373lines.append("#")lines 374–374return lines

Flows

_scope_line

str clew.propose.render._scope_line(Mapping[str, Any] scope)

One-line description of the derived index scope.

clew/propose/render.py:203

Show on the map →

Called by _header

Calls none

Source · 16 lines
def _scope_line(scope: Mapping[str, Any]) -> str:
    """The C/C++ count is stated separately from the parsed count because the
    parser router covers Python too: on a Python codebase the two differ, and only the
    first number describes what the R1 AST detectors could read.

    @brief Describe the scope every measured number was computed against.
    @version 3
    """
    head = (
        f"{scope['source']} — {scope['roots']} root(s), {scope['excludes']} exclude(s); "
        f"{scope['files_in_scope']} of {scope['files_parsed']} parsed source file(s) in scope, "
        f"{scope['ast_readable_in_scope']} of them C/C++"
    )
    return head if scope["derived"] else f"{head}   [NOT DERIVED: {scope['reason']}]"

Activity · 2 steps
lines 211–215head = ( f"{scope['source']} — {scope['roots']} root(s), {scope['excludes']} exclude(s); " f"{scope['files_in_scope']} of {scope['files_parsed']} parsed source file(s) in scope, " f"{scope['ast_readable_in_scope']} of them C/C++" )lines 216–216return head if scope["derived"] else f"{head} [NOT DERIVED: {scope['reason']}]"

Flows

_section_block

list[str] clew.propose.render._section_block(SectionProposal section)

One section's whole block: status, evidence, YAML, rejections, notes.

clew/propose/render.py:278

Source · 17 lines
def _section_block(section: SectionProposal) -> list[str]:
    """@brief Render one declaration section."""
    meaning = _STATUS_MEANING.get(section.status, "")
    return [
        f"# ══ {section.name} " + "═" * max(0, _WIDTH - 6 - len(section.name)),
        f"#  STATUS: {section.status.value.upper()}" + (f"  ({meaning})" if meaning else ""),
        *_wrap(section.reason, "#  WHY:   ", "#         "),
        *_checked(section.checked),
        "#",
        *_entries(section.entries),
        *_yaml_block(section),
        *_rejections(section.rejections),
        *_notes(section.notes),
        "",
    ]

Activity · 2 steps
lines 280–280meaning = _STATUS_MEANING.get(section.status, "")lines 281–292return [ f"# ══ {section.name} " + "═" * max(0, _WIDTH - 6 - len(section.name)), f"# STATUS: {section.status.value.upper()}" + (f" ({meaning})" if meaning else ""), *_wrap(section.reason, "# WHY: ", "# "), *_checked(section.checked), "#", *_entries(section.entries), *_yaml_block(section), *_rejections(section.rejections), *_notes(section.notes), "", ]

Flows

_summary

list[str] clew.propose.render._summary(Sequence[SectionProposal] sections)

The section index: one row per section with its status and counts.

clew/propose/render.py:256

Source · 17 lines
def _summary(sections: Sequence[SectionProposal]) -> list[str]:
    """Up front because it is the only view that makes an OMISSION visible: every
    declaration section appears here, so a reader can see that a section was
    considered even when it produced nothing.

    @brief Render the per-section status table.
    @version 1
    """
    width = max((len(s.name) for s in sections), default=0)
    rows = [
        f"#    {s.name:<{width}}  {s.status.value:<16} {len(s.entries):>3} proposed"
        f" {len(s.rejections):>3} rejected"
        for s in sections
    ]
    return ["#  SECTIONS", *rows, "#", _MID, ""]

Activity · 3 steps
lines 264–264width = max((len(s.name) for s in sections), default=0)lines 265–269rows = [ f"# {s.name:<{width}} {s.status.value:<16} {len(s.entries):>3} proposed" f" {len(s.rejections):>3} rejected" for s in sections ]lines 270–270return ["# SECTIONS", *rows, "#", _MID, ""]

Flows

_wrap

list[str] clew.propose.render._wrap(str text, str first, str|None rest=None)

Wrap prose into comment lines at the document width.

clew/propose/render.py:399

Source · 18 lines
def _wrap(text: str, first: str, rest: str | None = None) -> list[str]:
    """Only prose is wrapped. Evidence lines are pre-formatted columns and are
    emitted verbatim — wrapping them would destroy the alignment that makes a
    before/after measurement readable at a glance.

    @brief Wrap one prose paragraph into comment lines.
    @version 1
    """
    continuation = first if rest is None else rest
    wrapped = textwrap.wrap(
        text,
        width=_WIDTH,
        initial_indent=first,
        subsequent_indent=continuation,
        break_long_words=False,
        break_on_hyphens=False,
    )
    return wrapped or [first.rstrip()]

1 more lines, not shown

Activity · 3 steps
lines 407–407continuation = first if rest is None else restlines 408–415wrapped = textwrap.wrap( text, width=_WIDTH, initial_indent=first, subsequent_indent=continuation, break_long_words=False, break_on_hyphens=False, )lines 416–416return wrapped or [first.rstrip()]

Flows

_yaml_block

list[str] clew.propose.render._yaml_block(SectionProposal section)

The activatable YAML block for a section, marked with the gutter.

clew/propose/render.py:334

Source · 18 lines
def _yaml_block(section: SectionProposal) -> list[str]:
    """A section's block is its `yaml_header` followed by every entry's
    `yaml_lines`, in order — the one composition rule, so a new section brings its
    own shape and needs no branch here.

    @brief Render a section's YAML behind the activation marker.
    @version 1
    """
    body = [*section.yaml_header, *(line for entry in section.entries for line in entry.yaml_lines)]
    if not body:
        return []
    return [
        "#  ── ACTIVATE (delete the leading '" + YAML_MARKER.rstrip() + " ') " + "─" * 18,
        *(YAML_MARKER + line for line in body),
        "#",
    ]

Activity · 4 steps
lines 342–342body = [*section.yaml_header, *(line for entry in section.entries for line in entry.yaml_lines)]lines 343–343◇ if not bodylines 344–344return []lines 345–349return [ "# ── ACTIVATE (delete the leading '" + YAML_MARKER.rstrip() + " ') " + "─" * 18, *(YAML_MARKER + line for line in body), "#", ]

Flows

marked_lines

list[str] clew.propose.render.marked_lines(str text)

The YAML lines a draft marks as activatable, marker removed.

clew/propose/render.py:97

Source · 18 lines
def marked_lines(text: str) -> list[str]:
    """A line must START with the marker to count. The header's own instruction
    quotes the marker mid-sentence, and a substring test would pick that prose up
    as YAML — which is exactly the confusion the marker exists to remove.

    @brief Extract a draft's marked YAML lines.
    @version 1
    """
    marker = YAML_MARKER.rstrip()
    out: list[str] = []
    for line in text.splitlines():
        if line.startswith(YAML_MARKER):
            out.append(line[len(YAML_MARKER) :])
        elif line.strip() == marker:
            out.append("")
    return out

Activity · 8 steps
lines 105–105marker = YAML_MARKER.rstrip()lines 106–106out: list[str] = []lines 107–107◇ for line in text.splitlines()lines 108–108◇ if line.startswith(YAML_MARKER)lines 109–109out.append(line[len(YAML_MARKER) :])lines 110–110◇ elif line.strip() == markerlines 111–111out.append("")lines 112–112return out

Requirements

REQ-DDB-CONFIG-001

render_declaration

str clew.propose.render.render_declaration(Path repo_root, Mapping[str, Any] db_status, Mapping[str, Any] scope, Sequence[SectionProposal] sections)

Render a whole proposal as a commented .clew.yaml draft.

clew/propose/render.py:79

Source · 13 lines
def render_declaration(
    repo_root: Path,
    db_status: Mapping[str, Any],
    scope: Mapping[str, Any],
    sections: Sequence[SectionProposal],
) -> str:
    """@brief Assemble the header, the section index and every section block."""
    lines = [*_header(repo_root, db_status, scope), *_summary(sections)]
    for section in sections:
        lines.extend(_section_block(section))
    return "\n".join(lines) + "\n"

Activity · 4 steps
lines 86–86lines = [*_header(repo_root, db_status, scope), *_summary(sections)]lines 87–87◇ for section in sectionslines 88–88lines.extend(_section_block(section))lines 89–89return "\n".join(lines) + "\n"

Requirements

REQ-DDB-CONFIG-001

Flows

statement_from_draft

dict[str, Any] clew.propose.render.statement_from_draft(str text)

The draft's activatable YAML as the mapping a build option accepts.

clew/propose/render.py:137

Source · 36 lines
def statement_from_draft(text: str) -> dict[str, Any]:
    """THE MACHINE PATH FROM A DRAFT TO A STATEMENT (gh#360), and the reason it is a
    separate function rather than a mode of the renderer: the draft stays all-comments and
    stays non-authoritative. `uncomment` performs the same transform an owner performs by
    hand; this parses the result into the exact `{section: document}` shape
    `buildoptions.apply_options` takes, so an agent can state a proposal on the next build
    without writing a file into a repository it does not own.

    IT IS STILL A PROPOSAL. Nothing here applies anything — a caller has to pass the value
    to `build_or_refresh(options=…)`, where it is validated as strictly as a parsed file.
    The draft being readable by a machine does not make it authoritative; an explicit
    statement is what counts, which is the whole distinction the all-comments contract
    exists to hold.

    A draft that proposes nothing yields `{}`, not an error: no candidate survived the dry
    run, which is a result. A recovered document that is not a mapping RAISES, because that
    could only mean this renderer emitted something malformed.

    @brief Parse a draft's activatable YAML into a statable options mapping.
    @return Section name → document.
    @version 1
    """
    import yaml

    body = uncomment(text)
    if not body.strip():
        return {}
    data = yaml.safe_load(body)
    if not isinstance(data, dict):
        raise ValueError(
            f"a draft's activatable lines did not parse to a mapping but to "
            f"{type(data).__name__} — the renderer emitted something malformed"
        )
    return data

Activity · 8 steps
lines 159–159import yamllines 161–161body = uncomment(text)lines 162–162◇ if not body.strip()lines 163–163return {}lines 164–164data = yaml.safe_load(body)lines 165–165◇ if not isinstance(data, dict)lines 166–169raise ValueError( f"a draft's activatable lines did not parse to a mapping but to " f"{type(data).__name__} — the renderer emitted something malformed" )lines 170–170return data

Requirements

REQ-DDB-CONFIG-008

uncomment

str clew.propose.render.uncomment(str text)

Recover the active YAML from a rendered draft.

clew/propose/render.py:120

Source · 12 lines
def uncomment(text: str) -> str:
    """The exact transform an owner performs by hand, so a test can prove the
    draft parses to the sections it claims. Anything not carrying the marker is
    prose ABOUT the proposal and is dropped — which is why the marker exists.

    @brief Strip the activation marker, yielding real YAML.
    @version 2
    """
    lines = marked_lines(text)
    return "\n".join(lines) + ("\n" if lines else "")

Activity · 2 steps
lines 128–128lines = marked_lines(text)lines 129–129return "\n".join(lines) + ("\n" if lines else "")

Requirements

REQ-DDB-CONFIG-001