build.py¶
clew/wiki/build.py
`clew wiki build`: a self-contained static site, rendered by Sphinx + MyST.
_actor_of
str clew.wiki.build._actor_of(Any spec, WikiConfig config)
Who starts a flow, for its actor lane (P5.6).
Source · 17 lines
def _actor_of(spec: Any, config: WikiConfig) -> str:
"""FROM WHERE THE SPEC CAME: a test flow is started by the test runner, a thread entry by its
thread, a console script (title `script — `func``) by a command-line user, a discovered `main`
by a program launcher; a flow the repository declares by its caller.
@brief Actor of a flow.
@return Name.
"""
if spec.role == "tests":
return "test runner"
if spec.role == "threads":
return "thread start"
if spec in config.flows:
return "caller"
return "command-line user" if " — " in (spec.title or "") else "program launcher"
Activity · 7 steps
Requirements
Flows
_all_flows
list clew.wiki.build._all_flows(Path repo_root, Path db, WikiConfig config)
The declared flows, then every entry point's flow not already declared.
Source · 20 lines
def _all_flows(repo_root: Path, db: Path, config: WikiConfig) -> list:
"""A DECLARED FLOW WINS for its function: its title, depth and lanes are the repository's
choice, so the derived one for the same entry is dropped.
@brief Declared + entry-point flows.
@return Specs.
"""
from .entrypoints import entry_point_flows
specs = list(config.flows)
if config.entry_point_depth > 0:
declared = {(s.entry, s.file) for s in specs} | {(s.entry, None) for s in specs}
specs += [
s
for s in entry_point_flows(db, repo_root, config.entry_point_depth)
if (s.entry, s.file) not in declared and (s.entry, None) not in declared
]
return specs
Activity · 6 steps
Flows
_architecture_entries
list clew.wiki.build._architecture_entries(Path db, Path repo_root, WikiConfig config, dict flow_of)
The entry points, as the Architecture page reads them.
Source · 24 lines
def _architecture_entries(db: Path, repo_root: Path, config: WikiConfig, flow_of: dict) -> list:
"""THE KIND FROM THE DISCOVERY that found it: a console script's title is `script — `func``,
a thread entry carries the `threads` role, anything else is a `main`.
@brief Classify entry points.
@return Entries.
"""
from .architecture import Entry
from .entrypoints import entry_point_flows
out = []
for spec in entry_point_flows(db, repo_root, config.entry_point_depth):
if spec.role == "threads":
kind, label = "thread", ""
elif " — " in spec.title:
kind, label = "script", spec.title.split(" — ", 1)[0]
else:
kind, label = "main", ""
## THE SAME ROLE THE FLOWS GET (`_with_role`): a `tooling`-glob entry is not a container.
role = _with_role(spec, config).role
out.append(Entry(kind, spec.entry, spec.file or "", label, flow_of.get(spec.entry), role))
return out
Activity · 13 steps
Requirements
_audience
Audience clew.wiki.build._audience(WikiConfig config, str|None audience)
The rules for the requested audience.
Source · 10 lines
def _audience(config: WikiConfig, audience: str | None) -> Audience:
"""@brief Resolve an audience. @return Rules."""
if audience is None:
return Audience()
if audience not in config.audiences:
known = ", ".join(sorted(config.audiences)) or "none declared"
raise ValueError(f"unknown audience {audience!r} (known: {known})")
return config.audiences[audience]
Activity · 6 steps
Flows
_build_site
Path clew.wiki.build._build_site(Path repo_root, Path db, Path out_dir, str|None audience=None, str|None version=None, Path|None config_path=None, Path|None summary=None)
Write and render the site.
Called by build_wiki
Calls _actor_of, _all_flows, _architecture_entries, _audience, _burndown, _commit, _coverage, _docs_page, _fetch_issues, _issues_into, _lines_by_test, _lit 39 more
_milestones, _product_section, _prose, _render, _requirements_of, _slices_by_test, _test_flows, _test_results, _with_role, _write_ci_summary, _write_index, api_pages, architecture_page, build_graph, commit_published, feature_pages, find_decisions, flow_page, flows_index, gather, impact_page, load_traces, load_wiki_config, minimap_html, nodes_page, parse_features, parse_junit, record_version, requirements_page, root_name, sbom_page, symbol_pages, test_pages, tests_index, trace_for, valid_key, web_page, write_exports, write_quick_views
Source · 120 lines
def _build_site(
repo_root: Path,
db: Path,
out_dir: Path,
audience: str | None = None,
version: str | None = None,
config_path: Path | None = None,
summary: Path | None = None,
) -> Path:
"""REFUSES rather than degrades: an invalid section, an unknown audience or a missing extra is
an error naming itself, never a partial site that looks complete.
@brief Write and render the site.
@return The HTML directory.
@version 1
"""
from .architecture import architecture_page
from .flowpage import flow_page, flows_index
from .impactpage import impact_page
from .graph import build_graph
from .issues import resolve_target
from .web import minimap_html, web_page
from . import testfacts
from .imports import parse_features
from .adr import find_decisions
from .exports import write_exports
from .tracerun import load_traces, root_name, trace_for
from .symbols import symbol_pages
from .testpages import test_pages
from .evidence import parse_junit
from .tracepages import Trace, nodes_page, requirements_page
from .versions import record_version, valid_key
repo_root, out_dir = Path(repo_root), Path(out_dir)
config, problems = load_wiki_config(repo_root, config_path)
if problems:
raise ValueError("wiki configuration problems: " + "; ".join(problems))
rules = _audience(config, audience)
site_dir = out_dir / valid_key(version) if version else out_dir
source = site_dir / "_source"
if source.exists():
shutil.rmtree(source)
source.mkdir(parents=True)
commit = _commit(repo_root)
if commit_published(repo_root, commit) is False:
config = dataclasses.replace(config, link_template="")
trace = Trace.gather(repo_root, db, config, commit)
snapshot = trace.snapshot(version or "")
milestones = _milestones(repo_root, config)
burndown = _burndown(out_dir, version, snapshot, milestones) if version else ""
req_of = _requirements_of(trace.evidence)
facts = testfacts.gather(trace.evidence)
traces = {
root_name(otlp): (rel, otlp) for rel, otlp in load_traces(repo_root, config.inputs.traces)
}
test_specs = _test_flows(db, facts, frozenset(traces), config.trace_depth)
specs = [*_all_flows(repo_root, db, config), *test_specs]
coverage = _coverage(repo_root, config)
## P5.6: THE GRAPH BEFORE THE FLOWS, so a flow's block lanes are the map's blocks.
graph = build_graph(
db,
trace.evidence,
trace.impact,
config.components,
exclude_tests=True,
component_depth=config.component_depth,
)
blocks = graph.get("file_block") or {}
pages, not_drawn, flow_of = [], [], {}
for s in specs:
try:
pages.append(
flow_page(
repo_root,
db,
_with_role(s, config),
source,
rules,
config,
commit,
req_of,
## X-2: a master flow takes the subtree a traced test reached under it.
trace_for(s.entry, traces),
coverage,
blocks,
_actor_of(s, config),
)
)
flow_of.setdefault(s.entry, pages[-1].name)
except ValueError as refused:
## Round 4: a DISCOVERED flow that cannot be drawn is listed with its reason; a
## DECLARED one is the repository's own statement and still fails the build.
if s in config.flows:
raise
not_drawn.append((s.entry, s.file or "", str(refused)))
unmatched = tuple(
(rel, root)
for root, (rel, _o) in sorted(traces.items())
if root not in {s.entry for s in specs}
)
keys = {(n, f) for r in trace.evidence for n, f, _l in r.implementer_sites}
keys |= {fn for p in pages for fn in p.functions}
symbol_ctx = {
## V6 (owner Q/A 2026-11-20): how many body lines a symbol page bundles.
"body_lines": config.body_lines,
"req_of": req_of,
"flows": pages,
"rules": rules,
"template": config.link_template,
## R5-CFG C3 (2.0.0): ONE test → implementer path depth for the symbol and test pages.
"path_depth": config.path_depth,
"commit": commit,
"tests": facts,
"implementers": {
r.req_id: {(n, f) for n, f, _l in r.implementer_sites} for r in trace.evidence
},
}
written = symbol_pages(db, repo_root, keys, symbol_ctx, source)
scenarios = parse_features(repo_root, config.inputs.features)
written |= testfacts.feature_pages(repo_root, scenarios, facts, source)120 more lines, not shown
Activity · 90 steps
Flows
_burndown
str clew.wiki.build._burndown(Path out_dir, str version, dict snapshot, list milestones)
The burndown for a versioned build: earlier recorded versions, then this one.
Source · 8 lines
def _burndown(out_dir: Path, version: str, snapshot: dict, milestones: list) -> str:
"""@brief Draw the burndown. @return SVG."""
from .charts import burndown
from .versions import series
return burndown(series(out_dir, version, snapshot), milestones)
Activity · 3 steps
Flows
_commit
str clew.wiki.build._commit(Path repo_root)
The repository's HEAD commit, or "HEAD" when it cannot be read.
Source · 22 lines
def _commit(repo_root: Path) -> str:
"""FULL IDS, through the hardened git environment (#67: commit-correct links).
@brief Read HEAD.
@return Sha.
"""
from ..gitenv import git_argv
try:
out = subprocess.run(
git_argv("rev-parse", "HEAD"),
cwd=repo_root,
capture_output=True,
text=True,
check=False,
timeout=30,
)
except (OSError, subprocess.TimeoutExpired):
return "HEAD"
return out.stdout.strip() or "HEAD"
Activity · 6 steps
Flows
_coverage
dict | None clew.wiki.build._coverage(Path repo_root, Any config)
Per-test coverage, when the section names it and it is there.
Source · 10 lines
def _coverage(repo_root: Path, config: Any) -> dict | None:
"""@brief Read contexts. @return Contexts or None."""
from .imports import parse_contexts
rel = config.inputs.contexts
return (
parse_contexts(repo_root / rel, repo_root) if rel and (repo_root / rel).is_file() else None
)
Activity · 3 steps
Flows
_fetch_issues
tuple[Any, list, str] clew.wiki.build._fetch_issues(WikiConfig config, Any target, list evidence)
Open issues linked to requirements, when the section asks for them.
Source · 29 lines
def _fetch_issues(config: WikiConfig, target: Any, evidence: list) -> tuple[Any, list, str]:
"""THE BUILD'S ONLY NETWORK USE, and only when `wiki.issues.fetch` is true. A failure is SAID
on the page — never a crash, and never an empty list that would read "no open issues".
@brief Fetch and link issues.
@return Linked, unlinked, note.
"""
from . import issues as tracker
if not config.issues_fetch:
return None, [], ""
if target is None:
return None, [], "Issues were not fetched: no tracker is declared or found on `origin`."
provider = tracker.provider_for(target)
try:
found = provider.list_open()
except (OSError, ValueError, KeyError) as exc:
return None, [], f"Issues were not fetched from {target[0]} `{target[1]}`: {exc}"
linked, unlinked = tracker.link_issues(found, [r.req_id for r in evidence])
## D14 (2.0.0): a listing cut at its page cap is SAID — the counts below are a floor.
note = (
f"Only the first {len(found)} open issues were read from {target[0]} `{target[1]}` (the "
f"listing stops at its page cap); counts on this page are a lower bound."
if getattr(provider, "truncated", False)
else ""
)
return linked, unlinked, note
Activity · 13 steps
Flows
_issues_into
None clew.wiki.build._issues_into(dict graph, Any linked)
Each component's count of open issues linked to the requirements it implements.
Source · 9 lines
def _issues_into(graph: dict, linked: Any) -> None:
"""@brief Count per component. @return None."""
if linked is None:
return
for comp in graph["components"]:
ids = {i.id for r, _tier in comp.get("req_ids") or [] for i in linked.get(r, [])}
comp["issues"] = len(ids)
Activity · 5 steps
Flows
_lines_by_test
dict clew.wiki.build._lines_by_test(dict|None coverage)
Each test's executed lines, from per-test coverage.
Source · 7 lines
def _lines_by_test(coverage: dict | None) -> dict:
"""@brief Group by test. @return Lines."""
from .slices import lines_per_test
return lines_per_test(coverage) if coverage else {}
Activity · 2 steps
Flows
_milestones
list[tuple[str, str]] clew.wiki.build._milestones(Path repo_root, WikiConfig config)
The roadmap's milestones, or none when no roadmap is declared.
Source · 7 lines
def _milestones(repo_root: Path, config: WikiConfig) -> list[tuple[str, str]]:
"""@brief Read milestones. @return Pairs."""
from .charts import roadmap_milestones
return roadmap_milestones(repo_root / config.roadmap) if config.roadmap else []
Activity · 2 steps
Flows
_requirements_of
dict[tuple[str, str], list[str]] clew.wiki.build._requirements_of(list evidence)
Which requirements each implementing function carries.
Source · 9 lines
def _requirements_of(evidence: list) -> dict[tuple[str, str], list[str]]:
"""@brief Invert implementer sites. @return Map."""
out: dict[tuple[str, str], list[str]] = {}
for row in evidence:
for name, rel, _line in row.implementer_sites:
out.setdefault((name, rel), []).append(row.req_id)
return out
Activity · 5 steps
Flows
_slices_by_test
dict[str, list] clew.wiki.build._slices_by_test(list pages)
Each test's slices of the master flows, most exercised first.
Source · 11 lines
def _slices_by_test(pages: list) -> dict[str, list]:
"""@brief Group slices by test. @return Slices."""
out: dict[str, list] = {}
for page in pages:
for test, cut in (page.slices or {}).items():
out.setdefault(test, []).append((page, cut))
for cuts in out.values():
cuts.sort(key=lambda pc: (-len(pc[1].exercised), pc[0].name))
return out
Activity · 7 steps
Requirements
Flows
_test_flows
list clew.wiki.build._test_flows(Path db, dict facts, frozenset traced=frozenset(), int depth=2)
Directly linked tests (by tag or measured coverage) with a packaged run, as flows.
Source · 22 lines
def _test_flows(db: Path, facts: dict, traced: frozenset = frozenset(), depth: int = 2) -> list:
"""CATALOG AND INFERRED LINKS ARE NOT DIRECT: a catalog names a whole test file and inference
reaches through the call graph; only a tagged or measured test is drawn by default.
@brief Test flows.
@return Specs.
"""
from ..query._common import connect
from .config import FlowSpec
from .symbols import test_functions
direct = {n for n, f in facts.items() if any(k in ("tag", "measured") for _r, k in f.verifies)}
with connect(db) as conn:
keys = sorted(test_functions(conn, direct))
chosen = [k for k in keys if k[0] in traced]
specs = [
FlowSpec(entry=n, file=f, depth=depth, title=f"test `{n}` ({f})", role="tests")
for n, f in chosen
]
return specs
Activity · 9 steps
Requirements
Flows
_with_role
Any clew.wiki.build._with_role(Any spec, WikiConfig config)
A flow with its role settled: declared, else tooling by path, else product.
Source · 11 lines
def _with_role(spec: Any, config: WikiConfig) -> Any:
"""@brief Classify. @return Spec."""
import dataclasses
import fnmatch
if spec.role:
return spec
tooling = bool(spec.file) and any(fnmatch.fnmatch(spec.file, g) for g in config.tooling)
return dataclasses.replace(spec, role="tooling" if tooling else "product")
Activity · 6 steps
Flows
build_wiki
Path clew.wiki.build.build_wiki(Path repo_root, Path db, Path out_dir, str|None audience=None, str|None version=None, Path|None config_path=None, Path|None summary=None)
Build the site for a repository.
Called by _build, _site, _site, _site, _site, built, inventory, open_main, site, site
Tested by 18 tests
test_a_build_writes_the_summary_beside_the_site, test_a_catalog_that_moved_since_its_pin_fails_check, test_a_discovered_flow_that_cannot_be_drawn_is_listed_not_fatal, test_a_model_no_code_realises_gets_no_page, test_a_partner_site_bundles_no_body_on_symbol_pages, test_a_partner_site_carries_no_call_text, test_a_partner_site_lists_no_assertions, test_a_public_site_keeps_requirement_text_off_the_requirement_page, test_a_repository_with_pinned_catalogues_gets_the_product_trace, test_an_audience_that_excludes_bodies_gets_none, test_an_imported_trace_is_drawn_over_its_test_flow, test_build_writes_a_self_contained_site
Calls _build_site, load_wiki_config, report_limit
Source · 23 lines
def build_wiki(
repo_root: Path,
db: Path,
out_dir: Path,
audience: str | None = None,
version: str | None = None,
config_path: Path | None = None,
summary: Path | None = None,
) -> Path:
"""THE REPORT SIZE LIMIT (`tests.max_report_mb`) IS THIS BUILD'S: every report reader below
consults it, so it is set around the whole build rather than threaded through each parser.
@brief Write and render the site, within this build's report limit.
@return The HTML directory.
@version 24
"""
from .evidence import report_limit
config, problems = load_wiki_config(Path(repo_root), config_path)
with report_limit(config.max_report_mb if not problems else DEFAULT_MAX_REPORT_MB):
return _build_site(repo_root, db, out_dir, audience, version, config_path, summary)
Activity · 4 steps
Requirements
Flows
commit_published
bool | None clew.wiki.build.commit_published(Path repo_root, str commit)
Whether a commit is on one of the repository's remotes.
Source · 29 lines
def commit_published(repo_root: Path, commit: str) -> bool | None:
"""OWNER 2026-11-15: "GH link broken (local unpushed commits)" — a permalink to a commit no
remote has is a 404. Only a KNOWN negative drops links: with nothing to go on they stay.
@brief Published?
@return Tri-state.
"""
from ..gitenv import git_argv
if not commit or commit == "HEAD":
return None
try:
remotes = subprocess.run(
git_argv("remote"), cwd=repo_root, capture_output=True, text=True, timeout=30
)
if remotes.returncode != 0 or not remotes.stdout.strip():
return None
found = subprocess.run(
git_argv("branch", "-r", "--contains", commit),
cwd=repo_root,
capture_output=True,
text=True,
timeout=30,
)
except (OSError, subprocess.TimeoutExpired):
return None
return bool(found.stdout.strip()) if found.returncode == 0 else None