flowpage.py

clew/wiki/flowpage.py

One flow's page: the diagram, its interactive layer, the step table and the bodies reached.

_badges

str clew.wiki.flowpage._badges(Any reqs)

Requirement badges, each linked to its row on the requirements page.

clew/wiki/flowpage.py:852

Source · 18 lines
def _badges(reqs: Any) -> str:
    """UX review D-10 (owner Q/A 2026-11-22): three or fewer inline; more fold under their count,
    and each pill opens the requirement's own page.

    @brief Badges.
    @return HTML.
    """
    from .reqmodal import page_of

    pills = [
        f'<a class="req-badge" href="{escape(page_of(r))}.html">{escape(r)}</a>'
        for r in sorted(set(reqs))
    ]
    if len(pills) <= 3:
        return " ".join(pills)
    return f'<details class="fold"><summary>{len(pills)} requirements</summary>{" ".join(pills)}</details>'

Activity · 5 steps
lines 859–859from .reqmodal import page_oflines 861–864pills = [ f'<a class="req-badge" href="{escape(page_of(r))}.html">{escape(r)}</a>' for r in sorted(set(reqs)) ]lines 865–865◇ if len(pills) <= 3lines 866–866return " ".join(pills)lines 867–867return f'<details class="fold"><summary>{len(pills)} requirements</summary>{" ".join(pills)}</details>'

Flows

_block

str clew.wiki.flowpage._block(Flow flow, list[dict[str, Any]] data, bool animate, str node="", dict|None segments=None)

The diagram, controls, data and script, as one raw HTML block.

clew/wiki/flowpage.py:502

Source · 28 lines
def _block(
    flow: Flow,
    data: list[dict[str, Any]],
    animate: bool,
    node: str = "",
    segments: dict | None = None,
) -> str:
    """`<` IS ESCAPED IN THE JSON so no repository text can close the script element.

    @brief Assemble the block.
    @return HTML.
    """
    ## X-1: each step carries the scenario line it builds, for present mode's step panel.
    current = ""
    for i, row in enumerate(data):
        current = (segments or {}).get(i, current)
        row["seg"] = current
    blob = json.dumps(data, ensure_ascii=False).replace("<", "\\u003c")
    attr = f' data-test-node="{escape(node)}"' if node else ""

    return (
        f'<div class="flow-block"{attr}>{_STYLE}<div class="flow-home">{_controls()}'
        f'<div class="flow-wrap" data-pz>{flow_svg(flow, animate=animate, segments=segments)}</div></div>'
        f'<script type="application/json" class="flow-data">{blob}</script>'
        f"{_SCRIPT}</div>"
    )

Activity · 7 steps
lines 515–515current = ""lines 516–516◇ for i, row in enumerate(data)lines 517–517current = (segments or {}).get(i, current)lines 518–518row["seg"] = currentlines 519–519blob = json.dumps(data, ensure_ascii=False).replace("<", "\\u003c")lines 520–520attr = f' data-test-node="{escape(node)}"' if node else ""lines 522–527return ( f'<div class="flow-block"{attr}>{_STYLE}<div class="flow-home">{_controls()}' f'<div class="flow-wrap" data-pz>{flow_svg(flow, animate=animate, segments=segments)}</div></div>' f'<script type="application/json" class="flow-data">{blob}</script>' f"{_SCRIPT}</div>" )

Flows

_call_text

str clew.wiki.flowpage._call_text(Path repo_root, str rel, int line)

The call expression at a call site, read across lines until its parentheses close.

clew/wiki/flowpage.py:777

Show on the map →

Called by step_data

Calls none

Source · 16 lines
def _call_text(repo_root: Path, rel: str, line: int) -> str:
    """@brief Read the call. @return Text."""
    try:
        lines = (Path(repo_root) / rel).read_text(encoding="utf-8", errors="replace").splitlines()
    except OSError:
        return ""
    out: list[str] = []
    depth = 0
    for text in lines[max(0, line - 1) : line - 1 + _CALL_LINES]:
        out.append(text.rstrip())
        depth += text.count("(") - text.count(")")
        if depth <= 0:
            break
    return "\n".join(out).strip()

Activity · 12 steps
lines 779–779trylines 780–780lines = (Path(repo_root) / rel).read_text(encoding="utf-8", errors="replace").splitlines()lines 781–781except OSErrorlines 782–782return ""lines 783–783out: list[str] = []lines 784–784depth = 0lines 785–785◇ for text in lines[max(0, line - 1) : line - 1 + _CALL_LINES]lines 786–786out.append(text.rstrip())lines 787–787depth += text.count("(") - text.count(")")lines 788–788◇ if depth <= 0lines 789–789breaklines 790–790return "\n".join(out).strip()

Flows

_controls

str clew.wiki.flowpage._controls()

The player's controls: play, pause, step, present, and the reading-speed slider.

clew/wiki/flowpage.py:534

Show on the map →

Called by _block, test_the_player_has_a_speed_control_and_a_present_mode

Calls none

Source · 18 lines
def _controls() -> str:
    """W-3: the speed scales the reading-paced dwell, ×0.25 (slowest) to ×2.

    @brief Controls.
    @return HTML.
    """
    buttons = "".join(
        f'<button type="button" data-flow-control="{c}">{c}</button>'
        for c in ("play", "pause", "step", "present")
    )
    speed = (
        '<label class="flow-speed">speed <input type="range" min="0.25" max="2" step="0.25" '
        'value="1" data-flow-speed aria-label="playback speed"> <output data-flow-speed-label>'
        "\u00d71</output></label>"
    )
    return f'<div class="flow-controls">{buttons}{speed}</div>'

