tracepages.py

clew/wiki/tracepages.py

The requirement trace and the model entries, gathered once and written as the site's pages.

_node_example

str clew.wiki.tracepages._node_example(Trace trace)

A worked example, drawn from the first entry a function realises: entry → function → requirement.

clew/wiki/tracepages.py:771

Show on the map →

Called by nodes_page

Calls list, text

Source · 44 lines
def _node_example(trace: Trace) -> str:
    """A REAL ROW OF THIS REPOSITORY, not a made-up one: the example is what the reader will
    find in the table below.

    @brief Example diagram.
    @return HTML.
    """
    node = next((n for n in trace.nodes if trace.refs.get(n.ref)), None)
    if node is None:
        return ""
    func = sorted(trace.refs[node.ref])[0]
    reqs = list(node.requirements) or sorted(
        r.req_id for r in trace.evidence if any(n == func for n, _f, _l in r.implementer_sites)
    )
    boxes = [
        (node.ref, node.file, "model entry"),
        (func, "realises it", "function"),
        (reqs[0] if reqs else "—", "served", "requirement"),
    ]
    arrows = [f"@node {node.ref}", "@req" if reqs else ""]
    parts = []
    for i, (name, sub, kind) in enumerate(boxes):
        x = 10 + i * 270
        parts.append(
            f'<rect x="{x}" y="20" width="200" height="64" rx="10"/>'
            f'<text class="k" x="{x + 12}" y="40">{text(kind)}</text>'
            f'<text class="n" x="{x + 12}" y="60">{text(name)}</text>'
            f'<text class="k" x="{x + 12}" y="76">{text(sub)}</text>'
        )
    for i, label in enumerate(arrows):
        x = 210 + i * 270
        parts.append(
            f'<path d="M{x + 4} 52H{x + 64}" marker-end="url(#node-arrow)"/>'
            f'<text class="a" x="{x + 34}" y="14" text-anchor="middle">{text(label)}</text>'
        )
    return (
        '<svg class="node-example" xmlns="http://www.w3.org/2000/svg" width="760" height="100" '
        'viewBox="0 0 760 100" role="img" aria-label="How a model entry traces to a requirement">'
        '<defs><marker id="node-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" '
        'markerHeight="8" orient="auto"><path d="M0 0L10 5L0 10z"/></marker></defs>'
        f"{''.join(parts)}</svg>"
    )

Activity · 15 steps
lines 778–778node = next((n for n in trace.nodes if trace.refs.get(n.ref)), None)lines 779–779◇ if node is Nonelines 780–780return ""lines 781–781func = sorted(trace.refs[node.ref])[0]lines 782–784reqs = list(node.requirements) or sorted( r.req_id for r in trace.evidence if any(n == func for n, _f, _l in r.implementer_sites) )lines 785–789boxes = [ (node.ref, node.file, "model entry"), (func, "realises it", "function"), (reqs[0] if reqs else "—", "served", "requirement"), ]lines 790–790arrows = [f"@node {node.ref}", "@req" if reqs else ""]lines 791–791parts = []lines 792–792◇ for i, (name, sub, kind) in enumerate(boxes)lines 793–793x = 10 + i * 270lines 794–799parts.append( f'<rect x="{x}" y="20" width="200" height="64" rx="10"/>' f'<text class="k" x="{x + 12}" y="40">{text(kind)}</text>' f'<text class="n" x="{x + 12}" y="60">{text(name)}</text>' f'<text class="k" x="{x + 12}" y="76">{text(sub)}</text>' )lines 800–800◇ for i, label in enumerate(arrows)lines 801–801x = 210 + i * 270lines 802–805parts.append( f'<path d="M{x + 4} 52H{x + 64}" marker-end="url(#node-arrow)"/>' f'<text class="a" x="{x + 34}" y="14" text-anchor="middle">{text(label)}</text>' )lines 806–812return ( '<svg class="node-example" xmlns="http://www.w3.org/2000/svg" width="760" height="100" ' 'viewBox="0 0 760 100" role="img" aria-label="How a model entry traces to a requirement">' '<defs><marker id="node-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" ' 'markerHeight="8" orient="auto"><path d="M0 0L10 5L0 10z"/></marker></defs>' f"{''.join(parts)}</svg>" )

