Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(generation): module pages written from structured facts, with checked diagrams and citations (#2740)

Raghav Chamadiya978365db3113
diff --git a/packages/core/src/repowise/core/generation/agent_digest.py b/packages/core/src/repowise/core/generation/agent_digest.py
index c5e99d9e5..69a4d01af 100644
--- a/packages/core/src/repowise/core/generation/agent_digest.py
+++ b/packages/core/src/repowise/core/generation/agent_digest.py
@@ -38,7 +38,7 @@ _H2 = re.compile(r"^##\s+(.+?)\s*#*\s*$")
_FENCE = re.compile(r"^\s*(```|~~~)")
-def _h2_sections(content: str) -> list[tuple[str | None, list[str]]]:
+def h2_sections(content: str) -> list[tuple[str | None, list[str]]]:
"""Split *content* into ``(heading, lines)`` runs at level-2 headings.
The first run has no heading. A ``##`` inside a fenced block is text.
@@ -64,7 +64,7 @@ def split_questions(content: str) -> tuple[str, str]:
"""
body: list[str] = []
questions: list[str] = []
- for heading, lines in _h2_sections(content or ""):
+ for heading, lines in h2_sections(content or ""):
if heading is not None and heading.strip().lower() in _QUESTION_HEADINGS:
questions.extend(lines)
else:
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py
index bb504fc5d..c3df63561 100644
--- a/packages/core/src/repowise/core/generation/context/assembler.py
+++ b/packages/core/src/repowise/core/generation/context/assembler.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import re
from collections import Counter
+from collections.abc import Sequence
from pathlib import PurePosixPath
from typing import Any
@@ -44,6 +45,7 @@ from .graph_intelligence import (
extract_heritage,
)
from .module_excerpts import module_excerpts
+from .module_facts import build_module_facts
from .token_budget import (
estimate_kg_tokens,
estimate_tokens,
@@ -510,6 +512,7 @@ class ContextAssembler:
public_api: list[dict] | None = None,
parsed_files: dict[str, ParsedFile] | None = None,
source_map: dict[str, bytes] | None = None,
+ execution_flows: Sequence[Any] = (),
) -> ModulePageContext:
"""Assemble context for the module_page template.
@@ -644,7 +647,7 @@ class ContextAssembler:
max(0, _MODULE_EXCERPT_BUDGET - api_cost),
)
- return ModulePageContext(
+ ctx = ModulePageContext(
title=title,
directories=directories,
language=language,
@@ -670,7 +673,16 @@ class ContextAssembler:
packages=packages or [],
public_api=api_rows,
public_api_omitted=len(public_api or ()) - len(api_rows),
- code_excerpts=excerpts.rendered,
+ code_excerpts=[
+ {
+ "file": item.path,
+ "symbol": item.symbol,
+ "lines": f"{item.start_line}-{item.end_line}",
+ "truncated": item.truncated,
+ "code": item.text,
+ }
+ for item in excerpts.included
+ ],
declared_files=declared_files,
hotspot_count=hotspot_count,
stable_count=stable_count,
@@ -679,6 +691,8 @@ class ContextAssembler:
bugfix_total=bugfix_total,
most_fixed_file=most_fixed_file,
)
+ ctx.facts = build_module_facts(ctx, file_contexts, graph, execution_flows)
+ return ctx
def _excerpt_public_api(self, api: list[dict]) -> tuple[list[dict], int]:
"""Every name (to the hard cap), then signature + doc line while half the rest lasts.
diff --git a/packages/core/src/repowise/core/generation/context/contexts.py b/packages/core/src/repowise/core/generation/context/contexts.py
index 3b9a7500a..3062add18 100644
--- a/packages/core/src/repowise/core/generation/context/contexts.py
+++ b/packages/core/src/repowise/core/generation/context/contexts.py
@@ -5,6 +5,7 @@ One dataclass per template; extracted from the former context_assembler.py.
from __future__ import annotations
+import json
from dataclasses import dataclass, field
from typing import Any
@@ -127,8 +128,9 @@ class ModulePageContext:
public_api: list[dict] = field(default_factory=list)
# Public API entries past the hard cap, counted, not listed.
public_api_omitted: int = 0
- # Rendered source excerpts, then one-line signatures for files with no excerpt.
- code_excerpts: str = ""
+ # Exact source for the central symbols: [{"file", "symbol", "lines",
+ # "truncated", "code"}], then one-line signatures for files with no excerpt.
+ code_excerpts: list[dict] = field(default_factory=list)
declared_files: list[str] = field(default_factory=list)
# Git-derived subsystem health, aggregated over the page's member files.
# All degrade to zero/empty when no git metadata is available, so the
@@ -162,6 +164,14 @@ class ModulePageContext:
# Top files inside the module by PageRank, for the "key files" section.
key_files: list[dict] = field(default_factory=list)
top_owners: list[dict] = field(default_factory=list)
+ # What the model writes the page from: parts, import edges between them,
+ # key files, neighbours and a traced flow. See ``module_facts.py``.
+ facts: dict = field(default_factory=dict)
+
+ @property
+ def facts_json(self) -> str:
+ """The facts as the prompt shows them: readable JSON, arrows left unescaped."""
+ return json.dumps(self.facts, indent=1, ensure_ascii=False)
@dataclass
diff --git a/packages/core/src/repowise/core/generation/context/module_facts.py b/packages/core/src/repowise/core/generation/context/module_facts.py
new file mode 100644
index 000000000..a0d958f8d
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/context/module_facts.py
@@ -0,0 +1,254 @@
+"""Structural facts for a module page, as data the model reads, not bullets.
+
+A module page used to receive its material as a dozen bulleted lists (key files,
+dependencies, owners, health counts) and returned a page shaped like them. The
+facts here are what a reader needs to understand how the module works: its
+parts and the import edges between them, its key files, exact source for its
+central symbols and signatures for the rest (both chosen and budgeted by
+``module_excerpts``), what it depends on and what depends on it, and, for a
+module that hosts an operation, one traced execution flow through it. They are handed to the model
+as one JSON object, together with the diagram the module's shape calls for.
+
+Paths are relative to the module's base directory, which is how a reader thinks
+about the module and how the page cites them; :func:`module_base` is the one
+place that decides the base, so the sources lint resolves them the same way.
+"""
+
+from __future__ import annotations
+
+import math
+from collections import Counter, defaultdict
+from collections.abc import Iterable, Sequence
+from pathlib import PurePosixPath
+from typing import Any
+
+import networkx as nx
+
+# The diagram stays small enough to read without zooming.
+_MAX_PARTS = 9
+_MAX_PART_EDGES = 12
+_MAX_KEY_FILES = 6
+_MAX_NEIGHBOURS = 6
+_MAX_FLOW_STEPS = 10
+# A traced flow earns a sequence diagram only when it starts here and enough
+# of it runs here: a flow merely passing through says little about the module.
+_MIN_FLOW_STEPS_INSIDE = 3
+_MIN_FLOW_STEPS = 4
+# Package entry files that re-export their siblings. Their import edges point
+# at every part and turn a diagram into a star, so the diagram leaves them out.
+_BARREL_STEMS = frozenset({"index", "__init__", "mod", "lib"})
+
+
+def module_base(files: Iterable[str]) -> str:
+ """The deepest directory holding every one of *files*, ``""`` for the root."""
+ parents = [PurePosixPath(f).parent.parts for f in files]
+ if not parents:
+ return ""
+ common: list[str] = []
+ for level in zip(*parents, strict=False):
+ if len(set(level)) != 1:
+ break
+ common.append(level[0])
+ return "/".join(common)
+
+
+def relative_to(path: str, base: str) -> str:
+ """*path* relative to *base* when it lies under it, else unchanged."""
+ prefix = f"{base}/" if base else ""
+ return path[len(prefix) :] if prefix and path.startswith(prefix) else path
+
+
+def _part_of(path: str, base: str) -> str:
+ """The module part a file belongs to: its first segment below *base*."""
+ rest = relative_to(path, base)
+ head, _, tail = rest.partition("/")
+ return f"{head}/" if tail else head
+
+
+def _area(path: str) -> str:
+ """How a file outside the module is named: its directory."""
+ parent = str(PurePosixPath(path).parent)
+ return "(root)" if parent == "." else f"{parent}/"
+
+
+def _import_edges(graph: Any, members: set[str]) -> Iterable[tuple[str, str, dict]]:
+ for source in sorted(members):
+ if source not in graph:
+ continue
+ for _, target, data in graph.out_edges(source, data=True):
+ if data.get("edge_type") == "imports":
+ yield source, target, data
+
+
+def _flow_steps(
+ flows: Sequence[Any], graph: Any, members: set[str], base: str
+) -> list[dict[str, str]]:
+ """The traced flow that starts in this module and runs furthest in it, as steps."""
+ candidates: list[tuple[int, int, float, str, Any]] = []
+ for flow in flows:
+ trace = list(getattr(flow, "trace", []) or [])
+ inside = [n for n in trace if n.split("::")[0] in members]
+ starts_here = bool(trace) and trace[0].split("::")[0] in members
+ if not starts_here or len(inside) < _MIN_FLOW_STEPS_INSIDE or len(trace) < _MIN_FLOW_STEPS:
+ continue
+ # The flow that crosses the most parts shows how they work together.
+ crossed = len({_part_of(n.split("::")[0], base) for n in inside})
+ score = float(getattr(flow, "entry_point_score", 0.0))
+ candidates.append((-crossed, -len(inside), -score, trace[0], flow))
+ if not candidates:
+ return []
+ best = min(candidates, key=lambda c: c[:4])[4]
+ steps = []
+ for node in best.trace[:_MAX_FLOW_STEPS]:
+ file, _, symbol = node.partition("::")
+ data = graph.nodes[node] if node in graph else {}
+ inside = file in members
+ if steps and steps[-1]["call"] == (data.get("name") or symbol or file):
+ continue # the same call back to back is one step
+ steps.append(
+ {
+ "call": data.get("name") or symbol or file,
+ "file": relative_to(file, base) if inside else file,
+ "part": _part_of(file, base) if inside else f"outside: {_area(file)}",
+ }
+ )
+ return steps
+
+
+def _ranked(counts: Counter[Any]) -> list[tuple[Any, int]]:
+ """Highest count first, ties by key: the facts are part of the prompt, and a
+ prompt that changes between runs defeats reuse of the page written from it."""
+ return sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))
+
+
+def _public_api(rows: Sequence[dict]) -> list[dict]:
+ """The assembler's budgeted Public API: rows with a signature in full, then
+ the names past the budget grouped by file, so every name costs one word."""
+ full = [
+ {k: e[k] for k in ("name", "kind", "file", "signature", "doc", "alias_of") if e.get(k)}
+ for e in rows
+ if e.get("signature")
+ ]
+ bare: dict[str, list[str]] = {}
+ for e in rows:
+ if not e.get("signature"):
+ alias = f" (another name for {e['alias_of']})" if e.get("alias_of") else ""
+ bare.setdefault(e["file"], []).append(e["name"] + alias)
+ return full + [{"file": f, "names": names} for f, names in bare.items()]
+
+
+def _is_hub(part_edges: Counter[tuple[str, str]], parts: Sequence[str], has_entry: bool) -> bool:
+ """A module run from one place: an entry point, or one part importing most others."""
+ if has_entry:
+ return True
+ reach: dict[str, set[str]] = defaultdict(set)
+ for a, b in part_edges:
+ reach[a].add(b)
+ needed = max(3, math.ceil(0.6 * (len(parts) - 1)))
+ return any(len(targets) >= needed for targets in reach.values())
+
+
+def build_module_facts(
+ ctx: Any,
+ file_contexts: Sequence[Any],
+ graph: Any,
+ flows: Sequence[Any] = (),
+) -> dict[str, Any]:
+ """The JSON-ready facts a module page is written from."""
+ graph = graph if graph is not None else nx.DiGraph()
+ members = set(ctx.files)
+ base = module_base(ctx.files)
+ by_part: Counter[str] = Counter(_part_of(f, base) for f in ctx.files)
+
+ part_edges: Counter[tuple[str, str]] = Counter()
+ edge_names: dict[tuple[str, str], set[str]] = defaultdict(set)
+ depends_on: Counter[str] = Counter()
+ for source, target, data in _import_edges(graph, members):
+ if target in members:
+ if PurePosixPath(source).stem in _BARREL_STEMS:
+ continue
+ pair = (_part_of(source, base), _part_of(target, base))
+ if pair[0] != pair[1]:
+ part_edges[pair] += 1
+ edge_names[pair].update(sorted(data.get("imported_names") or [])[:4])
+ elif "::" not in target:
+ depends_on[_area(target)] += 1
+ used_by: Counter[str] = Counter()
+ for target in sorted(members):
+ if target not in graph:
+ continue
+ for source, _, data in graph.in_edges(target, data=True):
+ if (
+ data.get("edge_type") == "imports"
+ and source not in members
+ and "::" not in source
+ and not graph.nodes[source].get("is_test")
+ ):
+ used_by[_area(source)] += 1
+
+ # The busiest parts, so a wide module still draws a readable diagram.
+ weight: Counter[str] = Counter()
+ for (a, b), n in part_edges.items():
+ weight[a] += n
+ weight[b] += n
+ parts = sorted(by_part, key=lambda p: (-weight[p], -by_part[p], p))[:_MAX_PARTS]
+ shown = set(parts)
+ edges = [
+ {"from": a, "to": b, "imports": n, "names": sorted(edge_names[(a, b)])[:4]}
+ for (a, b), n in _ranked(part_edges)
+ if a in shown and b in shown
+ ][:_MAX_PART_EDGES]
+
+ flow = _flow_steps(flows, graph, members, base)
+ hub = _is_hub(part_edges, parts, bool(ctx.entry_points))
+ # Parts only earn a flowchart when enough of them are connected; isolated
+ # boxes tell a reader nothing an ordinary list would not.
+ connected = {p for e in edges for p in (e["from"], e["to"])}
+ if flow and hub:
+ diagram = "sequenceDiagram"
+ elif len(connected) >= 3 and len(edges) >= 2:
+ diagram = "flowchart"
+ else:
+ diagram = "sequenceDiagram" if flow else "none"
+
+ ranked = sorted(file_contexts, key=lambda fc: (-fc.pagerank_score, fc.file_path))
+ key_files = [
+ {
+ "path": relative_to(fc.file_path, base),
+ "summary": (ctx.file_summaries.get(fc.file_path) or "").strip(),
+ "entry_point": fc.is_entry_point,
+ }
+ for fc in ranked[:_MAX_KEY_FILES]
+ ]
+
+ facts: dict[str, Any] = {
+ "module": ctx.title,
+ "base_directory": base or "(repository root)",
+ "language": ctx.language,
+ "files": len(ctx.files),
+ "shape": "hub" if hub else "parts",
+ "diagram": diagram,
+ "parts": [{"part": p, "files": by_part[p]} for p in parts],
+ "parts_not_shown": max(0, len(by_part) - len(parts)),
+ "imports_between_parts": edges,
+ "traced_flow": flow,
+ "key_files": key_files,
+ "entry_points": [relative_to(p, base) for p in ctx.entry_points],
+ "public_api": _public_api(ctx.public_api),
+ "public_api_not_listed": ctx.public_api_omitted,
+ "code_excerpts": [{**e, "file": relative_to(e["file"], base)} for e in ctx.code_excerpts],
+ "declared": ctx.declared_files,
+ "depends_on": [
+ {"area": a, "imports": n} for a, n in _ranked(depends_on)[:_MAX_NEIGHBOURS]
+ ],
+ "used_by": [{"area": a, "imports": n} for a, n in _ranked(used_by)[:_MAX_NEIGHBOURS]],
+ "external_systems": [s["name"] for s in ctx.external_systems[:8]],
+ "decisions": [
+ {"title": d.get("title", ""), "decision": d.get("decision", ""), "why": d.get("rationale", "")}
+ for d in ctx.decision_records[:3]
+ ],
+ "child_pages": ctx.child_pages,
+ "packages": [p["path"] for p in ctx.packages],
+ }
+ # Empty keys are noise the model has to read past.
+ return {k: v for k, v in facts.items() if v not in ([], "", None, 0)}
diff --git a/packages/core/src/repowise/core/generation/mermaid_safety.py b/packages/core/src/repowise/core/generation/mermaid_safety.py
index 3f67c80bb..9fba4d064 100644
--- a/packages/core/src/repowise/core/generation/mermaid_safety.py
+++ b/packages/core/src/repowise/core/generation/mermaid_safety.py
@@ -36,6 +36,7 @@ _MERMAID_FENCE_RE = re.compile(
# Diagram kinds that use ``id[label]`` node syntax we know how to repair.
_GRAPH_DIRECTIVE_RE = re.compile(r"^\s*(graph|flowchart)\b", re.IGNORECASE)
+_SEQUENCE_DIRECTIVE_RE = re.compile(r"^\s*sequenceDiagram\b")
# Shape bracket pairs, longest opener first so ``([`` wins over ``(``.
_SHAPE_PAIRS: tuple[tuple[str, str], ...] = (
@@ -333,11 +334,10 @@ def sanitize_mermaid(markdown: str) -> str:
first_line = body.lstrip().split("\n", 1)[0]
if _GRAPH_DIRECTIVE_RE.match(first_line):
body = _rewrite_graph_block(body)
- else:
- # Other diagram kinds (sequenceDiagram, erDiagram, classDiagram)
- # have different grammars — only quote obviously risky labels is
- # unsafe there, so leave them untouched.
- pass
+ elif _SEQUENCE_DIRECTIVE_RE.match(first_line):
+ body = _drop_flowchart_styling(body)
+ # Other diagram kinds (erDiagram, classDiagram) have their own
+ # grammars; quoting labels there is unsafe, so they are left alone.
except Exception as exc: # never corrupt a working diagram
log.debug("mermaid_safety.block_failed", error=str(exc))
body = match.group("body")
@@ -346,6 +346,227 @@ def sanitize_mermaid(markdown: str) -> str:
return _MERMAID_FENCE_RE.sub(_replace, markdown)
+# ---------------------------------------------------------------------------
+# Structural validation
+#
+# ``sanitize_mermaid`` repairs what it can recognise. What it cannot repair a
+# renderer rejects, and one rejected block shows the reader an error box where
+# the page promised a picture. These checks are the grammar rules a generated
+# diagram breaks in practice, per diagram type. They are not a parser: a block
+# they pass can still fail to render, and types they have no rules for pass on
+# a known header.
+# ---------------------------------------------------------------------------
+
+_DIAGRAM_TYPES = frozenset(
+ {
+ "graph",
+ "flowchart",
+ "sequencediagram",
+ "classdiagram",
+ "statediagram",
+ "statediagram-v2",
+ "erdiagram",
+ "journey",
+ "gantt",
+ "pie",
+ "mindmap",
+ "timeline",
+ "gitgraph",
+ "quadrantchart",
+ "c4context",
+ "c4container",
+ "c4component",
+ "c4dynamic",
+ "c4deployment",
+ }
+)
+
+# A flowchart node id as mermaid reads it, followed by what may come after one.
+_FLOW_ID_RE = re.compile(r"^[A-Za-z0-9_.]+$")
+# Keywords the flowchart grammar reads before it reads an id: a node named
+# ``end`` closes a subgraph, one named ``graph`` starts a new diagram.
+_FLOW_RESERVED_IDS = frozenset(
+ {"end", "graph", "flowchart", "subgraph", "style", "class", "classDef", "click", "linkStyle"}
+)
+_FLOW_KEYWORDS = ("classDef ", "class ", "style ", "linkStyle ", "click ", "direction ")
+
+# Every statement a sequence diagram accepts, by its leading word.
+_SEQ_STATEMENTS = frozenset(
+ {
+ "participant",
+ "actor",
+ "autonumber",
+ "note",
+ "activate",
+ "deactivate",
+ "title",
+ "create",
+ "destroy",
+ "link",
+ "links",
+ "box",
+ "loop",
+ "alt",
+ "else",
+ "opt",
+ "par",
+ "and",
+ "critical",
+ "option",
+ "break",
+ "rect",
+ "end",
+ }
+)
+_SEQ_BLOCK_OPENERS = frozenset({"loop", "alt", "opt", "par", "critical", "break", "rect", "box"})
+# ``A->>B: text``, with the arrow set sequence diagrams define.
+_SEQ_MESSAGE_RE = re.compile(
+ r"^[^\s:<>\-+][^:<>]*?\s*(?:<<)?(?:-->>|->>|-->|->|--x|-x|--\)|-\))\s*[+-]?[^:]+?\s*:.*$"
+)
+_SEQ_PARTICIPANT_RE = re.compile(
+ r'^(participant|actor)\s+([A-Za-z0-9_]+|"[^"]+")(\s+as\s+.+)?\s*$', re.I
+)
+
+
+_FLOWCHART_STYLING_RE = re.compile(r"^\s*(classDef|class|style|linkStyle)\s")
+
+
+def _drop_flowchart_styling(body: str) -> str:
+ """Remove flowchart styling lines a sequence diagram cannot parse.
+
+ A model that has drawn flowcharts carries ``classDef`` and ``class`` lines
+ over; they add nothing to a sequence and fail the whole block.
+ """
+ return "\n".join(line for line in body.split("\n") if not _FLOWCHART_STYLING_RE.match(line))
+
+
+def _statements(body: str) -> list[str]:
+ """The block's lines that carry syntax: no blanks, comments, directives or front matter."""
+ lines = body.strip().split("\n")
+ if lines and lines[0].strip() == "---":
+ # A ``---``-fenced front matter block (title, config) precedes the header.
+ closing = next((i for i, line in enumerate(lines[1:], 1) if line.strip() == "---"), 0)
+ lines = lines[closing + 1 :]
+ return [line.strip() for line in lines if line.strip() and not _is_skippable(line)]
+
+
+def _balanced(line: str) -> bool:
+ """Whether quotes and brackets on *line* close, ignoring quoted text."""
+ if line.count('"') % 2:
+ return False
+ unquoted = re.sub(r'"[^"]*"', "", line)
+ unquoted = _PIPE_LABEL_RE.sub("", unquoted)
+ pairs = {"]": "[", ")": "(", "}": "{"}
+ stack: list[str] = []
+ for char in unquoted:
+ if char in "[({":
+ stack.append(char)
+ elif char in pairs and (not stack or stack.pop() != pairs[char]):
+ return False
+ return not stack
+
+
+def _flowchart_problems(lines: list[str]) -> list[str]:
+ problems: list[str] = []
+ depth = 0
+ for line in lines:
+ word = line.split()[0]
+ if word == "subgraph":
+ depth += 1
+ continue
+ if line == "end":
+ depth -= 1
+ if depth < 0:
+ problems.append("`end` without a matching `subgraph`")
+ depth = 0
+ continue
+ if line.startswith(_FLOW_KEYWORDS):
+ continue
+ if not _balanced(line):
+ problems.append(f"unbalanced quotes or brackets: {line[:60]}")
+ continue
+ # The first token is a node id, before any shape, class or edge.
+ head = re.split(r"[\s\[\(\{>:|&-]|:::", line, maxsplit=1)[0]
+ if head and (not _FLOW_ID_RE.match(head) or head in _FLOW_RESERVED_IDS):
+ problems.append(f"illegal node id {head!r}")
+ if depth:
+ problems.append("`subgraph` without a matching `end`")
+ return problems
+
+
+def _sequence_problems(lines: list[str]) -> list[str]:
+ problems: list[str] = []
+ depth = 0
+ for line in lines:
+ word = line.split()[0].lower().rstrip(":")
+ if word in ("classdef", "class", "style", "linkstyle", "click", "subgraph"):
+ problems.append(f"`{word}` is not sequence diagram syntax")
+ continue
+ if word in _SEQ_BLOCK_OPENERS:
+ depth += 1
+ elif word == "end":
+ depth -= 1
+ if depth < 0:
+ problems.append("`end` without an opening block")
+ depth = 0
+ elif word in ("participant", "actor"):
+ if not _SEQ_PARTICIPANT_RE.match(line):
+ problems.append(f"participant id must be a plain word: {line[:60]}")
+ elif word not in _SEQ_STATEMENTS and not _SEQ_MESSAGE_RE.match(line):
+ problems.append(f"not a sequence diagram statement: {line[:60]}")
+ if depth:
+ problems.append("a block (`loop`, `alt`, `opt`, ...) without its `end`")
+ return problems
+
+
+def mermaid_problems(body: str) -> list[str]:
+ """What would stop the renderer drawing this mermaid block, if anything.
+
+ Empty means no known rule is broken. The checks follow the diagram type the
+ first statement names; types with no checks here pass on a known header.
+ """
+ lines = _statements(body)
+ if not lines:
+ return ["empty diagram"]
+ header = lines[0].split()[0].lower()
+ if header not in _DIAGRAM_TYPES and not header.endswith("-beta"):
+ return [f"unknown diagram type {lines[0].split()[0]!r}"]
+ if header in ("graph", "flowchart"):
+ return _flowchart_problems(lines[1:])
+ if header == "sequencediagram":
+ return _sequence_problems(lines[1:])
+ return []
+
+
+def invalid_mermaid_blocks(markdown: str) -> list[str]:
+ """One problem line per mermaid block in *markdown* that fails validation."""
+ found: list[str] = []
+ for match in _MERMAID_FENCE_RE.finditer(markdown or ""):
+ problems = mermaid_problems(match.group("body"))
+ if problems:
+ found.append(problems[0])
+ return found
+
+
+def renderable_mermaid(markdown: str) -> str:
+ """*markdown* with its mermaid repaired, and any block still failing removed."""
+ return strip_invalid_mermaid(sanitize_mermaid(markdown))
+
+
+def strip_invalid_mermaid(markdown: str) -> str:
+ """*markdown* without the mermaid blocks that fail validation."""
+
+ def _keep(match: re.Match[str]) -> str:
+ return "" if mermaid_problems(match.group("body")) else match.group(0)
+
+ stripped = _MERMAID_FENCE_RE.sub(_keep, markdown)
+ if stripped == markdown:
+ # Nothing removed: leave the page byte-identical, or a template page
+ # with spare blank lines reads as changed and is stored twice.
+ return markdown
+ return re.sub(r"\n{3,}", "\n\n", stripped)
+
+
_HEADING_LINE_RE = re.compile(r"(?m)^#{1,6}\s")
@@ -368,22 +589,35 @@ def strip_leading_preamble(markdown: str) -> str:
def sanitize_pages(pages: list) -> int:
- """Run :func:`sanitize_mermaid` over a list of ``GeneratedPage``.
-
- Mutates ``page.content`` in place. Returns the number of pages whose
- content actually changed (for logging).
+ """Make every page of a run renderable before it is stored.
+
+ The one pass every page goes through, whatever wrote it: a fresh model
+ response, one reused from a prior run, a diagram embedded after
+ generation (the overview's map) or a template. Repairs what
+ :func:`sanitize_mermaid` can, and removes any block that still fails
+ :func:`mermaid_problems`. Mutates ``page.content`` in place. Returns the
+ number of pages whose content changed (for logging).
"""
changed = 0
for page in pages:
content = getattr(page, "content", None)
if not content:
continue
- fixed = strip_leading_preamble(content)
- fixed = sanitize_mermaid(fixed)
+ fixed = renderable_mermaid(strip_leading_preamble(content))
+ if invalid_mermaid_blocks(sanitize_mermaid(content)):
+ log.warning("mermaid_safety.block_removed", page_id=getattr(page, "page_id", ""))
if fixed != content:
page.content = fixed
changed += 1
return changed
-__all__ = ["sanitize_mermaid", "sanitize_pages", "strip_leading_preamble"]
+__all__ = [
+ "invalid_mermaid_blocks",
+ "mermaid_problems",
+ "renderable_mermaid",
+ "sanitize_mermaid",
+ "sanitize_pages",
+ "strip_invalid_mermaid",
+ "strip_leading_preamble",
+]
diff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.py
index 10d34e8ba..20fe7ee6d 100644
--- a/packages/core/src/repowise/core/generation/page_generator/core.py
+++ b/packages/core/src/repowise/core/generation/page_generator/core.py
@@ -35,6 +35,7 @@ from ..context.evidence import (
from ..context_assembler import ContextAssembler, FilePageContext
from ..house_vocabulary import cell
from ..languages import sanitize_language_code
+from ..mermaid_safety import renderable_mermaid
from ..models import (
MODEL_PAGE_CONFIDENCE,
GeneratedPage,
@@ -54,6 +55,7 @@ from .structural import (
)
from .validation import (
InvalidGeneratedContentError,
+ InvalidMermaidError,
reset_artifact_check_counts,
validate_generated_response,
)
@@ -457,8 +459,21 @@ class PageGenerator(PerTypeGenerationMixin, StructuralRenderMixin):
cache_hints=cache_hints,
)
# A second failure raises, so the caller's stub-fallback path is
- # reached exactly as it was before the retry existed.
- validate_generated_response(response)
+ # reached exactly as it was before the retry existed. A page lost
+ # only to a diagram is kept without it: the retry when its own
+ # failure is a diagram, else the first attempt when that one was.
+ # The retry's token counts stay either way; both were billed.
+ try:
+ validate_generated_response(response)
+ except InvalidGeneratedContentError as second_failure:
+ if isinstance(second_failure, InvalidMermaidError):
+ salvage = response
+ elif isinstance(first_failure, InvalidMermaidError):
+ salvage = discarded
+ else:
+ raise
+ response = replace(response, content=renderable_mermaid(salvage.content))
+ validate_generated_response(response)
# The discarded attempt was billed. Carrying its tokens forward is
# what keeps the run report's totals equal to what the provider
# actually charged for; the page itself is the retry's content.
diff --git a/packages/core/src/repowise/core/generation/page_generator/levels.py b/packages/core/src/repowise/core/generation/page_generator/levels.py
index e03ebdbe5..14d6dbad1 100644
--- a/packages/core/src/repowise/core/generation/page_generator/levels.py
+++ b/packages/core/src/repowise/core/generation/page_generator/levels.py
@@ -258,6 +258,15 @@ def _rollup_child_pages(rollup: Any, groups: list[Any]) -> list[dict]:
return [{"title": g.display, "path": g.key} for g in children]
+def _execution_flows(graph_builder: Any) -> list[Any]:
+ """The run's traced execution flows, for module pages that host one."""
+ try:
+ return list(graph_builder.execution_flows().flows)
+ except Exception as exc:
+ log.warning("module_page.execution_flows_unavailable", error=str(exc))
+ return []
+
+
def build_level4_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
"""Level 4 (module_page), allow-set filtered."""
gen = run.gen
@@ -267,6 +276,7 @@ def build_level4_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
if not isinstance(parsed_by_path, dict) or not parsed_by_path:
parsed_by_path = {p.file_info.path: p for p in run.parsed_files}
package_roots = package_roots_from_paths(set(parsed_by_path))
+ flows = _execution_flows(run.graph_builder)
for mg in run.sel_module_groups:
# Read from the wider set: a chapter's prose is about its whole
# subsystem, while ``file_paths`` is the narrower, disjoint claim on who
@@ -333,6 +343,7 @@ def build_level4_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
public_api=compute_public_api(material, parsed_by_path, package_roots),
parsed_files=parsed_by_path,
source_map=run.source_map,
+ execution_flows=flows,
),
)
)
diff --git a/packages/core/src/repowise/core/generation/page_generator/pertype.py b/packages/core/src/repowise/core/generation/page_generator/pertype.py
index 0a44cfa33..78efe623d 100644
--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py
+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py
@@ -29,6 +29,7 @@ from ..architecture_mermaid import (
system_map_section,
)
from ..context.assembler import build_concept_index
+from ..context.module_facts import module_base
from ..context_assembler import FilePageContext
from ..models import (
GENERATION_LEVELS,
@@ -45,6 +46,7 @@ from ..overview_tables import (
embed_capability_table,
embed_package_table,
)
+from ..page_sources import lint_sources
from ..structural_labels import structural_page_title
log = structlog.get_logger(__name__)
@@ -236,6 +238,7 @@ class PerTypeGenerationMixin:
public_api: list[dict] | None = None,
parsed_files: dict[str, Any] | None = None,
source_map: dict[str, bytes] | None = None,
+ execution_flows: Sequence[Any] = (),
) -> GeneratedPage:
ctx = self._assembler.assemble_module_page(
title,
@@ -256,6 +259,7 @@ class PerTypeGenerationMixin:
public_api=public_api,
parsed_files=parsed_files,
source_map=source_map,
+ execution_flows=execution_flows,
)
module_git_summary = None
if git_meta_map:
@@ -391,6 +395,15 @@ class PerTypeGenerationMixin:
compute_source_hash(user_prompt),
GENERATION_LEVELS["module_page"],
)
+ # Citations of a missing file, or one its section never names, go.
+ # Diagrams are checked for every page of the run in ``sanitize_pages``.
+ page.content = lint_sources(
+ page.content,
+ base=module_base(ctx.files),
+ members=ctx.files,
+ known_paths=[n for n in graph if "::" not in n],
+ symbols_by_file={fc.file_path: [s["name"] for s in fc.symbols] for fc in file_contexts},
+ )
return _stamp_concept(_with_digest(page))
async def generate_scc_page(
diff --git a/packages/core/src/repowise/core/generation/page_generator/prompts.py b/packages/core/src/repowise/core/generation/page_generator/prompts.py
index cb4028652..2f9966dbc 100644
--- a/packages/core/src/repowise/core/generation/page_generator/prompts.py
+++ b/packages/core/src/repowise/core/generation/page_generator/prompts.py
@@ -21,46 +21,19 @@ from ..languages import SUPPORTED_LANGUAGES # noqa: F401
SYSTEM_PROMPTS: dict[str, str] = {
"module_page": (
- "You are repowise, an expert technical documentation generator. "
- "Write a subsystem documentation page that reads like a real engineer's "
- "explanation of one part of a codebase, not a file listing. "
+ "You are repowise, writing one page of an engineering wiki for a codebase. "
+ "The reader is a capable engineer who is new to this part of the code and "
+ "wants to understand it in five minutes. Clarity beats completeness: explain "
+ "how the parts work together and why, in short plain sentences, and leave "
+ "lists of names to the reference material kept beside the page. "
"Output markdown only. "
"\n"
- "FORM: Open with one or two paragraphs that state the subsystem's job in "
- "the larger system and situate it against its neighbours (what it does and, "
- "using the scope line below, what it deliberately leaves to other pages). "
- "Lead the first sentence with the role, in architectural vocabulary (entry "
- "stage, orchestration layer, persistence boundary, transport adapter, and so "
- "on), naming the inputs it consumes and the outputs it produces. "
- "Bad: 'The X module contains 15 files responsible for...'. "
- "Good: 'The ingestion layer is the entry stage of the indexing pipeline: it "
- "traverses a repository, parses files into ASTs, and yields structured "
- "records for downstream analysis.' "
- "\n"
- "Choose H2/H3 headings that name THIS subsystem's actual concerns rather "
- "than any fixed template. Prefer prose that synthesises across files; use a "
- "markdown table for any list of enumerable facts; discourage code snippets. "
- "Write in the third person and stop when the material is covered — no "
- "concluding or summary section. "
- "\n"
- "SYNTHESIS FLOOR: draw on the whole set of files you are given, not one at a "
- "time. A page that walks through files one by one has failed even if every "
- "sentence is true. Synthesise. "
- "\n"
- # The mandatory '## Questions this page answers' section is asked for once,
- # in module_page.j2, where the rest of the module-page contract lives.
- # Stating it here as well made the model stutter the heading: it emitted the
- # heading bare, then again with the questions under it, on 86 of 92 pages
- # measured across local indexes (gpt-5.4-nano). Pages written before the
- # instruction was doubled show none of it. One instruction, one heading.
- # Worded around the reader-facing vocabulary the artifact rules ban.
- # "the supplied material" is a literal hit for the ``supplied_context``
- # rule in validation.py, and the model echoed the instruction back into
- # the page, so this sentence destroyed the pages it was meant to keep
- # honest. Say where to ground a claim without naming the prompt.
- "Ground every claim in the files and signals listed below: do not invent "
- "files, symbols, or rationale that are not listed. Draw on the whole file "
- "set, not one file."
+ # The page shape, including the questions section, is stated once, in
+ # module_page.j2: stating a heading in both places makes the model emit it
+ # twice. The grounding sentence avoids the phrasings the supplied_context
+ # rule in validation.py rejects, which the model would echo into the page.
+ "Ground every claim in the structural facts listed below: never invent "
+ "components, files, edges or rationale that are not there."
),
"repo_overview": (
"You are repowise, an expert technical documentation generator. "
diff --git a/packages/core/src/repowise/core/generation/page_generator/validation.py b/packages/core/src/repowise/core/generation/page_generator/validation.py
index b0d1026ab..aea3a64d9 100644
--- a/packages/core/src/repowise/core/generation/page_generator/validation.py
+++ b/packages/core/src/repowise/core/generation/page_generator/validation.py
@@ -11,6 +11,7 @@ import re
from collections import Counter
from dataclasses import dataclass
+from repowise.core.generation.mermaid_safety import invalid_mermaid_blocks, sanitize_mermaid
from repowise.core.generation.prose import prose_text
from repowise.core.ingestion.models import ParsedFile
from repowise.core.providers.llm.base import GeneratedResponse
@@ -51,6 +52,15 @@ class InvalidGeneratedContentError(ValueError):
self.retryable = retryable
+class InvalidMermaidError(InvalidGeneratedContentError):
+ """A mermaid block in the response would not render.
+
+ Retried like any other rejection. When the retry breaks a diagram too, the
+ caller keeps the page and strips the failing blocks: a page without its
+ picture is still worth reading, an error box where the picture was is not.
+ """
+
+
# ---------------------------------------------------------------------------
# Generation artifacts
#
@@ -233,6 +243,11 @@ def validate_generated_response(response: GeneratedResponse) -> None:
f"{preamble}{detail}", retry_hint=f"{preamble}{retry_hint}"
)
+ # Checked on the repaired form, which is the form that gets stored.
+ broken = invalid_mermaid_blocks(sanitize_mermaid(response.content))
+ if broken:
+ raise InvalidMermaidError(f"a mermaid diagram will not render: {broken[0]}")
+
# Common words that appear in backticks but are not code symbols.
_BACKTICK_SKIP = frozenset(
diff --git a/packages/core/src/repowise/core/generation/page_sources.py b/packages/core/src/repowise/core/generation/page_sources.py
new file mode 100644
index 000000000..0e11bdabf
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/page_sources.py
@@ -0,0 +1,140 @@
+"""Check the file citations a model-written module page makes.
+
+Each section of a module page ends with a ``Sources:`` line and the page lists
+three files under "Where to start reading". A citation is only worth its place
+when the file exists and the section it closes is about that file; a wrong one
+sends the reader to the wrong code with the page's authority behind it. This
+pass keeps a citation that resolves to a real file (or directory) and that its
+section names, by file name or by one of the file's symbols, rewrites it to the
+path the rest of the page uses, and drops the rest. Deterministic: no model.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Collection, Iterable, Mapping
+from pathlib import PurePosixPath
+
+import structlog
+
+from .agent_digest import h2_sections
+from .context.module_facts import relative_to
+
+log = structlog.get_logger(__name__)
+
+_SOURCES_RE = re.compile(r"^\s*(?:[*_]{1,2})?Sources?:(?:[*_]{1,2})?\s*(.*)$", re.IGNORECASE)
+_BACKTICK_RE = re.compile(r"`([^`]+)`")
+_LINE_REF_RE = re.compile(r":\d+(?:-\d+)?$")
+_START_BULLET_RE = re.compile(r"^(\s*[-*]\s+)`([^`]+)`(.*)$")
+_MAX_SOURCES = 3
+_MIN_STEM = 3
+_MIN_SYMBOL = 4
+
+
+class _Resolver:
+ """Maps a cited path to the repository file or directory it names."""
+
+ def __init__(self, base: str, members: Collection[str], known: Collection[str]) -> None:
+ self._base = base
+ self._members = sorted(members)
+ self._known = set(known) | set(members)
+ self._dirs = {
+ str(parent)
+ for path in self._known
+ for parent in PurePosixPath(path).parents
+ if str(parent) != "."
+ }
+
+ def resolve(self, cited: str) -> str | None:
+ item = _LINE_REF_RE.sub("", cited.strip().strip("./")).rstrip("/")
+ if not item:
+ return None
+ is_dir = cited.strip().endswith("/")
+ rooted = f"{self._base}/{item}" if self._base else item
+ for candidate in (rooted, item):
+ if not is_dir and candidate in self._known:
+ return candidate
+ if candidate in self._dirs:
+ return f"{candidate}/"
+ if is_dir:
+ return None
+ return self._unique_suffix(item, self._members) or self._unique_suffix(item, self._known)
+
+ @staticmethod
+ def _unique_suffix(item: str, paths: Iterable[str]) -> str | None:
+ hits = [p for p in paths if p == item or p.endswith(f"/{item}")]
+ return hits[0] if len(hits) == 1 else None
+
+
+def _spellings(name: str) -> set[str]:
+ """How prose writes a file or directory name: as is, and with its separators as spaces."""
+ name = name.lower()
+ spaced = re.sub(r"[_\-.]+", " ", name).strip()
+ return {name, spaced, spaced.removesuffix("s")} - {""}
+
+
+def _named_in(
+ path: str, text: str, base: str, symbols: Mapping[str, Collection[str]]
+) -> bool:
+ """Whether *text* names the file at *path*, its part, or one of its symbols.
+
+ A path written out in full, from the repository root or from the module,
+ counts. Names match whole words only, so a short stem such as ``spec`` is
+ not found in "specific".
+ """
+ bare = path.rstrip("/").lower()
+ if bare in text or relative_to(bare, base.lower()) in text:
+ return True
+ pure = PurePosixPath(path.rstrip("/"))
+ names = {pure.name}
+ if len(pure.stem) >= _MIN_STEM:
+ names.add(pure.stem)
+ if str(pure.parent) not in (base, "."):
+ names.add(pure.parent.name)
+ names.update(n for n in symbols.get(path, ()) if len(n) >= _MIN_SYMBOL)
+ return any(
+ re.search(rf"(?<!\w){re.escape(word)}(?!\w)", text)
+ for name in names
+ for word in _spellings(name)
+ )
+
+
+def lint_sources(
+ content: str,
+ *,
+ base: str,
+ members: Collection[str],
+ known_paths: Collection[str],
+ symbols_by_file: Mapping[str, Collection[str]],
+) -> str:
+ """*content* with every ``Sources:`` line and start-reading bullet checked."""
+ resolver = _Resolver(base, members, known_paths)
+ out: list[str] = []
+ for heading, lines in h2_sections(content):
+ start_reading = heading is not None and heading.lower().startswith("where to start")
+ prose = "\n".join(line for line in lines if not _SOURCES_RE.match(line)).lower()
+ for line in lines:
+ if start_reading and (bullet := _START_BULLET_RE.match(line)):
+ path = resolver.resolve(bullet.group(2))
+ if path:
+ out.append(f"{bullet.group(1)}`{relative_to(path, base)}`{bullet.group(3)}")
+ else:
+ log.info("page_sources.dropped", cited=bullet.group(2), resolved="")
+ continue
+ match = _SOURCES_RE.match(line) if heading is not None else None
+ if not match:
+ out.append(line)
+ continue
+ cited = _BACKTICK_RE.findall(match.group(1)) or match.group(1).split(",")
+ kept: list[str] = []
+ for item in cited:
+ path = resolver.resolve(item)
+ shown = relative_to(path, base) if path else ""
+ if path and shown not in kept and _named_in(path, prose, base, symbols_by_file):
+ kept.append(shown)
+ elif not path or shown not in kept:
+ # One line per dropped citation; the run log shows how often it happens.
+ log.info("page_sources.dropped", cited=item.strip(), resolved=path or "")
+ if kept:
+ out.append("Sources: " + ", ".join(f"`{p}`" for p in kept[:_MAX_SOURCES]))
+ return re.sub(r"\n{3,}", "\n\n", "\n".join(out)).strip() + "\n"
diff --git a/packages/core/src/repowise/core/generation/templates/module_page.j2 b/packages/core/src/repowise/core/generation/templates/module_page.j2
index ba57ee895..85d086158 100644
--- a/packages/core/src/repowise/core/generation/templates/module_page.j2
+++ b/packages/core/src/repowise/core/generation/templates/module_page.j2
@@ -1,122 +1,44 @@
+{#- The module page contract. The facts arrive as one JSON object built by
+ ``context/module_facts.py``; the model turns them into a page a newcomer can
+ read in five minutes. Identifiers, public API and git signals are rendered
+ into the page's digest after generation, so they are not asked for here. -#}
{% if ctx.is_rollup %}
-You are documenting **{{ ctx.title }}**, an OVERVIEW of the `{{ ctx.directories[0] if ctx.directories else ctx.title }}` subsystem as a whole. Detail lives on the child pages listed below; this page situates the subsystem, explains how its parts fit together, and points a reader to the right child page. Do not re-document each file.
-{% else %}
-You are documenting **{{ ctx.title }}** (language: {{ ctx.language }}), a group of files that belong together, not a single directory. Write about what the group does as a whole.
+This page is the overview of a subsystem whose parts have their own pages (`child_pages` in the facts). Explain how the parts fit together and send the reader to the right child page by naming its path in backticks; do not re-document each file.
{% endif %}
{% if ctx.packages %}
-This page covers {{ ctx.packages | length }} sibling packages: {% for p in ctx.packages %}`{{ p.path }}`{% if not loop.last %}, {% endif %}{% endfor %}. Each is a separate package with its own manifest. Say what they share and how they differ; never describe the group as one of them or name the page after one. A table listing every package is appended after you write the page, so do not reproduce it.
+The page covers several sibling packages (`packages` in the facts), each with its own manifest. Say what they share and how they differ, and never name the page after one of them. A table of the packages is added after you write, so do not list them.
{% endif %}
-
{% if ctx.scope %}
-SCOPE (use this to open by situating the page against its siblings — say what it covers and what it deliberately leaves to other pages; do NOT quote this line verbatim):
-> {{ ctx.scope }}
+Scope, for setting the boundary in the opening (what this page covers and what it leaves to neighbouring pages; do not quote it): {{ ctx.scope }}
{% endif %}
-## Material
-
-**Covers:** {% if ctx.directories %}{% for d in ctx.directories[:6] %}`{{ d }}`{% if not loop.last %}, {% endif %}{% endfor %}{% if ctx.directories | length > 6 %} and {{ ctx.directories | length - 6 }} more{% endif %}{% else %}the repository root{% endif %} | **Language:** {{ ctx.language }} | **Files:** {{ ctx.files | length }} | **Public symbols:** {{ ctx.public_symbols }} / {{ ctx.total_symbols }}{% if ctx.community_label %} | **Community:** {{ ctx.community_label }}{% if ctx.community_cohesion > 0 %} (cohesion {{ "%.2f"|format(ctx.community_cohesion) }}){% endif %}{% endif %}
+Structural facts about **{{ ctx.title }}**, read from the code and its import graph. `code_excerpts` holds exact source for the central symbols; `declared` lists what other files declare, signatures only:
-{%- set _mod_signals = [] -%}
-{%- if ctx.entry_points -%}{%- set _ = _mod_signals.append("hosts entry points into this subsystem") -%}{%- endif -%}
-{%- if ctx.pagerank_mean is defined and ctx.pagerank_mean >= 0.005 -%}{%- set _ = _mod_signals.append("architecturally central (high mean PageRank across its files)") -%}{%- endif -%}
-{% if _mod_signals %}
-**Architectural signals:** {{ _mod_signals | join("; ") }}. Weave these into the opening rather than listing them.
-{% endif %}
-
-{% if ctx.is_rollup and ctx.child_pages %}
-### Child pages (this overview links down to these)
-Name each in backticks by its path so it resolves to a wiki link; explain in one clause what each covers and when a reader should go there.
-{% for cp in ctx.child_pages %}
-- **{{ cp.title }}** — `{{ cp.path }}`
-{% endfor %}
-{% endif %}
+```json
+{{ ctx.facts_json }}
+```
-{% if ctx.public_api %}
-### Public API (computed from the package manifests and re-exports; what a consumer imports)
-Name the central ones in backticks exactly as written and say what each is for; do not invent members beyond these.
-{% for e in ctx.public_api if e.signature %}
-- `{{ e.name }}` ({{ e.kind }}, `{{ e.file }}`): `` {{ e.signature }} ``{% if e.doc %}: {{ e.doc }}{% endif %}
-{% endfor %}
-{% for file, rows in ctx.public_api | rejectattr("signature") | groupby("file") %}
-- `{{ file }}`: {% for e in rows %}`{{ e.name }}`{% if e.alias_of %} (another name for `{{ e.alias_of }}`){% endif %}{% if not loop.last %}, {% endif %}{% endfor %}
-{% endfor %}
-{% if ctx.public_api_omitted %}
-- and {{ ctx.public_api_omitted }} more public names not listed
-{% endif %}
-{% endif %}
+Write the page in Markdown with exactly this shape.
-{% if ctx.entry_points %}
-### Entry points
-{% for ep in ctx.entry_points %}
-- `{{ ep }}`
-{% endfor %}
-{% endif %}
+# {{ ctx.title }}
-{% if ctx.key_files %}
-### Key files (highest PageRank first — read these first)
-{% for kf in ctx.key_files %}
-- `{{ kf.path }}`{% if kf.is_entry_point %} *(entry point)*{% endif %}{% if kf.summary %} — {{ kf.summary }}{% endif %}
-{% endfor %}
-{% endif %}
+An opening of 2 or 3 plain sentences: what this part of the system does, what it takes in and hands on, and why the rest of the system needs it. No file paths, numbers or identifiers in the opening. Do not open with a frame: "The X layer is the Y of Z", "X serves as the ...", "X acts as the ...", "X is the entry stage of ...", "it consumes ... and produces ..." and "This module contains N files" are all banned, because two pages that open with the same first five words read as one.
-{% if ctx.decision_records %}
-### Architectural decisions
-Use these to explain *why* the subsystem is shaped the way it is. Do not invent rationale beyond what is listed.
-{% for dr in ctx.decision_records[:5] %}
-- **{{ dr.title }}** — {{ dr.decision }}{% if dr.rationale %} *(Why: {{ dr.rationale }})*{% endif %}
-{% endfor %}
-{% endif %}
+Then one diagram in a fenced `mermaid` block, of the type the facts' `diagram` field names:
+- `sequenceDiagram`: draw `traced_flow` as one operation, with 4 to 6 participants and 6 to 10 messages. Participants are the parts involved under plain names, declared with one-word ids (`participant Store as Result store`); an outside caller or callee may be one participant. Messages follow the traced calls in order, each written as a short plain-English phrase for what the call does ("resolve call targets"), never the function's name.
+- `flowchart`: `flowchart LR` with 4 to 9 nodes for the parts that appear in `imports_between_parts`, under plain names, the directory in small text on a second line (`Resolvers["Resolvers<br/><small>resolvers/</small>"]`). Draw at most 10 edges, each one taken from `imports_between_parts`, pointing the way data or control flows and labelled with a short verb phrase (`-->|resolves imports for|`). At most 2 outside nodes from `depends_on` or `used_by`, marked `:::ext`, with `classDef ext stroke-dasharray:4 3;`.
+- `none`: no diagram.
+Node and participant ids are short CamelCase words (`GraphViews`), never a mermaid keyword such as `end`, `graph` or `style`. `classDef`, `class` and `style` lines belong in flowcharts only.
-{% if ctx.dependencies %}
-### Depends on (modules this imports)
-{% for dep in ctx.dependencies[:25] %}
-- `{{ dep }}`
-{% endfor %}
-{% endif %}
-
-{% if ctx.dependents %}
-### Depended on by (modules that import this)
-{% for dep in ctx.dependents[:25] %}
-- `{{ dep }}`
-{% endfor %}
-{% endif %}
-
-{% if ctx.external_systems %}
-### External systems used
-{% for sys in ctx.external_systems[:15] %}
-- `{{ sys.name }}`{% if sys.category and sys.category != 'library' %} *({{ sys.category }})*{% endif %}{% if sys.ecosystem %} — {{ sys.ecosystem }}{% endif %}
-{% endfor %}
-{% endif %}
-
-{% if ctx.key_classes %}
-### Class hierarchy
-{% for h in ctx.key_classes %}
-- `{{ h.child }}` {{ h.kind }} `{{ h.parent }}`{% if h.parent_file is defined and h.parent_file %} (in `{{ h.parent_file }}`){% endif %}
-{% endfor %}
-{% endif %}
-
-{% if ctx.declared_files %}
-### What other files declare (signatures only, no code shown)
-{% for line in ctx.declared_files %}
-- {{ line }}
-{% endfor %}
-{% endif %}
-{{ ctx.code_excerpts }}
+Then 3 to 5 sections, each a `##` heading that names a step or an idea in how the module works ("From a file to parsed symbols"), never a generic name such as Overview, Architecture, Key files, Public API, Dependencies or Summary. Each section is 1 to 3 short paragraphs that explain how and why. Put an identifier in backticks only where a reader would search for it. One section may carry a second small diagram when it walks a flow the first diagram does not show. End each section with one line, `Sources: ` followed by 1 to 3 file paths in backticks, written as in the facts, naming only files that section talks about.
-## How to write this page
+## Where to start reading
+Exactly 3 bullets: `path` - one sentence on why to read it first.
-Write the page now from the material above. Requirements:
+## How it connects
+One short paragraph, in words: what depends on this part of the system and what it depends on.
-- Open with one sentence that could only have been written about THIS subsystem, situating it against its siblings using the scope line. The opening sentence is stored as this page's summary and is shown as the module's description wherever the wiki is listed, so it has to carry information on its own.
- - Do not open with a frame. Every one of these is banned as an opening: "The X layer is the Y of Z", "The X layer serves as the ...", "The X layer acts as the ...", "X is the entry stage of ...", "it consumes ... and produces ...", and "This module contains N files".
- - Two module pages that open with the same first five words is the failure this rule exists to prevent. Name what this subsystem is responsible for, in words the material above forced on you.
-- Choose H2/H3 headings that name this subsystem's real concerns. There is no fixed heading list — do not emit generic "Overview / Public API / Architecture Notes" headings unless they are genuinely the right names here.
-- Synthesise across the whole file set. Draw on the material as a body of evidence; a file-by-file walkthrough is a failure even when accurate. Draw on many files, not one.
-- Put any enumerable list (key files, dependencies, decisions) in a markdown table where it reads better than prose.
-- Name the subsystem's key files and the neighbouring modules it consumes or serves in backticks exactly as written above so they resolve to wiki links. Mention a neighbour only where it explains this subsystem's role — no links for density, no reciprocal mentions for symmetry.
-- State behaviour only when an excerpt shows it; otherwise say what the file declares.
-- A commit subject is history, not current behaviour: if you cite one, label it (historical, <date>).
-- Third person throughout. No concluding or summary section.
-- End with the mandatory `## Questions this page answers` section: 3 to 6 real questions this page answers, phrased as a developer or agent would ask them.
+## Questions this page answers
+3 to 6 questions a developer or an agent would ask that this page answers, as a list. They are kept with the page for search, not shown in its body.
-Ground everything in the material above. Do not fabricate files, symbols, modules, or rationale that are not listed.
+Rules: 500 to 800 words before the questions. At most one table, and prefer none. No lists of symbols and no counts of files, commits or owners. Short sentences, active voice, third person. Never write markdown links: name a file, directory or child page by its path in backticks and the wiki links it. A style note at the top of this request changes voice and density; it does not change this shape. Use only the facts above: never invent files, symbols, edges or rationale. State behaviour only when an excerpt shows it; otherwise say what the file declares. A commit subject is history, not current behaviour: if you cite one, label it (historical, <date>).
diff --git a/tests/unit/generation/test_concept_package_walls.py b/tests/unit/generation/test_concept_package_walls.py
index 70d174c37..7e7a93a35 100644
--- a/tests/unit/generation/test_concept_package_walls.py
+++ b/tests/unit/generation/test_concept_package_walls.py
@@ -211,12 +211,10 @@ async def test_rollup_prompt_names_every_package_and_page_lists_them(sample_conf
packages=[{"path": f"packages/{n}", "files": 1} for n in ("alpha", "bravo", "charlie")],
)
prompt = provider._calls[-1]["user_prompt"]
- assert (
- "covers 3 sibling packages: `packages/alpha`, `packages/bravo`, `packages/charlie`"
- in prompt
- )
+ assert "several sibling packages" in prompt
assert "## Packages" in page.content
for n in ("alpha", "bravo", "charlie"):
+ assert f'"packages/{n}"' in prompt
assert f"| `packages/{n}` | 1 |" in page.content
diff --git a/tests/unit/generation/test_mermaid_validation.py b/tests/unit/generation/test_mermaid_validation.py
new file mode 100644
index 000000000..d30ae8ef4
--- /dev/null
+++ b/tests/unit/generation/test_mermaid_validation.py
@@ -0,0 +1,189 @@
+"""No page is stored with a mermaid block the renderer would reject.
+
+A diagram that fails to parse shows the reader an error box where the page
+promised a picture. The checks follow the diagram type: grammar a flowchart
+accepts (``classDef``) breaks a sequence diagram, and the reverse.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.generation.context_assembler import ContextAssembler
+from repowise.core.generation.mermaid_safety import (
+ invalid_mermaid_blocks,
+ mermaid_problems,
+ sanitize_mermaid,
+ strip_invalid_mermaid,
+)
+from repowise.core.generation.page_generator import PageGenerator
+from repowise.core.generation.page_generator.validation import (
+ InvalidMermaidError,
+ validate_generated_response,
+)
+from repowise.core.providers.llm.base import GeneratedResponse
+from repowise.core.providers.llm.mock import MockProvider
+
+_SEQUENCE = """sequenceDiagram
+ actor User
+ participant Cli as Command line
+ participant Core as Core pipeline
+ User->>Cli: start a run
+ Cli->>+Core: run the pipeline
+ loop each file
+ Core->>Core: parse it
+ end
+ Core-->>-Cli: results
+ Note over Cli: prints a summary"""
+
+_FLOWCHART = """flowchart LR
+ A["Parser<br/><small>parse/</small>"] -->|feeds| B["Graph"]
+ subgraph Store
+ C[(Database)]
+ end
+ B --> C
+ X:::ext --> A
+ classDef ext stroke-dasharray:4 3;"""
+
+
+def _block(body: str) -> str:
+ return f"# Page\n\nIntro.\n\n```mermaid\n{body}\n```\n\nAfter.\n"
+
+
+def test_well_formed_diagrams_pass():
+ assert mermaid_problems(_SEQUENCE) == []
+ assert mermaid_problems(_FLOWCHART) == []
+
+
+ ("body", "problem"),
+ [
+ (_SEQUENCE + "\n classDef ext stroke-dasharray:4 3;", "not sequence diagram syntax"),
+ ("sequenceDiagram\n A->>B: go\n loop again\n A->>B: go", "without its `end`"),
+ ("sequenceDiagram\n participant Core pipeline\n A->>B: go", "plain word"),
+ ("sequenceDiagram\n A calls B", "not a sequence diagram statement"),
+ ("flowchart LR\n subgraph S\n A --> B", "`subgraph` without a matching `end`"),
+ ("flowchart LR\n A --> B\n end", "`end` without a matching `subgraph`"),
+ ("flowchart LR\n end --> A", "illegal node id 'end'"),
+ ('flowchart LR\n graph["Graph views"] --> A', "illegal node id 'graph'"),
+ ('flowchart LR\n A["open --> B', "unbalanced"),
+ ("flowchat LR\n A --> B", "unknown diagram type"),
+ ("", "empty diagram"),
+ ],
+)
+def test_broken_diagrams_are_named(body, problem):
+ problems = mermaid_problems(body)
+ assert problems
+ assert problem in problems[0]
+
+
+def test_flowchart_styling_is_repaired_out_of_a_sequence_diagram():
+ raw = _block(_SEQUENCE + "\n classDef ext stroke-dasharray:4 3;\n class User ext;")
+
+ assert invalid_mermaid_blocks(raw)
+ assert invalid_mermaid_blocks(sanitize_mermaid(raw)) == []
+
+
+def test_stripping_keeps_the_page_and_drops_only_the_broken_block():
+ page = _block("flowchart LR\n end --> A") + "\n" + _block(_FLOWCHART)
+
+ stripped = strip_invalid_mermaid(page)
+
+ assert "end --> A" not in stripped
+ assert "classDef ext" in stripped
+ assert stripped.count("```mermaid") == 1
+ assert "Intro." in stripped and "After." in stripped
+
+
+def test_validation_rejects_a_page_with_an_unrenderable_diagram():
+ with pytest.raises(InvalidMermaidError):
+ validate_generated_response(
+ GeneratedResponse(
+ content=_block("sequenceDiagram\n A calls B"),
+ input_tokens=1,
+ output_tokens=1,
+ )
+ )
+
+
+def test_validation_accepts_what_the_repair_pass_fixes():
+ validate_generated_response(
+ GeneratedResponse(
+ content=_block(_SEQUENCE + "\n classDef ext stroke-dasharray:4 3;"),
+ input_tokens=1,
+ output_tokens=1,
+ )
+ )
+
+
+def _page(content: str) -> GeneratedResponse:
+ return GeneratedResponse(content=content, input_tokens=1, output_tokens=1)
+
+
+async def test_a_diagram_broken_twice_is_dropped_not_the_page(sample_config):
+ broken = _block("sequenceDiagram\n A calls B")
+ provider = MockProvider(responses=[_page(broken), _page(broken)])
+ generator = PageGenerator(provider, ContextAssembler(sample_config), sample_config)
+
+ response = await generator._call_provider("module_page", "Document this.", "request-id")
+
+ assert "```mermaid" not in response.content
+ assert "Intro." in response.content
+ assert "mermaid diagram will not render" in provider.calls[1]["user_prompt"]
+
+
+async def test_a_diagram_fixed_on_retry_is_kept(sample_config):
+ provider = MockProvider(
+ responses=[_page(_block("sequenceDiagram\n A calls B")), _page(_block(_SEQUENCE))]
+ )
+ generator = PageGenerator(provider, ContextAssembler(sample_config), sample_config)
+
+ response = await generator._call_provider("module_page", "Document this.", "request-id")
+
+ assert "Core->>Core: parse it" in response.content
+
+
+ "body",
+ [
+ "---\ntitle: Orders\n---\nflowchart LR\n A --> B",
+ "%%{init: {'theme': 'base'}}%%\nsequenceDiagram\n A->>B: go",
+ "block-beta\n columns 3\n a b c",
+ 'sequenceDiagram\n participant "Order service"\n A->>B: go',
+ "flowchart LR\n app.main --> app.db",
+ ],
+)
+def test_valid_mermaid_the_checks_do_not_know_well_still_passes(body):
+ assert mermaid_problems(body) == []
+
+
+async def test_a_retry_that_fails_otherwise_keeps_the_first_attempt_without_its_diagram(
+ sample_config,
+):
+ first = _block("sequenceDiagram\n A calls B")
+ second = "# Page\n\nIntro.\n\nLet me know if you would like more detail.\n"
+ provider = MockProvider(responses=[_page(first), _page(second)])
+ generator = PageGenerator(provider, ContextAssembler(sample_config), sample_config)
+
+ response = await generator._call_provider("module_page", "Document this.", "request-id")
+
+ assert "```mermaid" not in response.content
+ assert "After." in response.content
+ assert "Let me know" not in response.content
+
+
+def test_the_run_pass_removes_a_broken_block_from_any_page():
+ """An overview's map is embedded after the provider call, and a reused page
+ never reaches it; the pass every stored page goes through catches both."""
+ from types import SimpleNamespace
+
+ from repowise.core.generation.mermaid_safety import sanitize_pages
+
+ overview = SimpleNamespace(
+ page_id="repo_overview:r",
+ content=_block("flowchart LR\n end --> A") + "\n" + _block(_FLOWCHART),
+ )
+
+ assert sanitize_pages([overview]) == 1
+ assert overview.content.count("```mermaid") == 1
+ assert invalid_mermaid_blocks(overview.content) == []
diff --git a/tests/unit/generation/test_module_code_excerpts.py b/tests/unit/generation/test_module_code_excerpts.py
index 9941bbedf..ebf6557cf 100644
--- a/tests/unit/generation/test_module_code_excerpts.py
+++ b/tests/unit/generation/test_module_code_excerpts.py
@@ -8,6 +8,7 @@ keeps a line of signatures. Public API names are always listed.
from __future__ import annotations
+import json
from pathlib import Path
import networkx as nx
@@ -48,17 +49,17 @@ def _sources(repo: Path, parsed: dict) -> dict[str, bytes]:
return {p: (repo / p).read_bytes() for p in parsed}
-def _excerpt_share(ctx, config) -> int:
- """Tokens of the rendered prompt's Public API rows, declarations and excerpts."""
- prompt = PageGenerator(_RecordingProvider(), ContextAssembler(config), config)._render(
- "module_page.j2", ctx=ctx
+def _excerpt_share(ctx) -> int:
+ """Tokens the facts spend on Public API rows, declarations and excerpts."""
+ return estimate_tokens(
+ json.dumps({k: ctx.facts.get(k) for k in ("public_api", "code_excerpts", "declared")})
)
- api = prompt[prompt.index("### Public API") :]
- api = api[: api.index("\n##", 1)]
- starts = [prompt.find(h) for h in ("### What other files declare", "## Exact source")]
- end = prompt.index("## How to write")
- code = prompt[min((i for i in starts if i >= 0), default=end) : end]
- return estimate_tokens(api) + estimate_tokens(code)
+
+
+def _facts(prompt: str) -> dict:
+ """The facts object a module prompt carries."""
+ start = prompt.index("```json\n") + len("```json\n")
+ return json.loads(prompt[start : prompt.index("\n```", start)])
async def test_prompt_snapshot_has_public_api_excerpts_and_declarations(tmp_path, sample_config):
@@ -80,25 +81,24 @@ async def test_prompt_snapshot_has_public_api_excerpts_and_declarations(tmp_path
prompt = provider._calls[-1]["user_prompt"]
assert "State behaviour only when an excerpt shows it" in prompt
assert "(historical, <date>)" in prompt
+ facts = _facts(prompt)
# Nothing is left over at this size, so every candidate has its body.
- assert "### What other files declare" not in prompt
- # Fixtures are written in text mode, so a Windows checkout has CRLF sources.
- code = prompt[prompt.index("## Exact source excerpts") : prompt.index("## How to write")]
- code = code.replace("\r\n", "\n")
- assert code.count("<source-excerpt ") == 2
+ assert "declared" not in facts
+ excerpts = facts["code_excerpts"]
# Public API first, then the higher-ranked file; private names never.
- assert code.index('symbol="packages/kit/kit/client.py::Client"') < code.index(
- 'symbol="packages/kit/kit/util.py::slugify"'
- )
- assert (
- '<source-excerpt path="packages/kit/kit/util.py" '
- 'symbol="packages/kit/kit/util.py::slugify" lines="1-3">\n'
+ assert [e["symbol"] for e in excerpts] == [
+ "packages/kit/kit/client.py::Client",
+ "packages/kit/kit/util.py::slugify",
+ ]
+ slugify = excerpts[1]
+ assert (slugify["file"], slugify["lines"], slugify["truncated"]) == ("util.py", "1-3", False)
+ # Fixtures are written in text mode, so a Windows checkout has CRLF sources.
+ assert slugify["code"].replace("\r\n", "\n").startswith(
"def slugify(text: str) -> str:\n"
' """Lower-case words joined by dashes."""\n'
- ' return "-".join(text.lower().split())\n\n'
- "</source-excerpt>"
- ) in code
- assert "_hidden" not in code
+ ' return "-".join(text.lower().split())\n'
+ )
+ assert "_hidden" not in json.dumps(excerpts)
def _many_functions(n: int, body_lines: int) -> str:
@@ -127,8 +127,8 @@ async def test_budget_drops_bodies_first_and_keeps_every_public_name(
)
assert [e["name"] for e in ctx.public_api] == [e["name"] for e in api]
# Section headings and instructions sit outside the budget; allow for them.
- assert _excerpt_share(ctx, sample_config) <= budget + 200
- assert 0 < ctx.code_excerpts.count("<source-excerpt ") < 20
+ assert _excerpt_share(ctx) <= budget + 200
+ assert 0 < len(ctx.code_excerpts) < 20
# A file whose body was dropped keeps its signatures.
assert ctx.declared_files and all("def f0()" in line for line in ctx.declared_files)
@@ -143,8 +143,9 @@ async def test_a_long_body_is_capped_at_sixty_lines(tmp_path, sample_config):
parsed_files=parsed,
source_map=_sources(tmp_path, parsed),
)
- assert 'symbol="big.py::f0" lines="1-60" truncated="true"' in ctx.code_excerpts
- assert "x59 = 59" not in ctx.code_excerpts and "x58 = 58" in ctx.code_excerpts
+ [excerpt] = ctx.code_excerpts
+ assert (excerpt["symbol"], excerpt["lines"], excerpt["truncated"]) == ("big.py::f0", "1-60", True)
+ assert "x59 = 59" not in excerpt["code"] and "x58 = 58" in excerpt["code"]
def test_public_api_names_past_the_hard_cap_are_counted(sample_config):
@@ -163,7 +164,7 @@ def test_public_api_names_past_the_hard_cap_are_counted(sample_config):
"A", "typescript", [_context("a.ts")], nx.DiGraph(), public_api=api
)
assert ctx.public_api_omitted == len(api) - len(ctx.public_api) > 0
- assert _excerpt_share(ctx, sample_config) <= assembler_mod._MODULE_EXCERPT_HARD_CAP
+ assert _excerpt_share(ctx) <= assembler_mod._MODULE_EXCERPT_HARD_CAP
@pytest.mark.parametrize("budget", [60, 200, 10_000])
diff --git a/tests/unit/generation/test_module_facts.py b/tests/unit/generation/test_module_facts.py
new file mode 100644
index 000000000..a8af69872
--- /dev/null
+++ b/tests/unit/generation/test_module_facts.py
@@ -0,0 +1,158 @@
+"""The facts a module page is written from, and the diagram its shape calls for."""
+
+from __future__ import annotations
+
+import os
+import subprocess
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.generation.context.contexts import ModulePageContext
+from repowise.core.generation.context.module_facts import build_module_facts, module_base
+
+_FILES = [
+ "src/shop/orders/place.py",
+ "src/shop/orders/models.py",
+ "src/shop/billing/charge.py",
+ "src/shop/stock/reserve.py",
+ "src/shop/__init__.py",
+]
+
+
+@dataclass
+class _Flow:
+ trace: list[str]
+ entry_point_score: float = 1.0
+
+
+def _ctx(files=_FILES, entry_points=()) -> ModulePageContext:
+ return ModulePageContext(
+ title="Shop",
+ language="python",
+ total_symbols=0,
+ public_symbols=0,
+ entry_points=list(entry_points),
+ dependencies=[],
+ dependents=[],
+ pagerank_mean=0.0,
+ files=list(files),
+ )
+
+
+def _graph() -> nx.DiGraph:
+ g = nx.DiGraph()
+ for f in [*_FILES, "src/web/views.py", "tests/test_shop.py", "src/db/session.py"]:
+ g.add_node(f, is_test=f.startswith("tests/"))
+ g.nodes["tests/test_shop.py"]["is_test"] = True
+
+ def imports(a, b, *names):
+ g.add_edge(a, b, edge_type="imports", imported_names=list(names))
+
+ imports("src/shop/orders/place.py", "src/shop/billing/charge.py", "charge")
+ imports("src/shop/orders/place.py", "src/shop/stock/reserve.py", "reserve")
+ imports("src/shop/billing/charge.py", "src/shop/orders/models.py", "Order")
+ imports("src/shop/__init__.py", "src/shop/orders/place.py", "place_order")
+ imports("src/shop/stock/reserve.py", "src/db/session.py", "session")
+ imports("src/web/views.py", "src/shop/orders/place.py", "place_order")
+ imports("tests/test_shop.py", "src/shop/orders/place.py", "place_order")
+ for sym in ("place_order", "charge", "reserve", "save"):
+ g.add_node(f"x::{sym}", node_type="symbol", name=sym)
+ return g
+
+
+def test_the_base_is_the_deepest_shared_directory():
+ assert module_base(_FILES) == "src/shop"
+ assert module_base(["a.py", "b/c.py"]) == ""
+
+
+def test_parts_and_the_imports_between_them():
+ facts = build_module_facts(_ctx(), [], _graph())
+
+ assert {p["part"] for p in facts["parts"]} == {"orders/", "billing/", "stock/", "__init__.py"}
+ edges = {(e["from"], e["to"]): e for e in facts["imports_between_parts"]}
+ assert edges[("orders/", "billing/")]["names"] == ["charge"]
+ assert ("billing/", "orders/") in edges
+ # A package entry file re-exports everything; its edges would make a star.
+ assert not any(a == "__init__.py" for a, _ in edges)
+
+
+def test_neighbours_are_named_by_directory_and_tests_do_not_count():
+ facts = build_module_facts(_ctx(), [], _graph())
+
+ assert facts["depends_on"] == [{"area": "src/db/", "imports": 1}]
+ assert facts["used_by"] == [{"area": "src/web/", "imports": 1}]
+
+
+def test_connected_parts_get_a_flowchart():
+ assert build_module_facts(_ctx(), [], _graph())["diagram"] == "flowchart"
+
+
+def test_a_hub_with_a_flow_that_starts_here_gets_a_sequence():
+ flow = _Flow(
+ [
+ "src/shop/orders/place.py::place_order",
+ "src/shop/billing/charge.py::charge",
+ "src/shop/stock/reserve.py::reserve",
+ "src/db/session.py::save",
+ ]
+ )
+ facts = build_module_facts(
+ _ctx(entry_points=["src/shop/orders/place.py"]), [], _graph(), [flow]
+ )
+
+ assert facts["diagram"] == "sequenceDiagram"
+ assert [s["part"] for s in facts["traced_flow"]] == [
+ "orders/",
+ "billing/",
+ "stock/",
+ "outside: src/db/",
+ ]
+ assert facts["traced_flow"][0]["file"] == "orders/place.py"
+
+
+def test_a_flow_that_only_passes_through_is_not_used():
+ flow = _Flow(
+ [
+ "src/web/views.py::render",
+ "src/shop/orders/place.py::place_order",
+ "src/shop/billing/charge.py::charge",
+ "src/shop/stock/reserve.py::reserve",
+ ]
+ )
+ facts = build_module_facts(_ctx(), [], _graph(), [flow])
+
+ assert "traced_flow" not in facts
+
+
+def test_a_small_unconnected_module_draws_nothing():
+ files = ["lib/one.py", "lib/two.py"]
+ facts = build_module_facts(_ctx(files=files), [], nx.DiGraph())
+
+ assert facts["diagram"] == "none"
+ assert "imports_between_parts" not in facts
+
+
+def test_the_facts_are_identical_under_any_hash_seed():
+ """The facts are part of the prompt, and a page is reused only when the
+ prompt is byte-identical, so set iteration order must not leak into them."""
+ script = (
+ "import json, sys; sys.path.insert(0, sys.argv[1]);"
+ "import test_module_facts as t;"
+ "from repowise.core.generation.context.module_facts import build_module_facts;"
+ "print(json.dumps(build_module_facts(t._ctx(), [], t._graph())))"
+ )
+ here = str(Path(__file__).parent)
+ outputs = {
+ subprocess.run(
+ [sys.executable, "-c", script, here],
+ env={**os.environ, "PYTHONHASHSEED": seed},
+ capture_output=True,
+ text=True,
+ check=True,
+ ).stdout
+ for seed in ("1", "2", "3")
+ }
+ assert len(outputs) == 1
diff --git a/tests/unit/generation/test_module_page_readability.py b/tests/unit/generation/test_module_page_readability.py
new file mode 100644
index 000000000..c200447e0
--- /dev/null
+++ b/tests/unit/generation/test_module_page_readability.py
@@ -0,0 +1,166 @@
+"""A module page is stored in the shape a reader reads, whatever the model sent.
+
+Checked on the page as stored, after every post-processing step: no diagram
+the renderer rejects, no citation of a file that does not exist, the agent
+material in the digest, and headings that name what the module does. Every
+built-in style asks for the same shape.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import replace
+
+import networkx as nx
+import pytest
+
+from repowise.core.generation.context_assembler import ContextAssembler, FilePageContext
+from repowise.core.generation.mermaid_safety import invalid_mermaid_blocks
+from repowise.core.generation.page_generator import PageGenerator
+from repowise.core.providers.llm.mock import MockProvider
+
+_GENERIC_HEADINGS = {
+ "overview",
+ "architecture",
+ "key files",
+ "public api",
+ "dependencies",
+ "summary",
+ "introduction",
+ "components",
+}
+_REQUIRED_TAIL = ["Where to start reading", "How it connects"]
+
+
+def table_line_share(markdown: str) -> float:
+ lines = [line for line in markdown.splitlines() if line.strip()]
+ return sum(1 for line in lines if line.lstrip().startswith("|")) / max(1, len(lines))
+
+
+def generic_headings(markdown: str) -> list[str]:
+ return [
+ h for h in re.findall(r"^##\s+(.+?)\s*$", markdown, re.M) if h.lower() in _GENERIC_HEADINGS
+ ]
+
+
+_SECTION = (
+ "The {part} part {verb} every order that reaches it. It reads the basket, checks what the "
+ "shop still holds and records the outcome before anything is charged. Keeping this step in "
+ "one place means a failed check never leaves a half written order behind, and the next "
+ "step can trust what it receives. The work is small on purpose: each function does one "
+ "thing, and the order moves through them in a fixed sequence that is easy to follow when "
+ "something goes wrong. Retries happen here and not further along, because only this "
+ "step knows which half of the work already succeeded.\n\n"
+ "A reader who wants the rules should open `{file}` first. It keeps the decisions near the "
+ "data they depend on, so a change to one rule rarely touches another part of the flow. "
+ "Tests for the step sit beside it and describe each rule in plain words."
+)
+
+_RESPONSE = "\n\n".join(
+ [
+ "# Order Handling",
+ "Order handling turns a customer's basket into a paid, reserved order. It sits between "
+ "the web views that take requests and the store that keeps the results, so the rest of "
+ "the shop never deals with half finished orders.",
+ "```mermaid\nflowchart LR\n Orders[\"Orders<br/><small>orders/</small>\"] -->|asks to charge| "
+ "Billing[\"Billing<br/><small>billing/</small>\"]\n Orders -->|reserves stock in| "
+ "Stock[\"Stock<br/><small>stock/</small>\"]\n Web[\"Web views\"]:::ext -->|places orders "
+ "through| Orders\n classDef ext stroke-dasharray:4 3;\n```",
+ "## From a basket to a placed order",
+ _SECTION.format(part="orders", verb="validates", file="orders/place.py"),
+ "Sources: `orders/place.py`",
+ "## Taking the payment",
+ _SECTION.format(part="billing", verb="charges", file="billing/charge.py"),
+ "Sources: `billing/charge.py`",
+ "## Holding the stock",
+ _SECTION.format(part="stock", verb="reserves stock for", file="stock/reserve.py"),
+ "Sources: `stock/reserve.py`, `stock/ghost.py`",
+ "## Following one order",
+ "The order moves from the basket to the store.",
+ "```mermaid\nsequenceDiagram\n Orders calls Billing\n```",
+ "## Where to start reading",
+ "- `orders/place.py` - where an order starts.\n"
+ "- `billing/charge.py` - how payment is taken.\n"
+ "- `stock/reserve.py` - how stock is held.",
+ "## How it connects",
+ "Web views call into order handling, and order handling writes through the store.",
+ "## Questions this page answers",
+ "- How is an order placed?\n- Where is payment taken?",
+ ]
+)
+
+_FILES = ["src/shop/orders/place.py", "src/shop/billing/charge.py", "src/shop/stock/reserve.py"]
+
+
+class _Provider(MockProvider):
+ async def generate(self, *args, **kwargs):
+ response = await super().generate(*args, **kwargs)
+ return replace(response, content=_RESPONSE)
+
+
+def _context(path: str) -> FilePageContext:
+ return FilePageContext(
+ file_path=path,
+ language="python",
+ docstring=None,
+ symbols=[],
+ imports=[],
+ exports=[],
+ pagerank_score=0.1,
+ betweenness_score=0.0,
+ community_id=0,
+ dependents=[],
+ dependencies=[],
+ is_api_contract=False,
+ is_entry_point=False,
+ is_test=False,
+ parse_errors=[],
+ estimated_tokens=10,
+ )
+
+
+async def _page(config, provider=None):
+ gen = PageGenerator(provider or _Provider(), ContextAssembler(config), config)
+ graph = nx.DiGraph()
+ graph.add_nodes_from(_FILES)
+ return await gen.generate_module_page(
+ "Order Handling",
+ "python",
+ [_context(f) for f in _FILES],
+ graph,
+ target_path="src/shop",
+ structural_key="k",
+ )
+
+
+async def test_post_processing_keeps_the_shape_and_moves_agent_material(sample_config):
+ """What the pipeline does to a response, not what the fixture already is:
+ the broken diagram and the invented citation go, the questions move to the
+ digest, and the reading shape survives."""
+ page = await _page(sample_config)
+
+ assert page.content.count("```mermaid") == 1
+ assert invalid_mermaid_blocks(page.content) == []
+ assert "ghost.py" not in page.content
+ assert page.content.count("Sources: `") == 3
+ assert "Questions this page answers" not in page.content
+ assert page.digest.startswith("## Questions this page answers")
+ assert table_line_share(page.content) == 0
+ assert generic_headings(page.content) == []
+ headings = re.findall(r"^##\s+(.+?)\s*$", page.content, re.M)
+ assert headings[-2:] == _REQUIRED_TAIL
+
+
[email protected]("style", ["comprehensive", "caveman", "reference", "tutorial"])
+def test_every_style_keeps_the_page_shape(sample_config, style):
+ config = replace(sample_config, wiki_style=style)
+ gen = PageGenerator(MockProvider(), ContextAssembler(config), config)
+ ctx = gen._assembler.assemble_module_page(
+ "Order Handling", "python", [_context(f) for f in _FILES], nx.DiGraph()
+ )
+ prompt = gen._render("module_page.j2", ctx=ctx)
+
+ for rule in ("fenced `mermaid` block", "Sources: ", "## Where to start reading", "500 to 800"):
+ assert rule in prompt
+ if style != "comprehensive":
+ assert style.upper() in prompt
diff --git a/tests/unit/generation/test_package_public_api.py b/tests/unit/generation/test_package_public_api.py
index 67b22d6cf..ce32dc574 100644
--- a/tests/unit/generation/test_package_public_api.py
+++ b/tests/unit/generation/test_package_public_api.py
@@ -155,8 +155,9 @@ async def test_public_api_reaches_the_prompt_excerpts(tmp_path, sample_config):
public_api=api,
)
prompt = provider._calls[-1]["user_prompt"]
- assert "### Public API" in prompt
- assert "- `Client` (class, `packages/sdk/src/client.ts`): `` class Client" in prompt
+ assert '"public_api": [' in prompt
+ assert '"name": "Client"' in prompt
+ assert '"signature": "class Client' in prompt
assert "Talks to the service." in prompt
diff --git a/tests/unit/generation/test_page_sources.py b/tests/unit/generation/test_page_sources.py
new file mode 100644
index 000000000..2f8cac6dd
--- /dev/null
+++ b/tests/unit/generation/test_page_sources.py
@@ -0,0 +1,90 @@
+"""Every file a module page cites exists and is what its section talks about."""
+
+from __future__ import annotations
+
+from repowise.core.generation.page_sources import lint_sources
+
+_MEMBERS = [
+ "src/shop/orders/place.py",
+ "src/shop/orders/models.py",
+ "src/shop/billing/charge.py",
+ "src/shop/config.py",
+]
+_KNOWN = [*_MEMBERS, "src/web/config.py", "src/web/views.py"]
+_SYMBOLS = {"src/shop/billing/charge.py": ["charge_card"]}
+
+
+def _lint(content: str) -> str:
+ return lint_sources(
+ content, base="src/shop", members=_MEMBERS, known_paths=_KNOWN, symbols_by_file=_SYMBOLS
+ )
+
+
+def _page(section: str, sources: str) -> str:
+ return f"# Shop\n\nOpening.\n\n## Reading the basket\n\n{section}\n\nSources: {sources}\n"
+
+
+def test_a_named_existing_file_is_kept():
+ out = _lint(_page("`place.py` checks the basket first.", "`orders/place.py`"))
+ assert "Sources: `orders/place.py`" in out
+
+
+def test_a_missing_file_is_dropped_and_an_empty_line_goes_with_it():
+ out = _lint(_page("The planner checks the basket.", "`orders/planner.py`"))
+ assert "Sources" not in out
+ assert "The planner checks the basket." in out
+
+
+def test_a_file_the_section_never_mentions_is_dropped():
+ out = _lint(_page("`place.py` checks the basket.", "`orders/place.py`, `orders/models.py`"))
+ assert "Sources: `orders/place.py`" in out
+ assert "models.py" not in out.split("Sources:")[1]
+
+
+def test_a_symbol_or_the_part_name_is_enough():
+ out = _lint(_page("It calls `charge_card` on the way out.", "`billing/charge.py`"))
+ assert "Sources: `billing/charge.py`" in out
+ out = _lint(_page("Billing takes the payment.", "`billing/charge.py`"))
+ assert "Sources: `billing/charge.py`" in out
+
+
+def test_a_short_stem_matches_whole_words_only():
+ out = _lint(_page("Configuration-specific rules apply.", "`config.py`"))
+ assert "Sources" not in out
+
+
+def test_a_bare_name_resolves_to_the_member_and_is_rewritten():
+ # Two files are called config.py; the module's own one wins.
+ out = _lint(_page("`config.py` holds the defaults.", "config.py"))
+ assert "Sources: `config.py`" in out
+ out = _lint(_page("`charge.py` settles it.", "`charge.py`"))
+ assert "Sources: `billing/charge.py`" in out
+
+
+def test_a_directory_can_be_cited():
+ out = _lint(_page("The orders part owns the flow.", "`orders/`"))
+ assert "Sources: `orders/`" in out
+
+
+def test_start_reading_drops_a_file_that_does_not_exist():
+ content = (
+ "# Shop\n\n## Where to start reading\n\n"
+ "- `orders/place.py` - the entry.\n- `orders/ghost.py` - invented.\n"
+ "- `src/shop/config.py` - defaults.\n"
+ )
+ out = _lint(content)
+ assert "- `orders/place.py` - the entry." in out
+ assert "ghost" not in out
+ assert "- `config.py` - defaults." in out
+
+
+def test_text_outside_sources_lines_is_untouched():
+ page = _page("`place.py` checks the basket.", "`orders/place.py`")
+ assert _lint(page) == page
+
+
+def test_a_file_named_by_its_full_path_is_kept():
+ out = _lint(_page("`src/shop/billing/charge.py` settles the card.", "`charge.py`"))
+ assert "Sources: `billing/charge.py`" in out
+ out = _lint(_page("`billing/charge.py` settles the card.", "`billing/charge.py`"))
+ assert "Sources: `billing/charge.py`" in out
diff --git a/tests/unit/generation/test_templates.py b/tests/unit/generation/test_templates.py
index 29e31374d..41b919df1 100644
--- a/tests/unit/generation/test_templates.py
+++ b/tests/unit/generation/test_templates.py
@@ -8,6 +8,7 @@ from pathlib import Path
import jinja2
import pytest
+from repowise.core.generation.context.module_facts import build_module_facts
from repowise.core.generation.context_assembler import (
ApiContractContext,
FilePageContext,
@@ -265,7 +266,7 @@ def test_file_page_asks_about_importers_only_when_it_has_them(
@pytest.fixture(scope="module")
def module_page_ctx() -> ModulePageContext:
- return ModulePageContext(
+ ctx = ModulePageContext(
title="Calculation Engine",
language="python",
total_symbols=5,
@@ -277,6 +278,8 @@ def module_page_ctx() -> ModulePageContext:
files=["python_pkg/calculator.py", "python_pkg/models.py"],
directories=["python_pkg"],
)
+ ctx.facts = build_module_facts(ctx, [], None)
+ return ctx
def test_module_page_renders_without_error(jinja_env, module_page_ctx):