Activity · 3 steps
lines 540–543buttons = "".join( f'<button type="button" data-flow-control="{c}">{c}</button>' for c in ("play", "pause", "step", "present") )lines 544–548speed = ( '<label class="flow-speed">speed <input type="range" min="0.25" max="2" step="0.25" ' 'value="1" data-flow-speed aria-label="playback speed"> <output data-flow-speed-label>' "\u00d71</output></label>" )lines 549–549return f'<div class="flow-controls">{buttons}{speed}</div>'

Flows

_diagram_exports

list[str] clew.wiki.flowpage._diagram_exports(Flow flow, Path source, str name)

Write the flow as Mermaid, PlantUML and DOT into the site's exports, and link them.

clew/wiki/flowpage.py:801

Source · 18 lines
def _diagram_exports(flow: Flow, source: Path, name: str) -> list[str]:
    """@brief Diagram exports. @return Lines."""
    from .exports import flow_dot, flow_mermaid, flow_plantuml

    out = Path(source) / "_extra" / "exports" / "flows"
    out.mkdir(parents=True, exist_ok=True)
    (out / f"{name}.mmd").write_text(flow_mermaid(flow), encoding="utf-8")
    (out / f"{name}.puml").write_text(flow_plantuml(flow), encoding="utf-8")
    ## S7 (2.0.0, P5.7): Graphviz DOT beside them.
    (out / f"{name}.dot").write_text(flow_dot(flow), encoding="utf-8")
    links = (
        f'<p class="exports">This diagram as <a href="exports/flows/{name}.mmd">Mermaid</a> · '
        f'<a href="exports/flows/{name}.puml">PlantUML</a> · '
        f'<a href="exports/flows/{name}.dot">Graphviz DOT</a></p>'
    )
    return ["```{raw} html", links, "```", ""]

Activity · 8 steps
lines 803–803from .exports import flow_dot, flow_mermaid, flow_plantumllines 805–805out = Path(source) / "_extra" / "exports" / "flows"lines 806–806out.mkdir(parents=True, exist_ok=True)lines 807–807(out / f"{name}.mmd").write_text(flow_mermaid(flow), encoding="utf-8")lines 808–808(out / f"{name}.puml").write_text(flow_plantuml(flow), encoding="utf-8")lines 810–810(out / f"{name}.dot").write_text(flow_dot(flow), encoding="utf-8")lines 811–815links = ( f'<p class="exports">This diagram as <a href="exports/flows/{name}.mmd">Mermaid</a> · ' f'<a href="exports/flows/{name}.puml">PlantUML</a> · ' f'<a href="exports/flows/{name}.dot">Graphviz DOT</a></p>' )lines 816–816return ["```{raw} html", links, "```", ""]

Flows

_executed

dict[str, set[int]] clew.wiki.flowpage._executed(dict[str, dict[int, set[str]]] coverage)

The lines any test ran, per file.

clew/wiki/flowpage.py:181

Show on the map →

Called by flow_page

Calls none

Source · 7 lines
def _executed(coverage: dict[str, dict[int, set[str]]]) -> dict[str, set[int]]:
    """@brief Union of all tests' lines. @return Lines."""
    return {
        rel: {line for line, tests in lines.items() if tests} for rel, lines in coverage.items()
    }

Activity · 1 steps
lines 183–185return { rel: {line for line, tests in lines.items() if tests} for rel, lines in coverage.items() }

Flows

_keyword

str clew.wiki.flowpage._keyword(str line)

A scenario line with its keyword marked.

clew/wiki/flowpage.py:744

Source · 6 lines
def _keyword(line: str) -> str:
    """@brief Keyword. @return HTML."""
    kw, _sp, rest = str(line).partition(" ")
    return f'<span class="kw">{escape(kw)}</span> {escape(rest)}'

Activity · 2 steps
lines 746–746kw, _sp, rest = str(line).partition(" ")lines 747–747return f'<span class="kw">{escape(kw)}</span> {escape(rest)}'

Flows

_message_of

str clew.wiki.flowpage._message_of(Any step)

A not-run stub's words.

clew/wiki/flowpage.py:670

Source · 5 lines
def _message_of(step: Any) -> str:
    """@brief Stub label. @return Text."""
    return f"… {plural(step.not_run, 'call')} not run"

Activity · 1 steps
lines 672–672return f"… {plural(step.not_run, 'call')} not run"

Flows

_overview

str clew.wiki.flowpage._overview(Any flow, dict[int, str] segments, tuple[str,...] scenario=())

The overview: one row per segment, its steps and lanes, each bringing its part into view.

clew/wiki/flowpage.py:683

Show on the map →

Called by flow_page, test_a_declared_scenario_is_drawn_once_as_the_overview, test_a_flow_page_opens_on_its_overview_and_folds_the_detail

Calls _keyword, _segment_row, plural

Source · 31 lines
def _overview(flow: Any, segments: dict[int, str], scenario: tuple[str, ...] = ()) -> str:
    """A-1 (UX review, owner Q/A 2026-11-22): summary first. A row's `data-goto` is its first
    step; the page script scrolls the diagram's box to it and selects it. A declared scenario is
    drawn ONCE, here (found in the browser: the overview repeated the Gherkin block above it).

    @brief Overview.
    @return HTML.
    """
    if len(flow.steps) < 2 or not segments:
        return ""
    starts = sorted(segments)
    ends = {
        i: (starts[n + 1] if n + 1 < len(starts) else len(flow.steps)) - 1
        for n, i in enumerate(starts)
    }
    at = {text: i for i, text in segments.items()}
    lines = scenario or tuple(segments[i] for i in starts)
    rows = [
        _segment_row(flow, at[line], ends[at[line]], line, bool(scenario))
        if line in at
        else f'<li class="plain">{_keyword(line)}</li>'
        for line in lines
        if str(line).strip()
    ]
    return (
        '<div class="flow-overview"><p class="ov-h">Overview · '
        f"{plural(len(flow.steps), 'step')}, {plural(len(flow.lanes), 'lane')}</p>"
        f'<ol class="segments">{"".join(rows)}</ol></div>'
    )