Requirements

REQ-DDB-WIKI-024

_with_needs

tuple[list, dict] clew.wiki.tracepages._with_needs(list evidence, dict declared, Path path)

Merge a Sphinx-needs import: the catalog wins; a need the index never saw is MISSING.

clew/wiki/tracepages.py:189

Show on the map →

Called by gather

Calls parse_needs

Source · 23 lines
def _with_needs(evidence: list, declared: dict, path: Path) -> tuple[list, dict]:
    """A NEED NOTHING IMPLEMENTS IS A REQUIREMENT WITH NO IMPLEMENTER — MISSING, not absent: the
    import declares it, and the site says nobody has done it.

    @brief Merge needs.
    @return Evidence and entries.
    """
    from .evidence import RequirementEvidence
    from .imports import parse_needs

    needs = parse_needs(path)
    merged = {**{k: dict(v) for k, v in needs.items()}, **declared}
    for key, entry in declared.items():
        merged[key] = {**needs.get(key, {}), **entry}
    known = {r.req_id for r in evidence}
    extra = [
        RequirementEvidence(nid, needs[nid].get("name", ""), "MISSING", (), ())
        for nid in sorted(needs)
        if nid not in known
    ]
    return [*evidence, *extra], merged

Activity · 9 steps
lines 196–196from .evidence import RequirementEvidencelines 197–197from .imports import parse_needslines 199–199needs = parse_needs(path)lines 200–200merged = {**{k: dict(v) for k, v in needs.items()}, **declared}lines 201–201◇ for key, entry in declared.items()lines 202–202merged[key] = {**needs.get(key, {}), **entry}lines 203–203known = {r.req_id for r in evidence}lines 204–208extra = [ RequirementEvidence(nid, needs[nid].get("name", ""), "MISSING", (), ()) for nid in sorted(needs) if nid not in known ]lines 209–209return [*evidence, *extra], merged

Requirements

REQ-DDB-WIKI-030

group_pages

list[str] clew.wiki.tracepages.group_pages(Trace trace, dict[str, Any] ctx, Path source)

Write one page per requirement group: its bar, its counts, its requirements.

clew/wiki/tracepages.py:351

