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(docs): deterministic architecture diagrams in wiki pages + present mode (#915)

Raghav Chamadiyae50408af37fd
diff --git a/packages/core/src/repowise/core/generation/architecture_mermaid.py b/packages/core/src/repowise/core/generation/architecture_mermaid.py
new file mode 100644
index 000000000..aecbb7e28
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/architecture_mermaid.py
@@ -0,0 +1,230 @@
+"""Deterministic architecture-diagram mermaid, built from the knowledge graph.
+
+The overview map and the per-layer diagrams are emitted straight from the KG
+(layers, curated modules, and ``imports`` edges) rather than authored by the
+LLM. Deterministic construction is free (no model call), can never emit a
+diagram that fails to render, and stays perfectly faithful to the graph.
+
+The output is intentionally style-free: no inline colors or ``classDef``. The
+rendering component (packages/ui MermaidDiagram) owns the palette through design
+tokens and is theme-aware, so a hardcoded fill here would break in dark mode.
+Boundary layers in a layer diagram are distinguished by node *shape*, not color.
+
+``build_overview_mermaid`` / ``build_layer_mermaid`` return ``None`` when the KG
+lacks the data to draw a useful diagram (older or uncurated indexes), so callers
+fall back cleanly to prior behavior.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import defaultdict
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .kg_context import KnowledgeGraphContext
+
+# --- tuning (mirrors the reviewed lab settings) ------------------------------
+_OVERVIEW_MODULES_PER_LAYER = 2 # top-N modules shown per layer in the hero map
+_OVERVIEW_MAX_EDGES = 16 # strongest inter-module edges kept in the hero
+_OVERVIEW_MIN_EDGE = 12 # drop dependencies weaker than this from the hero
+_LAYER_MODULES = 7 # module nodes inside one layer's own diagram
+_LAYER_MAX_INTRA_EDGES = 16
+_LAYER_BOUNDARY = 3 # deps-out / deps-in neighbour layers shown
+
+_MERMAID_BLOCK_RE = re.compile(r"```mermaid\b.*?```", re.DOTALL)
+
+
+def _slug(text: str) -> str:
+ """mermaid-safe node id."""
+ s = re.sub(r"[^A-Za-z0-9_]", "_", text)
+ if s and s[0].isdigit():
+ s = "n_" + s
+ return s or "n"
+
+
+def _short_module_label(module: dict) -> str:
+ """Short, readable label for a module node (last 1-2 path segments)."""
+ name = module.get("name") or ""
+ path = module.get("path") or ""
+ base = path or name
+ parts = [p for p in re.split(r"[\\/]", base) if p and p not in ("src", "packages")]
+ if not parts:
+ return name or path or module.get("id", "?")
+ return "/".join(parts[-2:]) if len(parts) >= 2 else parts[-1]
+
+
+def _esc(text: str) -> str:
+ """Quote-safe mermaid label text."""
+ return text.replace('"', "'").strip()
+
+
+class ArchitectureMermaidBuilder:
+ """Builds overview + per-layer mermaid from a KnowledgeGraphContext.
+
+ Indexes the graph once on construction so a run can draw the overview and
+ every layer diagram without re-aggregating the edge list each time.
+ """
+
+ def __init__(self, kg_ctx: KnowledgeGraphContext) -> None:
+ self._ok = bool(getattr(kg_ctx, "available", False))
+ self._layers: list[dict] = kg_ctx.get_layers() if self._ok else []
+ modules: list[dict] = kg_ctx.get_modules() if self._ok else []
+
+ self._mod_by_id: dict[str, dict] = {m["id"]: m for m in modules}
+ self._file_to_module: dict[str, str] = {}
+ for m in modules:
+ for nid in m.get("nodeIds", []):
+ if nid.startswith("file:"):
+ self._file_to_module[nid[5:]] = m["id"]
+
+ # modules per layer, ranked by size (file count)
+ self._modules_by_layer: dict[str, list[dict]] = defaultdict(list)
+ for m in modules:
+ lid = m.get("layerId")
+ if lid:
+ self._modules_by_layer[lid].append(m)
+ for lid in self._modules_by_layer:
+ self._modules_by_layer[lid].sort(key=lambda m: len(m.get("nodeIds", [])), reverse=True)
+
+ # file -> layer id
+ self._file_to_layer: dict[str, str] = {}
+ for ly in self._layers:
+ for nid in ly.get("nodeIds", []):
+ if nid.startswith("file:"):
+ self._file_to_layer[nid[5:]] = ly["id"]
+
+ # aggregate imports once: module->module and layer->layer counts
+ self._mod_edges: dict[tuple[str, str], int] = defaultdict(int)
+ self._layer_edges: dict[tuple[str, str], int] = defaultdict(int)
+ if self._ok:
+ for sf, tf in kg_ctx.iter_import_edges():
+ ms, mt = self._file_to_module.get(sf), self._file_to_module.get(tf)
+ if ms and mt and ms != mt:
+ self._mod_edges[(ms, mt)] += 1
+ ls, lt = self._file_to_layer.get(sf), self._file_to_layer.get(tf)
+ if ls and lt and ls != lt:
+ self._layer_edges[(ls, lt)] += 1
+
+ # -- overview -------------------------------------------------------------
+ def overview(self) -> str | None:
+ if not self._ok or not self._layers:
+ return None
+
+ selected: dict[str, dict] = {}
+ layer_nodes: dict[str, list[str]] = {}
+ for ly in self._layers:
+ mods = self._modules_by_layer.get(ly["id"], [])[:_OVERVIEW_MODULES_PER_LAYER]
+ layer_nodes[ly["id"]] = [m["id"] for m in mods]
+ for m in mods:
+ selected[m["id"]] = m
+ if not selected:
+ return None
+
+ kept = [
+ (ms, mt, c)
+ for (ms, mt), c in self._mod_edges.items()
+ if ms in selected and mt in selected and c >= _OVERVIEW_MIN_EDGE
+ ]
+ kept.sort(key=lambda x: x[2], reverse=True)
+ kept = kept[:_OVERVIEW_MAX_EDGES]
+
+ lines = ["flowchart LR"]
+ for ly in self._layers:
+ node_ids = layer_nodes.get(ly["id"], [])
+ if not node_ids:
+ continue
+ lines.append(f' subgraph {_slug(ly["id"])}["{_esc(ly["name"])}"]')
+ lines.append(" direction TB")
+ for mid in node_ids:
+ lines.append(f' {_slug(mid)}["{_esc(_short_module_label(selected[mid]))}"]')
+ lines.append(" end")
+ lines.append("")
+ mod_layer = {mid: self._mod_by_id[mid].get("layerId") for mid in selected}
+ for ms, mt, c in kept:
+ cross = mod_layer.get(ms) != mod_layer.get(mt)
+ arrow = "-->" if cross else "-.->"
+ lines.append(f' {_slug(ms)} {arrow}|"{c}"| {_slug(mt)}')
+ return "\n".join(lines)
+
+ # -- one layer ------------------------------------------------------------
+ def layer(self, layer: dict) -> str | None:
+ if not self._ok:
+ return None
+ lid = layer.get("id", "")
+ mods = self._modules_by_layer.get(lid, [])[:_LAYER_MODULES]
+ if not mods:
+ return None
+ sel = {m["id"]: m for m in mods}
+
+ intra = [
+ (ms, mt, c)
+ for (ms, mt), c in self._mod_edges.items()
+ if ms in sel and mt in sel and ms != mt
+ ]
+ intra.sort(key=lambda x: x[2], reverse=True)
+ intra = intra[:_LAYER_MAX_INTRA_EDGES]
+
+ name_by_id = {L["id"]: L["name"] for L in self._layers}
+ deps_out = sorted(
+ ((name_by_id.get(lt, lt), c) for (ls, lt), c in self._layer_edges.items() if ls == lid),
+ key=lambda x: x[1],
+ reverse=True,
+ )[:_LAYER_BOUNDARY]
+ deps_in = sorted(
+ ((name_by_id.get(ls, ls), c) for (ls, lt), c in self._layer_edges.items() if lt == lid),
+ key=lambda x: x[1],
+ reverse=True,
+ )[:_LAYER_BOUNDARY]
+
+ lines = ["flowchart TD"]
+ lines.append(f' subgraph core["{_esc(layer.get("name", "Layer"))} layer"]')
+ lines.append(" direction TB")
+ for mid in sel:
+ lines.append(f' {_slug(mid)}["{_esc(_short_module_label(sel[mid]))}"]')
+ for ms, mt, c in intra:
+ lines.append(f' {_slug(ms)} -->|"{c}"| {_slug(mt)}')
+ lines.append(" end")
+ # Boundary layers as stadium nodes (shape, not color, so it stays
+ # theme-safe): imported-by above, depends-on below.
+ if deps_in:
+ lines.append("")
+ for i, (name, c) in enumerate(deps_in):
+ nid = f"in_{i}"
+ lines.append(f' {nid}(["{_esc(name)}"])')
+ lines.append(f' {nid} ==>|"{c}"| core')
+ if deps_out:
+ lines.append("")
+ for i, (name, c) in enumerate(deps_out):
+ nid = f"out_{i}"
+ lines.append(f' {nid}(["{_esc(name)}"])')
+ lines.append(f' core -.->|"{c}"| {nid}')
+ return "\n".join(lines)
+
+
+def build_overview_mermaid(kg_ctx: KnowledgeGraphContext) -> str | None:
+ """Overview architecture map, or None when the KG can't support one."""
+ return ArchitectureMermaidBuilder(kg_ctx).overview()
+
+
+def build_layer_mermaid(kg_ctx: KnowledgeGraphContext, layer: dict) -> str | None:
+ """Per-layer diagram, or None when the layer has no curated modules."""
+ return ArchitectureMermaidBuilder(kg_ctx).layer(layer)
+
+
+def embed_mermaid(content: str, mermaid: str, *, heading: str) -> str:
+ """Return *content* with *mermaid* embedded, idempotently.
+
+ If the content already has a fenced mermaid block (the LLM's own, or one we
+ embedded on a prior run), its body is replaced. Otherwise the diagram is
+ appended under *heading*. Re-running on already-embedded content is a no-op,
+ so reused/cached pages stay stable across docs updates.
+ """
+ if not mermaid:
+ return content
+ block = f"```mermaid\n{mermaid}\n```"
+ if _MERMAID_BLOCK_RE.search(content):
+ # function replacement avoids backslash/group interpretation in mermaid
+ return _MERMAID_BLOCK_RE.sub(lambda _m: block, content, count=1)
+ sep = "" if content.endswith("\n") else "\n"
+ return f"{content}{sep}\n{heading}\n\n{block}\n"
diff --git a/packages/core/src/repowise/core/generation/context/contexts.py b/packages/core/src/repowise/core/generation/context/contexts.py
index 5ae2ebbf4..d68433a4c 100644
--- a/packages/core/src/repowise/core/generation/context/contexts.py
+++ b/packages/core/src/repowise/core/generation/context/contexts.py
@@ -118,6 +118,9 @@ class LayerPageContext:
tour_steps: list[dict] = field(default_factory=list)
entry_points: list[str] = field(default_factory=list)
edge_connectors: list[str] = field(default_factory=list)
+ # Deterministic per-layer architecture diagram (mermaid source), embedded
+ # into the page after generation. Empty when the KG can't produce one.
+ diagram_mermaid: str = ""
@dataclass
diff --git a/packages/core/src/repowise/core/generation/kg_context.py b/packages/core/src/repowise/core/generation/kg_context.py
index 031870994..b546cdec8 100644
--- a/packages/core/src/repowise/core/generation/kg_context.py
+++ b/packages/core/src/repowise/core/generation/kg_context.py
@@ -8,6 +8,7 @@ neighbor list, and optional tour step reference.
from __future__ import annotations
import json
+from collections.abc import Iterator
from dataclasses import dataclass, field
from pathlib import Path
@@ -183,6 +184,24 @@ class KnowledgeGraphContext:
"""Curated wiki modules from the KG artifact (empty when uncurated)."""
return self._modules if self._loaded else []
+ def iter_import_edges(self) -> Iterator[tuple[str, str]]:
+ """Yield (source_file, target_file) for every file->file imports edge.
+
+ Feeds the deterministic architecture-diagram builder, which aggregates
+ these into module- and layer-level dependency counts. Empty when the KG
+ isn't loaded.
+ """
+ if not self._loaded:
+ return
+ for edges in self._edges_by_source.values():
+ for e in edges:
+ if e.get("type") != "imports":
+ continue
+ src = e.get("source", "")
+ tgt = e.get("target", "")
+ if src.startswith("file:") and tgt.startswith("file:"):
+ yield src[5:], tgt[5:]
+
def get_tour(self) -> list[dict]:
return self._tour if self._loaded else []
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 ff8989462..4ebf664f9 100644
--- a/packages/core/src/repowise/core/generation/page_generator/levels.py
+++ b/packages/core/src/repowise/core/generation/page_generator/levels.py
@@ -307,10 +307,14 @@ def build_level5_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
if not run.kg_ctx.available:
return coros
+ from ..architecture_mermaid import ArchitectureMermaidBuilder
from ..context_assembler import LayerPageContext
_MIN_LAYER_FILES = 3
+ # One builder per run: indexes the graph once, then draws each layer.
+ diagram_builder = ArchitectureMermaidBuilder(run.kg_ctx)
+
for layer in run.kg_ctx.get_layers():
node_ids = layer.get("nodeIds", [])
file_paths = [nid[5:] for nid in node_ids if nid.startswith("file:")]
@@ -370,6 +374,7 @@ def build_level5_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
tour_steps=tour_steps,
entry_points=entry_points,
edge_connectors=edge_connectors,
+ diagram_mermaid=diagram_builder.layer(layer) or "",
)
coros.append((page_id, gen.generate_layer_page(ctx)))
@@ -398,11 +403,19 @@ def build_level6_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
)
)
if compute_page_id("architecture_diagram", run.repo_name) not in run.completed_ids:
+ from ..architecture_mermaid import build_overview_mermaid
+
+ overview_mermaid = build_overview_mermaid(run.kg_ctx)
coros.append(
(
compute_page_id("architecture_diagram", run.repo_name),
gen.generate_architecture_diagram(
- run.graph, run.pagerank, run.community, run.sccs, run.repo_name
+ run.graph,
+ run.pagerank,
+ run.community,
+ run.sccs,
+ run.repo_name,
+ overview_mermaid=overview_mermaid,
),
)
)
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 3eda035c1..8f0915b19 100644
--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py
+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py
@@ -17,6 +17,7 @@ import structlog
from repowise.core.ingestion.models import ParsedFile, RepoStructure
from .. import onboarding as _onboarding
+from ..architecture_mermaid import embed_mermaid
from ..context_assembler import FilePageContext, LayerPageContext
from ..models import GENERATION_LEVELS, GeneratedPage, compute_source_hash
@@ -228,6 +229,7 @@ class PerTypeGenerationMixin:
community: dict[str, int],
sccs: list[Any],
repo_name: str,
+ overview_mermaid: str | None = None,
) -> GeneratedPage:
ctx = self._assembler.assemble_architecture_diagram(
graph, pagerank, community, sccs, repo_name
@@ -236,6 +238,16 @@ class PerTypeGenerationMixin:
response = await self._call_provider(
"architecture_diagram", user_prompt, str(uuid.uuid4()), target_path=repo_name
)
+ # Swap the LLM's free-form diagram for the deterministic KG-derived map
+ # (idempotent, applies to fresh and reused content). Falls back to the
+ # LLM's own mermaid when the KG can't produce one.
+ if overview_mermaid:
+ response = replace(
+ response,
+ content=embed_mermaid(
+ response.content, overview_mermaid, heading="## Architecture map"
+ ),
+ )
return self._build_generated_page(
"architecture_diagram",
repo_name,
@@ -340,6 +352,15 @@ class PerTypeGenerationMixin:
response = await self._call_provider(
"layer_page", user_prompt, str(uuid.uuid4()), target_path=target
)
+ # Embed the deterministic per-layer diagram (idempotent, applies to fresh
+ # and reused content so it lands on both init and update).
+ if ctx.diagram_mermaid:
+ response = replace(
+ response,
+ content=embed_mermaid(
+ response.content, ctx.diagram_mermaid, heading="## Architecture"
+ ),
+ )
return self._build_generated_page(
"layer_page",
target,
diff --git a/packages/ui/__tests__/present/build-present-model.test.ts b/packages/ui/__tests__/present/build-present-model.test.ts
index 4f26ab84a..32eda3acb 100644
--- a/packages/ui/__tests__/present/build-present-model.test.ts
+++ b/packages/ui/__tests__/present/build-present-model.test.ts
@@ -137,6 +137,31 @@ describe("buildPresentModel", () => {
expect(model.deck[model.deck.length - 1]!.kind).toBe("closing");
});
+ it("builds a split slide for a layer page that embeds a diagram", () => {
+ const layerWithDiagram = makePage({
+ id: "ld",
+ page_type: "layer_page",
+ title: "Data layer",
+ content:
+ "# Data\n\nThe data layer persists and indexes everything the pipeline produces, and it is the durable backbone every other layer leans on.\n\n## Architecture\n\n```mermaid\nflowchart TD\nX-->Y\n```",
+ metadata: { layer_name: "Data" },
+ });
+ const model = buildPresentModel([overview, layerWithDiagram]);
+ const slide = model.deck.find((s) => s.eyebrow === "Layer");
+ expect(slide!.kind).toBe("split");
+ expect(slide!.mermaid).toContain("flowchart TD");
+ expect(slide!.bodyMarkdown).toBeTruthy();
+ // Prose column must not carry the diagram fence — it renders separately.
+ expect(slide!.bodyMarkdown).not.toContain("```mermaid");
+ });
+
+ it("keeps a plain section slide for a layer page without a diagram", () => {
+ const model = buildPresentModel([overview, layerCore]);
+ const slide = model.deck.find((s) => s.eyebrow === "Layer");
+ expect(slide!.kind).toBe("section");
+ expect(slide!.mermaid).toBeUndefined();
+ });
+
it("builds a walkthrough from the guided tour with time estimates", () => {
const model = buildPresentModel([overview, mainFile]);
expect(model.walkthrough).toHaveLength(2);
diff --git a/packages/ui/src/present/build-present-model.ts b/packages/ui/src/present/build-present-model.ts
index 02c6f1c30..ec2749e0f 100644
--- a/packages/ui/src/present/build-present-model.ts
+++ b/packages/ui/src/present/build-present-model.ts
@@ -153,12 +153,21 @@ export function buildPresentModel(
.sort((a, b) => rankOf(metaString(a, "layer_name")) - rankOf(metaString(b, "layer_name")))
.slice(0, MAX_LAYER_SLIDES);
for (const p of layerPages) {
+ // Layer pages generated with the deterministic architecture diagram embed
+ // it as a mermaid block; pair prose with diagram in a split slide. Older
+ // indexes without a diagram degrade to a plain prose section.
+ const layerChart = extractMermaidBlocks(p.content)[0];
+ let body = slideBody(p, DECK_BODY_CHARS);
+ // The diagram renders in its own column on a split slide, so keep any
+ // embedded fence out of the prose body.
+ if (layerChart) body = body.replace(/```mermaid[\s\S]*?```/g, "").trim();
deck.push({
id: `layer-${p.id}`,
- kind: "section",
+ kind: layerChart ? "split" : "section",
eyebrow: "Layer",
title: p.title,
- bodyMarkdown: slideBody(p, DECK_BODY_CHARS),
+ bodyMarkdown: body,
+ mermaid: layerChart,
sourcePageId: p.id,
sourcePath: p.target_path,
freshness: p.freshness_status,
@@ -236,7 +245,7 @@ export function buildPresentModel(
// slides so the walkthrough is never empty when a deck exists.
if (walkthrough.length === 0) {
walkthrough = deck
- .filter((s) => s.kind === "section" && s.bodyMarkdown)
+ .filter((s) => (s.kind === "section" || s.kind === "split") && s.bodyMarkdown)
.map((s, i) => ({
id: `step-${i}`,
order: i + 1,
diff --git a/packages/ui/src/present/deck-view.tsx b/packages/ui/src/present/deck-view.tsx
index b043e6237..41835bc2f 100644
--- a/packages/ui/src/present/deck-view.tsx
+++ b/packages/ui/src/present/deck-view.tsx
@@ -34,6 +34,9 @@ export function DeckView({ slides, index, onIndex, onOpenPage }: DeckViewProps)
const atEnd = index === slides.length - 1;
const isTitle = slide.kind === "title";
const isDiagram = slide.kind === "diagram";
+ // A layer slide pairing overview prose (left) with its diagram (right).
+ const isSplit = slide.kind === "split";
+ const isWide = isDiagram || isSplit;
return (
<div className="relative flex h-full flex-col">
@@ -41,7 +44,7 @@ export function DeckView({ slides, index, onIndex, onOpenPage }: DeckViewProps)
<div
className={cn(
"relative flex flex-1 items-center justify-center overflow-hidden py-4",
- isDiagram ? "px-4 sm:px-8" : "px-6 sm:px-16",
+ isWide ? "px-4 sm:px-8" : "px-6 sm:px-16",
)}
>
<AnimatePresence mode="wait">
@@ -53,55 +56,86 @@ export function DeckView({ slides, index, onIndex, onOpenPage }: DeckViewProps)
transition={{ duration: 0.22, ease: "easeOut" }}
className={cn(
"w-full",
- isTitle ? "max-w-3xl text-center" : isDiagram ? "max-w-6xl" : "max-w-3xl text-left",
+ isTitle ? "max-w-3xl text-center" : isWide ? "max-w-6xl" : "max-w-3xl text-left",
)}
>
- {slide.eyebrow && (
- <p className="mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--color-text-tertiary)]">
- {slide.eyebrow}
- </p>
- )}
- <h2
- className={cn(
- "font-serif font-semibold tracking-tight text-[var(--color-text-primary)]",
- isTitle ? "text-5xl sm:text-6xl" : isDiagram ? "text-2xl sm:text-3xl" : "text-3xl sm:text-4xl",
- )}
- >
- {slide.title}
- </h2>
-
- {slide.mermaid && (
- <div className="mt-4 flex justify-center">
- <div className="w-full">
- <MermaidDiagram chart={slide.mermaid} securityLevel="loose" />
+ {(() => {
+ const eyebrowEl = slide.eyebrow ? (
+ <p className="mb-3 text-xs font-semibold uppercase tracking-[0.14em] text-[var(--color-text-tertiary)]">
+ {slide.eyebrow}
+ </p>
+ ) : null;
+ const titleEl = (
+ <h2
+ className={cn(
+ "font-serif font-semibold tracking-tight text-[var(--color-text-primary)]",
+ isTitle
+ ? "text-5xl sm:text-6xl"
+ : isWide
+ ? "text-2xl sm:text-3xl"
+ : "text-3xl sm:text-4xl",
+ )}
+ >
+ {slide.title}
+ </h2>
+ );
+ const diagramEl = slide.mermaid ? (
+ <div className={cn("flex justify-center", isSplit ? "" : "mt-4")}>
+ <div className="w-full">
+ <MermaidDiagram chart={slide.mermaid} securityLevel="loose" />
+ </div>
</div>
- </div>
- )}
-
- {slide.bodyMarkdown && (
- <div
- className={cn(
- "mt-6 text-[var(--color-text-secondary)]",
- isTitle ? "mx-auto max-w-xl text-lg" : "text-base",
- )}
- >
- <WikiMarkdown content={slide.bodyMarkdown} />
- </div>
- )}
+ ) : null;
+ const bodyEl = slide.bodyMarkdown ? (
+ <div
+ className={cn(
+ "text-[var(--color-text-secondary)]",
+ isSplit ? "mt-4" : "mt-6",
+ isTitle ? "mx-auto max-w-xl text-lg" : "text-base",
+ )}
+ >
+ <WikiMarkdown content={slide.bodyMarkdown} />
+ </div>
+ ) : null;
+ const sourceEl =
+ slide.sourcePageId && onOpenPage ? (
+ <button
+ type="button"
+ onClick={() => onOpenPage(slide.sourcePageId!)}
+ className={cn(
+ "mt-6 inline-flex items-center gap-1.5 text-xs font-medium text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-accent-primary)]",
+ isTitle && "mx-auto",
+ )}
+ >
+ <ExternalLink className="h-3.5 w-3.5" />
+ Open{slide.sourcePath ? ` ${slide.sourcePath}` : ""} in reader
+ </button>
+ ) : null;
- {slide.sourcePageId && onOpenPage && (
- <button
- type="button"
- onClick={() => onOpenPage(slide.sourcePageId!)}
- className={cn(
- "mt-6 inline-flex items-center gap-1.5 text-xs font-medium text-[var(--color-text-tertiary)] transition-colors hover:text-[var(--color-accent-primary)]",
- isTitle && "mx-auto",
- )}
- >
- <ExternalLink className="h-3.5 w-3.5" />
- Open{slide.sourcePath ? ` ${slide.sourcePath}` : ""} in reader
- </button>
- )}
+ // Split: prose left, diagram right; stacks on narrow screens.
+ if (isSplit) {
+ return (
+ <div className="grid items-center gap-8 md:grid-cols-2">
+ <div className="min-w-0 text-left">
+ {eyebrowEl}
+ {titleEl}
+ {bodyEl}
+ {sourceEl}
+ </div>
+ <div className="min-w-0">{diagramEl}</div>
+ </div>
+ );
+ }
+ return (
+ <>
+ {eyebrowEl}
+ {titleEl}
+ {diagramEl}
+ {bodyEl}
+ {sourceEl}
+ </>
+ );
+ })()}
</motion.div>
</AnimatePresence>
diff --git a/packages/ui/src/present/types.ts b/packages/ui/src/present/types.ts
index c7ed926ea..c1ec57675 100644
--- a/packages/ui/src/present/types.ts
+++ b/packages/ui/src/present/types.ts
@@ -6,7 +6,9 @@
// Kept framework-free (plain data) so the same model serves the OSS dashboard
// and a future hosted app without re-implementing any logic.
-export type PresentSlideKind = "title" | "section" | "diagram" | "closing";
+// "split" pairs overview prose with a diagram side by side (used for layer
+// pages that carry a deterministic architecture diagram).
+export type PresentSlideKind = "title" | "section" | "diagram" | "split" | "closing";
export interface PresentSlide {
/** Stable id within the deck (slug), used as a React key. */
diff --git a/packages/ui/src/wiki/mermaid-diagram.tsx b/packages/ui/src/wiki/mermaid-diagram.tsx
index 8a97ba935..b8e900df3 100644
--- a/packages/ui/src/wiki/mermaid-diagram.tsx
+++ b/packages/ui/src/wiki/mermaid-diagram.tsx
@@ -74,6 +74,15 @@ function mermaidThemeConfig() {
stroke-width: 1.5px;
}
.cluster rect { stroke-dasharray: 8 5; rx: 12px; ry: 12px; }
+ /* Edge labels: mermaid draws the background rect from edgeLabelBackground
+ but leaves the label text uncolored, so labelled edges (the new
+ deterministic diagrams carry import counts) rendered as blank boxes.
+ Paint the text in the edge ink. */
+ .edgeLabel, .edgeLabel p, .edgeLabel span {
+ color: ${edge};
+ fill: ${edge};
+ font-weight: 600;
+ }
.nodes .node:first-of-type rect,
.nodes .node:first-of-type polygon,
.nodes .node:first-of-type circle {
diff --git a/tests/unit/generation/test_architecture_mermaid.py b/tests/unit/generation/test_architecture_mermaid.py
new file mode 100644
index 000000000..4ff69ed22
--- /dev/null
+++ b/tests/unit/generation/test_architecture_mermaid.py
@@ -0,0 +1,182 @@
+"""Tests for the deterministic architecture-diagram mermaid builder."""
+
+from __future__ import annotations
+
+from repowise.core.generation.architecture_mermaid import (
+ ArchitectureMermaidBuilder,
+ build_layer_mermaid,
+ build_overview_mermaid,
+ embed_mermaid,
+)
+from repowise.core.generation.kg_context import KnowledgeGraphContext
+
+
+def _kg() -> dict:
+ """Synthetic KG: two layers (UI, API), three modules, weighted imports.
+
+ ui/a -> api/a has 15 file-pair imports (a strong, kept edge); ui/b -> api/a
+ has 3 (below the overview floor, dropped); ui/a -> ui/b has 1 (an intra-UI
+ edge, shown only in the UI layer diagram).
+ """
+
+ def files(mod: str, n: int) -> list[str]:
+ return [f"{mod}/f{i}.py" for i in range(n)]
+
+ ui_a, ui_b, api_a = files("ui/a", 15), files("ui/b", 3), files("api/a", 15)
+ nodes = [{"id": f"file:{f}", "type": "file", "filePath": f} for f in ui_a + ui_b + api_a]
+
+ edges: list[dict] = []
+ for s, t in zip(ui_a, api_a, strict=True): # 15 cross-layer imports ui/a -> api/a
+ edges.append({"source": f"file:{s}", "target": f"file:{t}", "type": "imports"})
+ for s, t in zip(ui_b, api_a[:3], strict=True): # 3 cross-layer imports ui/b -> api/a
+ edges.append({"source": f"file:{s}", "target": f"file:{t}", "type": "imports"})
+ edges.append({"source": f"file:{ui_a[0]}", "target": f"file:{ui_b[0]}", "type": "imports"})
+
+ return {
+ "project": {"name": "t"},
+ "nodes": nodes,
+ "edges": edges,
+ "layers": [
+ {
+ "id": "layer:ui",
+ "name": "UI",
+ "description": "",
+ "nodeIds": [f"file:{f}" for f in ui_a + ui_b],
+ },
+ {
+ "id": "layer:api",
+ "name": "API",
+ "description": "",
+ "nodeIds": [f"file:{f}" for f in api_a],
+ },
+ ],
+ "modules": [
+ {
+ "id": "module:ui-a",
+ "name": "ui/a",
+ "path": "ui/a",
+ "layerId": "layer:ui",
+ "nodeIds": [f"file:{f}" for f in ui_a],
+ },
+ {
+ "id": "module:ui-b",
+ "name": "ui/b",
+ "path": "ui/b",
+ "layerId": "layer:ui",
+ "nodeIds": [f"file:{f}" for f in ui_b],
+ },
+ {
+ "id": "module:api-a",
+ "name": "api/a",
+ "path": "api/a",
+ "layerId": "layer:api",
+ "nodeIds": [f"file:{f}" for f in api_a],
+ },
+ ],
+ }
+
+
+def _ctx(kg: dict | None = None) -> KnowledgeGraphContext:
+ return KnowledgeGraphContext(None, data=kg if kg is not None else _kg())
+
+
+class TestOverview:
+ def test_shape_and_subgraphs(self):
+ ov = build_overview_mermaid(_ctx())
+ assert ov is not None
+ assert ov.startswith("flowchart LR")
+ # one subgraph per layer, module labels present
+ assert ov.count("subgraph") == 2
+ assert "ui/a" in ov and "api/a" in ov
+
+ def test_edge_floor_keeps_strong_drops_weak(self):
+ ov = build_overview_mermaid(_ctx())
+ # only the count-15 cross edge clears the floor; the count-3 and count-1
+ # edges are dropped
+ assert '|"15"|' in ov
+ assert '|"3"|' not in ov
+ assert ov.count("-->") == 1
+ assert ov.count("-.->") == 0
+
+ def test_no_inline_style_theme_safe(self):
+ ov = build_overview_mermaid(_ctx())
+ assert "#" not in ov # no raw hex — the renderer owns the palette
+ assert "classDef" not in ov and "style " not in ov
+
+
+class TestLayer:
+ def test_shape_modules_and_intra_edges(self):
+ c = _ctx()
+ ui = c.get_layers()[0]
+ lm = build_layer_mermaid(c, ui)
+ assert lm is not None
+ assert lm.startswith("flowchart TD")
+ assert '"UI layer"' in lm
+ assert "ui/a" in lm and "ui/b" in lm
+ assert '|"1"|' in lm # intra-layer ui/a -> ui/b
+
+ def test_boundary_layers_as_stadium_nodes(self):
+ c = _ctx()
+ ui = c.get_layers()[0]
+ lm = build_layer_mermaid(c, ui)
+ # UI depends on API with 15 + 3 = 18 imports, drawn as a stadium node
+ assert "API" in lm
+ assert '(["' in lm # stadium shape, not color, marks a boundary layer
+ assert '|"18"|' in lm
+
+ def test_no_inline_style_theme_safe(self):
+ c = _ctx()
+ lm = build_layer_mermaid(c, c.get_layers()[0])
+ assert "#" not in lm
+ assert "classDef" not in lm and "style " not in lm
+
+
+class TestFallbacks:
+ def test_unavailable_kg_returns_none(self):
+ c = KnowledgeGraphContext(None)
+ assert not c.available
+ assert build_overview_mermaid(c) is None
+ assert build_layer_mermaid(c, {"id": "layer:x", "name": "X"}) is None
+
+ def test_no_modules_returns_none(self):
+ kg = _kg()
+ kg.pop("modules")
+ c = _ctx(kg)
+ assert c.available
+ assert build_overview_mermaid(c) is None
+ assert build_layer_mermaid(c, c.get_layers()[0]) is None
+
+ def test_builder_reused_for_overview_and_layers(self):
+ b = ArchitectureMermaidBuilder(_ctx())
+ assert b.overview() is not None
+ assert b.layer(_ctx().get_layers()[0]) is not None
+
+
+class TestEmbed:
+ def test_append_when_no_block(self):
+ out = embed_mermaid("Prose.\n", "flowchart LR\nA-->B", heading="## Architecture")
+ assert "## Architecture" in out
+ assert out.count("```mermaid") == 1
+ assert "A-->B" in out
+
+ def test_append_is_idempotent(self):
+ c1 = embed_mermaid("Prose.\n", "flowchart LR\nA-->B", heading="## Architecture")
+ c2 = embed_mermaid(c1, "flowchart LR\nA-->B", heading="## Architecture")
+ assert c1 == c2
+ assert c2.count("```mermaid") == 1
+
+ def test_replaces_existing_block_and_keeps_surrounding_prose(self):
+ llm = "Intro\n```mermaid\ngraph TD\nX-->Y\n```\nOutro text"
+ out = embed_mermaid(llm, "flowchart LR\nA-->B", heading="## X")
+ assert out.count("```mermaid") == 1
+ assert "A-->B" in out and "X-->Y" not in out
+ assert "Intro" in out and "Outro text" in out
+
+ def test_replace_is_idempotent(self):
+ llm = "Intro\n```mermaid\ngraph TD\nX-->Y\n```\nOutro"
+ r1 = embed_mermaid(llm, "flowchart LR\nA-->B", heading="## X")
+ r2 = embed_mermaid(r1, "flowchart LR\nA-->B", heading="## X")
+ assert r1 == r2
+
+ def test_empty_mermaid_is_noop(self):
+ assert embed_mermaid("abc", "", heading="## X") == "abc"
diff --git a/tests/unit/generation/test_layer_pages.py b/tests/unit/generation/test_layer_pages.py
index a83f543e4..93d88e6f1 100644
--- a/tests/unit/generation/test_layer_pages.py
+++ b/tests/unit/generation/test_layer_pages.py
@@ -244,6 +244,47 @@ class TestBuildLevel5Coros:
# Page keyed by the layer's stable slug id, not its display name.
assert coros[0][0] == "layer_page:layer:core"
+ def test_layer_context_carries_diagram_when_modules_exist(self, tmp_path):
+ from unittest.mock import MagicMock
+
+ from repowise.core.generation.kg_context import KnowledgeGraphContext
+ from repowise.core.generation.page_generator.levels import build_level5_coros
+
+ files_a = [f"core/a/f{i}.py" for i in range(4)]
+ files_b = [f"core/b/f{i}.py" for i in range(3)]
+ nodes = [{"id": f"file:{f}", "filePath": f} for f in files_a + files_b]
+ edges = [{"source": f"file:{files_a[0]}", "target": f"file:{files_b[0]}",
+ "type": "imports"}]
+ layers = [{"id": "layer:core", "name": "Core", "description": "",
+ "nodeIds": [f"file:{f}" for f in files_a + files_b]}]
+ modules = [
+ {"id": "module:core-a", "name": "core/a", "path": "core/a",
+ "layerId": "layer:core", "nodeIds": [f"file:{f}" for f in files_a]},
+ {"id": "module:core-b", "name": "core/b", "path": "core/b",
+ "layerId": "layer:core", "nodeIds": [f"file:{f}" for f in files_b]},
+ ]
+ kg = {"nodes": nodes, "edges": edges, "layers": layers, "modules": modules, "tour": []}
+ for n in nodes:
+ full = tmp_path / n["filePath"]
+ full.parent.mkdir(parents=True, exist_ok=True)
+ full.touch()
+ kg_path = tmp_path / ".repowise" / "knowledge-graph.json"
+ kg_path.parent.mkdir(exist_ok=True)
+ kg_path.write_text(json.dumps(kg))
+
+ run = MagicMock()
+ run.kg_ctx = KnowledgeGraphContext(kg_path)
+ run.pagerank = {}
+ run.completed_page_summaries = {}
+ run.completed_ids = set()
+ run.gen = MagicMock()
+
+ coros = build_level5_coros(run)
+ assert len(coros) == 1
+ ctx = run.gen.generate_layer_page.call_args.args[0]
+ assert ctx.diagram_mermaid.startswith("flowchart TD")
+ assert "core/a" in ctx.diagram_mermaid
+
def test_skips_small_layers(self, tmp_path):
from repowise.core.generation.page_generator.levels import build_level5_coros