Activity · 8 steps
lines 691–691◇ if len(flow.steps) < 2 or not segmentslines 692–692return ""lines 693–693starts = sorted(segments)lines 694–697ends = { i: (starts[n + 1] if n + 1 < len(starts) else len(flow.steps)) - 1 for n, i in enumerate(starts) }lines 698–698at = {text: i for i, text in segments.items()}lines 699–699lines = scenario or tuple(segments[i] for i in starts)lines 700–706rows = [ _segment_row(flow, at[line], ends[at[line]], line, bool(scenario)) if line in at else f'<li class="plain">{_keyword(line)}</li>' for line in lines if str(line).strip() ]lines 707–711return ( '<div class="flow-overview"><p class="ov-h">Overview · ' f"{plural(len(flow.steps), 'step')}, {plural(len(flow.lanes), 'lane')}</p>" f'<ol class="segments">{"".join(rows)}</ol></div>' )

Flows

_preface

str clew.wiki.flowpage._preface(Any spec, bool scenario_shown=False)

A flow's declared intent, scenario and worked example, in reading order.

clew/wiki/flowpage.py:589

Show on the map →

Called by flow_page, test_a_declared_scenario_is_drawn_once_as_the_overview, test_the_preface_shows_intent_then_scenario_then_example

Calls gherkin

Source · 22 lines
def _preface(spec: Any, scenario_shown: bool = False) -> str:
    """W-1/W-5 (owner review 2026-11-22): the abstract first — what the flow is for — then its
    Gherkin scenario, always shown, then the example. Declared text only; escaped.

    @brief Flow preface.
    @return HTML.
    """
    parts = []
    if spec.intent:
        parts.append(f'<p class="intent">{escape(spec.intent)}</p>')
    ## A-1: an anchored scenario is drawn once, as the overview (`scenario_shown`).
    if spec.scenario and not scenario_shown:
        parts.append(gherkin(spec.scenario))
    if spec.example:
        given, got = spec.example
        parts.append(
            '<div class="example"><p class="ex-h">Worked example</p>'
            f'<pre class="ex-in">{escape(given)}</pre><pre class="ex-out">{escape(got)}</pre></div>'
        )
    return f'<div class="flow-preface">{"".join(parts)}</div>' if parts else ""

Activity · 9 steps
lines 596–596parts = []lines 597–597◇ if spec.intentlines 598–598parts.append(f'<p class="intent">{escape(spec.intent)}</p>')lines 600–600◇ if spec.scenario and not scenario_shownlines 601–601parts.append(gherkin(spec.scenario))lines 602–602◇ if spec.examplelines 603–603given, got = spec.examplelines 604–607parts.append( '<div class="example"><p class="ex-h">Worked example</p>' f'<pre class="ex-in">{escape(given)}</pre><pre class="ex-out">{escape(got)}</pre></div>' )lines 608–608return f'<div class="flow-preface">{"".join(parts)}</div>' if parts else ""

Flows

_segment_row

str clew.wiki.flowpage._segment_row(Any flow, int i, int end, str text, bool keyword)

One overview row: its words, then its step span and the lanes it touches.

clew/wiki/flowpage.py:723

Source · 16 lines
def _segment_row(flow: Any, i: int, end: int, text: str, keyword: bool) -> str:
    """@brief Segment row. @return HTML."""
    lanes = list(
        dict.fromkeys(x for s in flow.steps[i : end + 1] for x in (s.from_lane, s.to_lane))
    )
    shown = ", ".join(escape(x) for x in lanes[:3]) + (
        f" +{len(lanes) - 3}" if len(lanes) > 3 else ""
    )
    span = f"step {i + 1}" if end == i else f"steps {i + 1}–{end + 1}"
    words = _keyword(text) if keyword else escape(text)
    return (
        f'<li data-goto="{i}"><button type="button" class="seg-go">{words}</button>'
        f'<span class="seg-meta">{span} · {shown}</span></li>'
    )

Activity · 5 steps
lines 725–727lanes = list( dict.fromkeys(x for s in flow.steps[i : end + 1] for x in (s.from_lane, s.to_lane)) )lines 728–730shown = ", ".join(escape(x) for x in lanes[:3]) + ( f" +{len(lanes) - 3}" if len(lanes) > 3 else "" )lines 731–731span = f"step {i + 1}" if end == i else f"steps {i + 1}–{end + 1}"lines 732–732words = _keyword(text) if keyword else escape(text)lines 733–736return ( f'<li data-goto="{i}"><button type="button" class="seg-go">{words}</button>' f'<span class="seg-meta">{span} · {shown}</span></li>' )

Flows

_segments

dict[int, str] clew.wiki.flowpage._segments(Any spec, Any flow)

Where each anchored scenario line begins in a flow: step index → the line.

clew/wiki/flowpage.py:617

Show on the map →

Called by flow_page, test_the_scenario_is_drawn_as_bands_in_the_diagram

Calls none