Source · 36 lines
def group_pages(trace: Trace, ctx: dict[str, Any], source: Path) -> list[str]:
    """OWNER (round 5, P5.4): requirement groups get pages, linked from the group cards. ORPHAN
    pages, like the requirement pages: a group is a URL a reader can share, and the index stays
    the one place that lists every requirement.

    @brief Write reqgroup-*.md.
    @return Names.
    """
    from .summary import group_page_of, groups_of, tier_bar

    names = []
    for group, members in groups_of(trace.evidence):
        name = group_page_of(group)
        counts = (
            f"{len(members)} requirements: {sum(1 for r in members if r.implementers)} "
            f"implemented, {sum(1 for r in members if r.tests)} tested, "
            f"{sum(1 for r in members if r.tier == 'PASS')} passing."
        )
        lines = [
            "---",
            "orphan: true",
            "---",
            "",
            f"# {md_title(group)}",
            "",
            *_raw(
                '<p class="crumbs"><a href="requirements.html">← Requirements</a></p>'
                f'<p class="g-summary">{counts}</p><div class="g-page-bar">{tier_bar(members)}</div>'
            ),
            *_raw(_requirement_table(trace, ctx, members)),
        ]
        (source / f"{name}.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
        names.append(name)
    return names

Activity · 9 steps
lines 359–359from .summary import group_page_of, groups_of, tier_barlines 361–361names = []lines 362–362◇ for group, members in groups_of(trace.evidence)lines 363–363name = group_page_of(group)lines 364–368counts = ( f"{len(members)} requirements: {sum(1 for r in members if r.implementers)} " f"implemented, {sum(1 for r in members if r.tests)} tested, " f"{sum(1 for r in members if r.tier == 'PASS')} passing." )lines 369–381lines = [ "---", "orphan: true", "---", "", f"# {md_title(group)}", "", *_raw( '<p class="crumbs"><a href="requirements.html">← Requirements</a></p>' f'<p class="g-summary">{counts}</p><div class="g-page-bar">{tier_bar(members)}</div>' ), *_raw(_requirement_table(trace, ctx, members)), ]lines 382–382(source / f"{name}.md").write_text("\n".join(lines) + "\n", encoding="utf-8")lines 383–383names.append(name)lines 384–384return names

Requirements

REQ-DDB-WIKI-022

impact_path

Path clew.wiki.tracepages.impact_path(Path repo_root, WikiConfig config)

Where the impact report is: declared, else clew-guard's output directory.

clew/wiki/tracepages.py:219

Source · 16 lines
def impact_path(repo_root: Path, config: WikiConfig) -> Path:
    """ONE PATH (R5-CFG F9, 2.0.0): the gate's `guard.impact.report_dir`, where its hook and
    `clew guard impact --write` put the report. `wiki.impact` (a third key that could disagree) is
    gone; `config.impact` remains only as a test seam.

    @brief Locate impact.json.
    @return Path.
    """
    from ..guard.config import REPORT_JSON, report_dir
    from ..requirements import load_guard_config

    if config.impact:
        return Path(repo_root) / config.impact
    return Path(repo_root) / report_dir(load_guard_config(repo_root)) / REPORT_JSON

Activity · 5 steps
lines 227–227from ..guard.config import REPORT_JSON, report_dirlines 228–228from ..requirements import load_guard_configlines 230–230◇ if config.impactlines 231–231return Path(repo_root) / config.impactlines 232–232return Path(repo_root) / report_dir(load_guard_config(repo_root)) / REPORT_JSON

Requirements

REQ-DDB-WIKI-015

load_impact

list[dict] | None clew.wiki.tracepages.load_impact(Path path)

Read clew-guard's impact report.

clew/wiki/tracepages.py:241

Show on the map →

Called by gather

Calls none

Source · 16 lines
def load_impact(path: Path) -> list[dict] | None:
    """ABSENT IS NOT EMPTY: no file → None (no section); `[]` → "no requirement affected".

    @brief Read impact.
    @return Entries or None.
    """
    if not path.is_file():
        return None
    data = json.loads(path.read_text(encoding="utf-8"))
    ## PS3 (2.0.0): `{"schema_version", "entries"}`. A bare array is a report an older clew wrote,
    ## still read: a strict writer and a tolerant reader.
    if isinstance(data, dict):
        data = data.get("entries")
    return data if isinstance(data, list) else None

Activity · 6 steps
lines 247–247◇ if not path.is_file()lines 248–248return Nonelines 249–249data = json.loads(path.read_text(encoding="utf-8"))lines 252–252◇ if isinstance(data, dict)lines 253–253data = data.get("entries")lines 254–254return data if isinstance(data, list) else None

Requirements

REQ-DDB-WIKI-015

nodes_page

str clew.wiki.tracepages.nodes_page(Trace trace, WikiConfig config, Path source)

Write the model-entries page.

clew/wiki/tracepages.py:713

Source · 52 lines
def nodes_page(trace: Trace, config: WikiConfig, source: Path) -> str:
    """SAID WHAT IT IS (owner 2026-11-15: "model nodes is not well understood"): the page opens by
    explaining that each row is an entry of a declared model file, with a worked example drawn
    from a real row (round 3, P1g), and groups entries by source. ROUND 4, R12 (owner: "a USELESS
    page"): no page at all when no function realises any entry, and each source says how many of
    its entries have code behind them.

    @brief Render model entries.
    @return Page name.
    """
    if not any(trace.refs.get(n.ref) for n in trace.nodes):
        return ""
    lines = [
        "# Model entries",
        "",
        "Some of what this repository does is defined by DATA rather than code: a table of keys, a "
        "list of commands or topics, the models it ships. Those data files are declared in "
        "`wiki.sources`, and each row is a *model entry*. When a function implements a row, it "
        "says so with a `@node <source>:<id>` tag. This page shows, for every row, which code "
        "realises it and which requirement it serves, so a row nothing implements, or code that "
        "implements a row nobody declared, is visible. The diagram is a real row from this "
        "repository.",
        "",
        *_raw(_node_example(trace)),
    ]
    for spec in config.sources:
        mine = [n for n in trace.nodes if n.source == spec.name]
        done = sum(1 for n in mine if trace.refs.get(n.ref))
        lines += [
            f"## `{spec.name}` — `{spec.path}`",
            "",
            f"{done} of {len(mine)} entries have code realising them.",
            "",
        ]
        rows = [
            [
                code(n.id),
                text(n.doc),
                "<br>".join(code(f) for f in trace.refs.get(n.ref, ())),
                "<br>".join(
                    f'<a href="requirements.html#{text(r)}">{text(r)}</a>' for r in n.requirements
                ),
            ]
            for n in mine
        ]
        lines += _raw(
            table(["entry", "doc", "realised by", "serves"], rows, keep=("entry", "realised by"))
        )
    (source / "nodes.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
    return "nodes"

Activity · 11 steps
lines 723–723◇ if not any(trace.refs.get(n.ref) for n in trace.nodes)lines 724–724return ""lines 725–737lines = [ "# Model entries", "", "Some of what this repository does is defined by DATA rather than code: a table of keys, a " "list of commands or topics, the models it ships. Those data files are declared in " "`wiki.sources`, and each row is a *model entry*. When a function implements a row, it " "says so with a `@node <source>:<id>` tag. This page shows, for every row, which code " "realises it and which requirement it serves, so a row nothing implements, or code that " "implements a row nobody declared, is visible. The diagram is a real row from this " "repository.", "", *_raw(_node_example(trace)), ]lines 738–738◇ for spec in config.sourceslines 739–739mine = [n for n in trace.nodes if n.source == spec.name]lines 740–740done = sum(1 for n in mine if trace.refs.get(n.ref))lines 741–746lines += [ f"## `{spec.name}` — `{spec.path}`", "", f"{done} of {len(mine)} entries have code realising them.", "", ]lines 747–757rows = [ [ code(n.id), text(n.doc), "<br>".join(code(f) for f in trace.refs.get(n.ref, ())), "<br>".join( f'<a href="requirements.html#{text(r)}">{text(r)}</a>' for r in n.requirements ), ] for n in mine ]lines 758–760lines += _raw( table(["entry", "doc", "realised by", "serves"], rows, keep=("entry", "realised by")) )lines 761–761(source / "nodes.md").write_text("\n".join(lines) + "\n", encoding="utf-8")lines 762–762return "nodes"

Requirements

REQ-DDB-WIKI-004

requirements_page

str clew.wiki.tracepages.requirements_page(Trace trace, WikiConfig config, Path source, Audience rules, str burndown="", tuple flows=(), tuple[str, str]|None issues=None, dict[str, str]|None blocks=None)

Write the requirements page: summary, charts, impact, every requirement, rules, pins.

clew/wiki/tracepages.py:278

Show on the map →

Called by _build_site

Calls _catalogs_section, _issues_section, _link_kinds, _missing_note, _raw, _requirement_table, _rules_section, charts_block, group_cards, group_pages, group_table, list

2 morerequirement_pages, traceability_page

Source · 66 lines
def requirements_page(
    trace: Trace,
    config: WikiConfig,
    source: Path,
    rules: Audience,
    burndown: str = "",
    flows: tuple = (),
    issues: tuple[str, str] | None = None,
    blocks: dict[str, str] | None = None,
) -> str:
    """@brief Render the trace. @return Page name."""
    from .summary import charts_block, group_cards, group_table

    ev = trace.evidence
    ctx = {
        "trace": trace,
        "rules": rules,
        "flows": list(flows),
        "issues": issues,
        "ears": config.ears,
        ## W-9: where each requirement lives (file → map block).
        "blocks": blocks or {},
    }
    requirement_pages(trace, ctx, source)
    group_pages(trace, ctx, source)
    traceability_page(trace, source)
    origin = f" declared in `{trace.catalog_path}`" if trace.catalog_path else ""
    lines = [
        "# Requirements",
        "",
        f"{len(ev)} requirements{origin} or tagged in the code: "
        f"{sum(1 for r in ev if r.implementers)} implemented, "
        f"{sum(1 for r in ev if r.tests)} tested, {sum(1 for r in ev if r.tier == 'PASS')} passing.",
        "",
        _link_kinds(ev),
        "",
        *_missing_note(trace),
        *_raw(
            '<p>The <a href="traceability.html">traceability checklist</a> lists, per '
            "requirement, the IEEE 29148 attributes it carries and its trace evidence.</p>"
        ),
        "## Groups",
        "",
        "Each card is a requirement group; pick one to filter the list below to it.",
        "",
        *_raw(group_cards(ev)),
        "## Every requirement",
        "",
        "Each requirement opens its own page: acceptance criteria, implementers, every test with "
        "what it exercises, flows and issues.",
        "",
        *_raw(_requirement_table(trace, ctx)),
        "## Charts",
        "",
        *_raw(charts_block(ev)),
    ]
    if burndown:
        lines += ["## Burndown", "", *_raw(f'<div class="chart-card">{burndown}</div>')]
    lines += ["## Group counts", "", *_raw(group_table(ev, config.inputs.min_layers))]
    lines += _issues_section(trace)
    lines += _rules_section(trace, rules)
    lines += _catalogs_section(trace, rules)
    (source / "requirements.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
    return "requirements"

Activity · 16 steps
lines 289–289from .summary import charts_block, group_cards, group_tablelines 291–291ev = trace.evidencelines 292–300ctx = { "trace": trace, "rules": rules, "flows": list(flows), "issues": issues, "ears": config.ears, ## W-9: where each requirement lives (file → map block). "blocks": blocks or {}, }lines 301–301requirement_pages(trace, ctx, source)lines 302–302group_pages(trace, ctx, source)lines 303–303traceability_page(trace, source)lines 304–304origin = f" declared in `{trace.catalog_path}`" if trace.catalog_path else ""lines 305–333lines = [ "# Requirements", "", f"{len(ev)} requirements{origin} or tagged in the code: " f"{sum(1 for r in ev if r.implementers)} implemented, " f"{sum(1 for r in ev if r.tests)} tested, {sum(1 for r in ev if r.tier == 'PASS')} passing.", "", _link_kinds(ev), "", *_missing_note(trace), *_raw( '<p>The <a href="traceability.html">traceability checklist</a> lists, per ' "requirement, the IEEE 29148 attributes it carries and its trace evidence.</p>" ), "## Groups", "", "Each card is a requirement group; pick one to filter the list below to it.", "", *_raw(group_cards(ev)), "## Every requirement", "", "Each requirement opens its own page: acceptance criteria, implementers, every test with " "what it exercises, flows and issues.", "", *_raw(_requirement_table(trace, ctx)), "## Charts", "", *_raw(charts_block(ev)), ]lines 334–334◇ if burndownlines 335–335lines += ["## Burndown", "", *_raw(f'<div class="chart-card">{burndown}</div>')]lines 336–336lines += ["## Group counts", "", *_raw(group_table(ev, config.inputs.min_layers))]lines 337–337lines += _issues_section(trace)lines 338–338lines += _rules_section(trace, rules)lines 339–339lines += _catalogs_section(trace, rules)lines 340–340(source / "requirements.md").write_text("\n".join(lines) + "\n", encoding="utf-8")lines 341–341return "requirements"

Requirements

REQ-DDB-WIKI-012

Flows

traceability_page

str clew.wiki.tracepages.traceability_page(Trace trace, Path source)

Write the S4 traceability checklist: each requirement's attributes and evidence.

clew/wiki/tracepages.py:423

Show on the map →

Called by requirements_page

Calls _raw, _shows, code, text

Source · 48 lines
def traceability_page(trace: Trace, source: Path) -> str:
    """S4 (owner-approved 2026-11-17): per requirement, which IEEE 29148 attributes the catalogue
    gives it (rationale, verification method, parent) and whether the index shows it implemented,
    tested and passing. SUPPORTS EVIDENCE, NEVER A CONFORMANCE CLAIM: it reports what a catalogue
    and an index show, and conformance to a standard is an assessor's call, not a tool's.

    @brief Write traceability.md.
    @return Page name.
    """
    ev = trace.evidence
    rows = []
    for row in ev:
        entry = trace.declared.get(row.req_id, {})
        cells = "".join(
            f'<td data-check="{key}" class="{"ok" if _shows(row, entry, key) else "gap"}">'
            f"{'✓' if _shows(row, entry, key) else '—'}</td>"
            for key, _h, _p in _CHECKS
        )
        rows.append(f'<tr data-req="{text(row.req_id)}"><td>{code(row.req_id)}</td>{cells}</tr>')
    head = "".join(f"<th>{text(h)}</th>" for _k, h, _p in _CHECKS)
    counts = " · ".join(
        f"{sum(1 for r in ev if _shows(r, trace.declared.get(r.req_id, {}), key))} of {len(ev)} "
        f"{phrase}"
        for key, _h, phrase in _CHECKS
    )
    lines = [
        "---",
        "orphan: true",
        "---",
        "",
        "# Traceability checklist",
        "",
        "This page supports evidence for a traceability review in the IEEE 29148 sense: for each "
        "requirement, the attributes its catalogue entry carries and what the index shows about "
        "its implementation and tests. It is evidence for a reviewer, not a statement of "
        "conformance to any standard.",
        "",
        *_raw(
            '<p class="crumbs"><a href="requirements.html">← Requirements</a></p>'
            f'<p class="g-summary">{counts}</p>'
            f'<div class="table-wrap"><table class="clew checklist"><thead><tr><th>requirement</th>'
            f"{head}</tr></thead><tbody>{''.join(rows)}</tbody></table></div>"
        ),
    ]
    (source / "traceability.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
    return "traceability"

Activity · 11 steps
lines 432–432ev = trace.evidencelines 433–433rows = []lines 434–434◇ for row in evlines 435–435entry = trace.declared.get(row.req_id, {})lines 436–440cells = "".join( f'<td data-check="{key}" class="{"ok" if _shows(row, entry, key) else "gap"}">' f"{'✓' if _shows(row, entry, key) else '—'}</td>" for key, _h, _p in _CHECKS )lines 441–441rows.append(f'<tr data-req="{text(row.req_id)}"><td>{code(row.req_id)}</td>{cells}</tr>')lines 442–442head = "".join(f"<th>{text(h)}</th>" for _k, h, _p in _CHECKS)lines 443–447counts = " · ".join( f"{sum(1 for r in ev if _shows(r, trace.declared.get(r.req_id, {}), key))} of {len(ev)} " f"{phrase}" for key, _h, phrase in _CHECKS )lines 448–466lines = [ "---", "orphan: true", "---", "", "# Traceability checklist", "", "This page supports evidence for a traceability review in the IEEE 29148 sense: for each " "requirement, the attributes its catalogue entry carries and what the index shows about " "its implementation and tests. It is evidence for a reviewer, not a statement of " "conformance to any standard.", "", *_raw( '<p class="crumbs"><a href="requirements.html">← Requirements</a></p>' f'<p class="g-summary">{counts}</p>' f'<div class="table-wrap"><table class="clew checklist"><thead><tr><th>requirement</th>' f"{head}</tr></thead><tbody>{''.join(rows)}</tbody></table></div>" ), ]lines 467–467(source / "traceability.md").write_text("\n".join(lines) + "\n", encoding="utf-8")lines 468–468return "traceability"

Requirements

REQ-DDB-WIKI-022