Source · 21 lines
def _segments(spec: Any, flow: Any) -> dict[int, str]:
    """X-1 (owner 2026-11-22): an anchored line begins at the first step, searching forward from
    the previous anchor, whose callee its `at` names; an anchor the flow never reaches draws nothing.
    The segments are drawn IN the diagram as bands — the story list that duplicated the step table
    is gone (owner: "a no").

    @brief Segment starts.
    @return Map.
    """
    out: dict[int, str] = {}
    cursor = 0
    for line, at in zip(spec.scenario or (), spec.scenario_at or ()):
        hit = next(
            (i for i in range(cursor, len(flow.steps)) if at and flow.steps[i].callee == at), None
        )
        if hit is not None:
            out[hit] = line
            cursor = hit
    return out

Activity · 8 steps
lines 626–626out: dict[int, str] = {}lines 627–627cursor = 0lines 628–628◇ for line, at in zip(spec.scenario or (), spec.scenario_at or ())lines 629–631hit = next( (i for i in range(cursor, len(flow.steps)) if at and flow.steps[i].callee == at), None )lines 632–632◇ if hit is not Nonelines 633–633out[hit] = linelines 634–634cursor = hitlines 635–635return out

Flows

_signatures

dict[tuple[str, str], tuple[str, str]] clew.wiki.flowpage._signatures(Path db, Flow flow)

The callee signatures and briefs of a flow's steps.

clew/wiki/flowpage.py:560

Source · 23 lines
def _signatures(db: Path, flow: Flow) -> dict[tuple[str, str], tuple[str, str]]:
    """@brief Read signatures. @return Map."""
    from ..query._common import connect, identity_rowids

    out: dict[tuple[str, str], tuple[str, str]] = {}
    with connect(db) as conn:
        for step in flow.steps:
            key = (step.callee, step.callee_qualified)
            if key in out or not step.callee_qualified:
                continue
            rowids = identity_rowids(conn, step.callee, step.callee_qualified)
            if not rowids:
                continue
            row = conn.execute(
                "SELECT definition, argsstring, briefdescription FROM memberdef WHERE rowid = ?",
                (min(rowids),),
            ).fetchone()
            if row:
                brief = " ".join(re.sub(r"<[^>]+>", " ", str(row[2] or "")).split())
                out[key] = (f"{row[0] or ''}{row[1] or ''}".strip(), brief)
    return out

Activity · 15 steps
lines 562–562from ..query._common import connect, identity_rowidslines 564–564out: dict[tuple[str, str], tuple[str, str]] = {}lines 565–565with connect(db) as connlines 566–566◇ for step in flow.stepslines 567–567key = (step.callee, step.callee_qualified)lines 568–568◇ if key in out or not step.callee_qualifiedlines 569–569continuelines 570–570rowids = identity_rowids(conn, step.callee, step.callee_qualified)lines 571–571◇ if not rowidslines 572–572continuelines 573–576row = conn.execute( "SELECT definition, argsstring, briefdescription FROM memberdef WHERE rowid = ?", (min(rowids),), ).fetchone()lines 577–577◇ if rowlines 578–578brief = " ".join(re.sub(r"<[^>]+>", " ", str(row[2] or "")).split())lines 579–579out[key] = (f"{row[0] or ''}{row[1] or ''}".strip(), brief)lines 580–580return out

Flows

_site_cell

str clew.wiki.flowpage._site_cell(Any step, dict[str, Any] row)

A step row's call-site cell: a link to the line, plain text, or nothing for a stub.

clew/wiki/flowpage.py:756

Source · 14 lines
def _site_cell(step: Any, row: dict[str, Any]) -> str:
    """W-8 (owner review 2026-11-22): a not-run stub stands for several calls, so it names no line
    (it showed `clew/cli.py:0`).

    @brief Call-site cell.
    @return HTML.
    """
    if step.not_run:
        return ""
    if row["link"]:
        return f'<a href="{escape(row["link"])}">{escape(row["site"])}</a>'
    return code(row["site"])

Activity · 5 steps
lines 763–763◇ if step.not_runlines 764–764return ""lines 765–765◇ if row["link"]lines 766–766return f'<a href="{escape(row["link"])}">{escape(row["site"])}</a>'lines 767–767return code(row["site"])

Flows

_top_segments

dict[int, str] clew.wiki.flowpage._top_segments(Any flow, list[dict[str, Any]] data)

The overview's segments when none is declared: the entry's top-level calls.

clew/wiki/flowpage.py:644

Show on the map →

Called by flow_page, test_a_flow_page_opens_on_its_overview_and_folds_the_detail

Calls _message_of

Source · 21 lines
def _top_segments(flow: Any, data: list[dict[str, Any]]) -> dict[int, str]:
    """A-1 (UX review, owner Q/A 2026-11-22). Measured on clew's flows: 1-11 top-level calls each.
    One top-level call says nothing, so the overview goes one level down until there are two.

    @brief Derived segments.
    @return Map.
    """
    depths = sorted({s.depth for s in flow.steps})
    heads: list[int] = []
    for level in depths:
        heads = [i for i, s in enumerate(flow.steps) if s.depth == level]
        if len(heads) > 1:
            break
    out = {}
    for i in heads:
        step, brief = flow.steps[i], (data[i].get("brief") or "") if i < len(data) else ""
        name = step.callee or _message_of(step)
        out[i] = f"{name} — {brief}" if brief else name
    return out

Activity · 12 steps
lines 651–651depths = sorted({s.depth for s in flow.steps})lines 652–652heads: list[int] = []lines 653–653◇ for level in depthslines 654–654heads = [i for i, s in enumerate(flow.steps) if s.depth == level]lines 655–655◇ if len(heads) > 1lines 656–656breaklines 657–657out = {}lines 658–658◇ for i in headslines 659–659step, brief = flow.steps[i], (data[i].get("brief") or "") if i < len(data) else ""lines 660–660name = step.callee or _message_of(step)lines 661–661out[i] = f"{name} — {brief}" if brief else namelines 662–662return out

Flows

flow_page

FlowPage clew.wiki.flowpage.flow_page(Path repo_root, Path db, FlowSpec spec, Path source, Audience rules, WikiConfig config, str commit, dict[tuple[str, str], list[str]]|None req_of=None, tuple[str, dict[str, Any]]|None trace=None, dict[str, dict[int, set[str]]]|None coverage=None, dict[str, str]|None blocks=None, str actor="")

Write one flow's page.

clew/wiki/flowpage.py:228

Source · 120 lines
def flow_page(
    repo_root: Path,
    db: Path,
    spec: FlowSpec,
    source: Path,
    rules: Audience,
    config: WikiConfig,
    commit: str,
    req_of: dict[tuple[str, str], list[str]] | None = None,
    trace: tuple[str, dict[str, Any]] | None = None,
    coverage: dict[str, dict[int, set[str]]] | None = None,
    blocks: dict[str, str] | None = None,
    actor: str = "",
) -> FlowPage:
    """THE STEP TABLE LINKS THE CALL SITE — the caller's file at the call's line (`site_file`),
    not the callee's file. The table drops a column no step fills.

    @brief Render one flow page.
    @return The page.
    """
    executed = _executed(coverage) if coverage is not None and spec.role != "tests" else None
    flow = derive_flow(
        db,
        repo_root,
        spec.entry,
        qualified=spec.qualified,
        depth=spec.depth,
        lanes=spec.lanes,
        stop_at=spec.stop_at,
        file=spec.file,
        executed=executed,
        ## R5-CFG C1/C2 (2.0.0): the flow's own values, else the site's; both apply only to a
        ## MEASURED flow (an unmeasured one is bounded by its depth, as before).
        max_steps=(spec.max_steps or config.measured_steps) if executed is not None else None,
        measured_depth=spec.measured_depth or config.measured_depth,
        ## P5.6 (owner, round 5): block lanes and the actor.
        blocks=blocks,
        actor=actor,
    )
    slices = slices_of(flow, coverage) if coverage is not None and spec.role != "tests" else {}
    ## UX review A-2 (owner Q/A 2026-11-22): the DIAGRAM's lanes are chosen per flow; the exports
    ## and `clew wiki flow` keep derive_flow's.
    drawn = per_flow_lanes(flow)
    name = page_name(spec)
    data = step_data(db, repo_root, flow, rules, config.link_template, commit)
    ## P5.6, REPLAY WITH VALUES: a recorded run gives each step it confirmed its values.
    if trace is not None:
        data = with_values(data, trace[1], rules)
    declared = _segments(spec, flow)
    lines = [
        f"# {spec.title or 'Flow: ' + spec.entry}",
        "",
        "```{raw} html",
        ## W-1/W-5: what the flow is for, its scenario and a worked example, above the diagram.
        _preface(spec, scenario_shown=bool(declared)),
        ## A-1 (UX review, owner Q/A 2026-11-22): the overview, then the diagram in its own box.
        _overview(drawn, declared or _top_segments(drawn, data), spec.scenario if declared else ()),
        _block(drawn, data, spec.animate, test_node(spec), declared),
        "```",
        "",
    ]
    rows = []
    for i, (step, row) in enumerate(zip(flow.steps, data, strict=True), start=1):
        site = _site_cell(step, row)
        reqs = _badges((req_of or {}).get((step.callee, step.file), ()))
        callee = f'<a href="{escape(symbol_href(step.callee, step.file))}">{code(step.callee)}</a>'
        if step.not_run:
            callee = f'<span class="nr">… {step.not_run} not run</span>'
        ## X-1: what the step does, in the table that already lists the steps.
        what = escape(row.get("brief") or "")
        rows.append([str(i), code(step.caller), callee, what, reqs, escape(row["frames"]), site])
    head = ["#", "caller", "callee", "what it does", "requirements", "frames", "call site"]
    ## P5.6, LIVE SYNC: each row names its step, so the page script can light it as the diagram plays.
    marks = [f' data-step="{i}"' for i in range(len(rows))]
    steps_table = table(head, rows, cls="steps", numeric=("#",), row_attrs=marks)
    ## A-1: the step table folds under its count (live sync still lights its rows).
    steps_table = (
        f'<details class="fold steps-fold"><summary>All {plural(len(rows), "step")}</summary>'
        f"{steps_table}</details>"
    )
    lines += ["```{raw} html", steps_table, "```", ""]
    if trace is not None:
        lines += ["```{raw} html", imported_trace(flow, *trace), "```", ""]
    if slices:
        payload = json.dumps(
            {t: list(c.exercised) for t, c in slices.items()}, separators=(",", ":")
        )
        payload = payload.replace("</", "<\\/")
        lines += [
            "```{raw} html",
            f'<script type="application/json" id="flow-slices">{payload}</script>',
            "```",
            "",
        ]
    files = {s.file for s in flow.steps} | {s.site_file for s in flow.steps if s.site_file}
    hops = tuple((s.site_file, s.file) for s in flow.steps if s.site_file and s.callee)
    functions = {(s.callee, s.file) for s in flow.steps if s.callee} | {
        (s.caller, s.site_file) for s in flow.steps if s.site_file
    }
    lines += _functions(functions)
    lines += _diagram_exports(flow, source, name)
    (source / f"{name}.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
    title = spec.title or "Flow: " + spec.entry
    reqs = frozenset(r for f in functions for r in (req_of or {}).get(f, ()))
    calls = tuple((s.caller, s.callee) for s in flow.steps if s.callee)
    return FlowPage(
        name,
        title,
        frozenset(files),
        hops,
        frozenset(functions),
        spec.role,
        len(flow.steps),
        reqs,
        calls,
        ## A-2: test pages draw their slices on the same lanes as this page.
        drawn,
        slices,
        spec.intent,
    )

2 more lines, not shown

Activity · 40 steps
lines 248–248executed = _executed(coverage) if coverage is not None and spec.role != "tests" else Nonelines 249–266flow = derive_flow( db, repo_root, spec.entry, qualified=spec.qualified, depth=spec.depth, lanes=spec.lanes, stop_at=spec.stop_at, file=spec.file, executed=executed, ## R5-CFG C1/C2 (2.0.0): the flow's own values, else the site's; both apply only to a ## MEASURED flow (an unmeasured one is bounded by its depth, as before). max_steps=(spec.max_steps or config.measured_steps) if executed is not None else None, measured_depth=spec.measured_depth or config.measured_depth, ## P5.6 (owner, round 5): block lanes and the actor. blocks=blocks, actor=actor, )lines 267–267slices = slices_of(flow, coverage) if coverage is not None and spec.role != "tests" else {}lines 270–270drawn = per_flow_lanes(flow)lines 271–271name = page_name(spec)lines 272–272data = step_data(db, repo_root, flow, rules, config.link_template, commit)lines 274–274◇ if trace is not Nonelines 275–275data = with_values(data, trace[1], rules)lines 276–276declared = _segments(spec, flow)lines 277–288lines = [ f"# {spec.title or 'Flow: ' + spec.entry}", "", "```{raw} html", ## W-1/W-5: what the flow is for, its scenario and a worked example, above the diagram. _preface(spec, scenario_shown=bool(declared)), ## A-1 (UX review, owner Q/A 2026-11-22): the overview, then the diagram in its own box. _overview(drawn, declared or _top_segments(drawn, data), spec.scenario if declared else ()), _block(drawn, data, spec.animate, test_node(spec), declared), "```", "", ]lines 289–289rows = []lines 290–290◇ for i, (step, row) in enumerate(zip(flow.steps, data, strict=True), start=1)lines 291–291site = _site_cell(step, row)lines 292–292reqs = _badges((req_of or {}).get((step.callee, step.file), ()))lines 293–293callee = f'<a href="{escape(symbol_href(step.callee, step.file))}">{code(step.callee)}</a>'lines 294–294◇ if step.not_runlines 295–295callee = f'<span class="nr">… {step.not_run} not run</span>'lines 297–297what = escape(row.get("brief") or "")lines 298–298rows.append([str(i), code(step.caller), callee, what, reqs, escape(row["frames"]), site])lines 299–299head = ["#", "caller", "callee", "what it does", "requirements", "frames", "call site"]lines 301–301marks = [f' data-step="{i}"' for i in range(len(rows))]lines 302–302steps_table = table(head, rows, cls="steps", numeric=("#",), row_attrs=marks)lines 304–307steps_table = ( f'<details class="fold steps-fold"><summary>All {plural(len(rows), "step")}</summary>' f"{steps_table}</details>" )lines 308–308lines += ["```{raw} html", steps_table, "```", ""]lines 309–309◇ if trace is not Nonelines 310–310lines += ["```{raw} html", imported_trace(flow, *trace), "```", ""]lines 311–311◇ if sliceslines 312–314payload = json.dumps( {t: list(c.exercised) for t, c in slices.items()}, separators=(",", ":") )lines 315–315payload = payload.replace("</", "<\\/")lines 316–321lines += [ "```{raw} html", f'<script type="application/json" id="flow-slices">{payload}</script>', "```", "", ]lines 322–322files = {s.file for s in flow.steps} | {s.site_file for s in flow.steps if s.site_file}lines 323–323hops = tuple((s.site_file, s.file) for s in flow.steps if s.site_file and s.callee)lines 324–326functions = {(s.callee, s.file) for s in flow.steps if s.callee} | { (s.caller, s.site_file) for s in flow.steps if s.site_file }lines 327–327lines += _functions(functions)lines 328–328lines += _diagram_exports(flow, source, name)lines 329–329(source / f"{name}.md").write_text("\n".join(lines) + "\n", encoding="utf-8")lines 330–330title = spec.title or "Flow: " + spec.entrylines 331–331reqs = frozenset(r for f in functions for r in (req_of or {}).get(f, ()))lines 332–332calls = tuple((s.caller, s.callee) for s in flow.steps if s.callee)lines 333–347return FlowPage( name, title, frozenset(files), hops, frozenset(functions), spec.role, len(flow.steps), reqs, calls, ## A-2: test pages draw their slices on the same lanes as this page. drawn, slices, spec.intent, )

Requirements

REQ-DDB-WIKI-014 REQ-DDB-WIKI-041 REQ-DDB-WIKI-050

Flows

flows_index

str clew.wiki.flowpage.flows_index(Path source, list[FlowPage] pages, tuple unmatched=(), tuple not_drawn=())

The Flows page: flows grouped by role, tooling folded away.

clew/wiki/flowpage.py:882

Show on the map →

Called by _build_site

Calls _role_block

Source · 43 lines
def flows_index(
    source: Path,
    pages: list[FlowPage],
    unmatched: tuple = (),
    not_drawn: tuple = (),
) -> str:
    """OWNER 2026-11-15: the product's flows first — console scripts, declared roots, mains
    outside tooling — then thread entries, then tooling (scripts, harnesses) folded. A role
    with no flow has no section.

    @brief Write flows.md.
    @return Page name.
    """
    if not pages and not not_drawn:
        return ""
    lines = ["# Flows", "", _FLOWS_LEAD, ""]
    for role, heading, lead in _ROLES:
        members = sorted((p for p in pages if (p.role or "product") == role), key=lambda p: p.title)
        if members:
            lines += [
                f"## {heading}",
                "",
                lead,
                "",
                "```{raw} html",
                _role_block(role, members),
                "```",
                "",
            ]
    if unmatched:
        lines += ["Imported traces whose test has no flow here:", ""]
        lines += [f"- `{rel}` — root `{root}`" for rel, root in unmatched]
        lines.append("")
    if not_drawn:
        lines += ["Entry points found but not drawn:", ""]
        lines += [f"- `{e}` (`{f}`) — not drawn: {r}" for e, f, r in not_drawn]
        lines.append("")
    names = [p.name for p in pages]
    lines += ["```{toctree}", ":hidden:", ":maxdepth: 1", "", *names, "```", ""]
    (Path(source) / "flows.md").write_text("\n".join(lines), encoding="utf-8")
    return "flows"

Activity · 19 steps
lines 895–895◇ if not pages and not not_drawnlines 896–896return ""lines 897–897lines = ["# Flows", "", _FLOWS_LEAD, ""]lines 898–898◇ for role, heading, lead in _ROLESlines 899–899members = sorted((p for p in pages if (p.role or "product") == role), key=lambda p: p.title)lines 900–900◇ if memberslines 901–910lines += [ f"## {heading}", "", lead, "", "```{raw} html", _role_block(role, members), "```", "", ]lines 911–911◇ if unmatchedlines 912–912lines += ["Imported traces whose test has no flow here:", ""]lines 913–913lines += [f"- `{rel}` — root `{root}`" for rel, root in unmatched]lines 914–914lines.append("")lines 915–915◇ if not_drawnlines 916–916lines += ["Entry points found but not drawn:", ""]lines 917–917lines += [f"- `{e}` (`{f}`) — not drawn: {r}" for e, f, r in not_drawn]lines 918–918lines.append("")lines 919–919names = [p.name for p in pages]lines 920–920lines += ["```{toctree}", ":hidden:", ":maxdepth: 1", "", *names, "```", ""]lines 921–921(Path(source) / "flows.md").write_text("\n".join(lines), encoding="utf-8")lines 922–922return "flows"

Requirements

REQ-DDB-WIKI-023

imported_trace

str clew.wiki.flowpage.imported_trace(Flow flow, str rel, dict[str, Any] otlp)

An imported trace drawn over the flow: per-step CSS and a panel saying what it found.

clew/wiki/flowpage.py:358

Source · 43 lines
def imported_trace(flow: Flow, rel: str, otlp: dict[str, Any]) -> str:
    """STATIC, so a published site carries it: each predicted step is styled CONFIRMED or dimmed
    as NOT EXECUTED by a CSS rule on its `data-step`; discovered calls and the failure are listed.

    @brief Imported trace overlay.
    @return HTML.
    """
    from .tracerun import failure_of, overlay

    result = overlay([(s.caller, s.callee) for s in flow.steps], otlp)
    rules = "".join(
        f'svg.seq g[data-step="{i}"]{{opacity:.25}}'
        if state != "confirmed"
        else f'svg.seq g[data-step="{i}"] line{{stroke:#3D6B2E;stroke-width:3}}'
        for i, state in enumerate(result["steps"])
    )
    confirmed = result["steps"].count("confirmed")
    lines = [
        f"Imported trace <code>{escape(rel)}</code>: {confirmed} of {len(result['steps'])} "
        "predicted steps confirmed; the rest are dimmed."
    ]
    found = [
        f"<li><code>{escape(a)}</code> → <code>{escape(b)}</code></li>"
        for a, b in result["discovered"]
    ]
    failed = failure_of(otlp)
    if failed:
        where = f" at line {escape(failed['line'])}" if failed["line"] else ""
        lines.append(
            f'<span class="bad">Failed in <code>{escape(failed["span"])}</code>{where}: '
            f"{escape(failed['message'])}</span>"
        )
    body = "".join(f"<p>{line}</p>" for line in lines)
    ## A-1 (UX review, owner Q/A 2026-11-22): what the run discovered folds under its count
    ## (5,777 px on clew's dossier flow); the summary and any failure stay in view.
    if found:
        body += (
            f'<details class="fold"><summary>{plural(len(found), "discovered call")} not in the '
            f"flow</summary><ul>{''.join(found)}</ul></details>"
        )
    return f'<style>{rules}</style><div class="trace-panel imported">{body}</div>'

Activity · 14 steps
lines 365–365from .tracerun import failure_of, overlaylines 367–367result = overlay([(s.caller, s.callee) for s in flow.steps], otlp)lines 368–373rules = "".join( f'svg.seq g[data-step="{i}"]{{opacity:.25}}' if state != "confirmed" else f'svg.seq g[data-step="{i}"] line{{stroke:#3D6B2E;stroke-width:3}}' for i, state in enumerate(result["steps"]) )lines 374–374confirmed = result["steps"].count("confirmed")lines 375–378lines = [ f"Imported trace <code>{escape(rel)}</code>: {confirmed} of {len(result['steps'])} " "predicted steps confirmed; the rest are dimmed." ]lines 379–382found = [ f"<li><code>{escape(a)}</code> → <code>{escape(b)}</code></li>" for a, b in result["discovered"] ]lines 383–383failed = failure_of(otlp)lines 384–384◇ if failedlines 385–385where = f" at line {escape(failed['line'])}" if failed["line"] else ""lines 386–389lines.append( f'<span class="bad">Failed in <code>{escape(failed["span"])}</code>{where}: ' f"{escape(failed['message'])}</span>" )lines 390–390body = "".join(f"<p>{line}</p>" for line in lines)lines 393–393◇ if foundlines 394–397body += ( f'<details class="fold"><summary>{plural(len(found), "discovered call")} not in the ' f"flow</summary><ul>{''.join(found)}</ul></details>" )lines 398–398return f'<style>{rules}</style><div class="trace-panel imported">{body}</div>'

Requirements

REQ-DDB-WIKI-036

Flows

page_name

str clew.wiki.flowpage.page_name(FlowSpec spec)

A flow's page name: the entry, and its file when the flow selects one.

clew/wiki/flowpage.py:416

Show on the map →

Called by _flow_page, flow_page

Calls none

Source · 8 lines
def page_name(spec: FlowSpec) -> str:
    """@brief Name a page. @return Name."""
    import re

    suffix = "-" + re.sub(r"[^A-Za-z0-9]+", "-", spec.file).strip("-") if spec.file else ""
    return f"flow-{spec.entry}{suffix}"

Activity · 3 steps
lines 418–418import relines 420–420suffix = "-" + re.sub(r"[^A-Za-z0-9]+", "-", spec.file).strip("-") if spec.file else ""lines 421–421return f"flow-{spec.entry}{suffix}"

Flows

step_data

list[dict[str, Any]] clew.wiki.flowpage.step_data(Path db, Path repo_root, Flow flow, Audience rules, str template, str commit)

The data each step carries, for its dialog.

clew/wiki/flowpage.py:435

Source · 27 lines
def step_data(
    db: Path, repo_root: Path, flow: Flow, rules: Audience, template: str, commit: str
) -> list[dict[str, Any]]:
    """@brief Gather step data. @return Rows."""
    signatures = _signatures(db, flow)
    out = []
    for step in flow.steps:
        site = step.site_file or step.file
        link = source_url(template, commit, site, step.line)
        sig, brief = signatures.get((step.callee, step.callee_qualified), ("", ""))
        out.append(
            {
                "caller": step.caller,
                "callee": step.callee,
                "callee_qualified": step.callee_qualified,
                "call": "" if rules.exclude_bodies else _call_text(repo_root, site, step.line),
                "signature": sig,
                "brief": brief,
                "frames": ", ".join(f"{f.kind} (line {f.line})" for f in step.frames),
                "ambiguous": ", ".join(step.ambiguous),
                "site": f"{site}:{step.line}",
                "link": link,
            }
        )
    return out

Activity · 8 steps
lines 439–439signatures = _signatures(db, flow)lines 440–440out = []lines 441–441◇ for step in flow.stepslines 442–442site = step.site_file or step.filelines 443–443link = source_url(template, commit, site, step.line)lines 444–444sig, brief = signatures.get((step.callee, step.callee_qualified), ("", ""))lines 445–458out.append( { "caller": step.caller, "callee": step.callee, "callee_qualified": step.callee_qualified, "call": "" if rules.exclude_bodies else _call_text(repo_root, site, step.line), "signature": sig, "brief": brief, "frames": ", ".join(f"{f.kind} (line {f.line})" for f in step.frames), "ambiguous": ", ".join(step.ambiguous), "site": f"{site}:{step.line}", "link": link, } )lines 459–459return out

Requirements

REQ-DDB-WIKI-014

Flows

test_node

str clew.wiki.flowpage.test_node(FlowSpec spec)

A test flow's pytest node id, or "" for any other flow.

clew/wiki/flowpage.py:406

Source · 5 lines
def test_node(spec: FlowSpec) -> str:
    """@brief Node id. @return Text."""
    return f"{spec.file}::{spec.entry}" if spec.role == "tests" and spec.file else ""

Activity · 1 steps
lines 408–408return f"{spec.file}::{spec.entry}" if spec.role == "tests" and spec.file else ""

Requirements

REQ-DDB-WIKI-035

Flows

with_values

list[dict[str, Any]] clew.wiki.flowpage.with_values(list[dict[str, Any]] data, dict[str, Any] otlp, Audience rules)

Step data with each confirmed step's recorded values (replay with values, P5.6).

clew/wiki/flowpage.py:469

Source · 20 lines
def with_values(
    data: list[dict[str, Any]], otlp: dict[str, Any], rules: Audience
) -> list[dict[str, Any]]:
    """RUNTIME DATA IS WITHHELD WITH THE BODIES: an audience that may not see source does not see
    the values it computed either.

    @brief Merge values.
    @return Rows.
    """
    if rules.exclude_bodies:
        return data
    from .tracerun import overlay

    values = overlay([(r["caller"], r["callee"]) for r in data], otlp)["values"]
    return [
        {**row, "called_with": v["args"], "returned": v["return"]} if v else row
        for row, v in zip(data, values, strict=True)
    ]

Activity · 5 steps
lines 478–478◇ if rules.exclude_bodieslines 479–479return datalines 480–480from .tracerun import overlaylines 482–482values = overlay([(r["caller"], r["callee"]) for r in data], otlp)["values"]lines 483–486return [ {**row, "called_with": v["args"], "returned": v["return"]} if v else row for row, v in zip(data, values, strict=True) ]

Requirements

REQ-DDB-WIKI-049

Flows