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(wiki): read the stored page tree in MCP, the docs tree and breadcrumbs (#1022)

Raghav Chamadiya5131f926993c
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.py
index 56c10ed9f..c8ec6c83e 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py
@@ -254,6 +254,26 @@ async def _load_overview_page(session: Any, repository: Any) -> Page | None:
return result.scalars().first()
+def _section_sort_key(section: str | None) -> tuple:
+ """Sort key that puts "8.10" after "8.9" instead of between "8.1" and "8.2".
+
+ Unplaced pages (no section) sort last rather than first, so a store whose
+ tree has not been rebuilt degrades to the previous title order instead of
+ leading with its least-placed pages.
+ """
+ if not section:
+ return (1,)
+ try:
+ return (0, tuple(int(part) for part in section.split(".")))
+ except ValueError:
+ return (0, ())
+
+
+def _module_order_key(page: Any) -> tuple:
+ """Outline position of a module page, falling back to its title."""
+ return (_section_sort_key(page.section_number), page.title or "")
+
+
async def _load_module_pages(
session: Any, repository: Any, collector: OmissionCollector
) -> list[Page]:
@@ -263,10 +283,14 @@ async def _load_module_pages(
.where(
Page.repository_id == repository.id,
Page.page_type == "module_page",
+ Page.freshness_status != "tombstone",
)
.order_by(Page.title)
)
- all_module_pages = result.scalars().all()
+ # Outline order, not alphabetical: the stored tree already ranks modules by
+ # the dependency layer they sit in, so the capped-to-8 list is the top of
+ # the spine rather than whatever sorts first.
+ all_module_pages = sorted(result.scalars().all(), key=_module_order_key)
if len(all_module_pages) > _MODULE_CAP:
collector.add(
f"module pages beyond cap={_MODULE_CAP} "
@@ -509,6 +533,135 @@ async def _build_architecture(session: Any, repository: Any) -> dict[str, Any]:
}
+# The outline is the whole wiki, so it is served shallow by default: the top
+# rung plus a descendant count per entry orients an agent in a few hundred
+# tokens. ``include=["outline"]`` opens the next rung.
+_OUTLINE_TOP_CAP = 40
+_OUTLINE_CHILD_CAP = 10
+
+
+async def _load_tree_rows(session: Any, repository: Any) -> list[Any]:
+ """Tree columns for every live page. Tombstones are deliberately unplaced."""
+ result = await session.execute(
+ select(
+ Page.id,
+ Page.title,
+ Page.page_type,
+ Page.target_path,
+ Page.parent_page_id,
+ Page.display_order,
+ Page.section_number,
+ ).where(
+ Page.repository_id == repository.id,
+ Page.freshness_status != "tombstone",
+ )
+ )
+ return list(result.tuples().all())
+
+
+def _outline_index(rows: list[Any]) -> tuple[Any | None, dict[str, list[Any]]]:
+ """Root row and parent → children map, or ``(None, {})`` for an unbuilt tree."""
+ by_id = {r.id: r for r in rows}
+ children: dict[str, list[Any]] = defaultdict(list)
+ claimed: set[str] = set()
+ for row in rows:
+ parent = row.parent_page_id
+ if parent and parent != row.id and parent in by_id:
+ children[parent].append(row)
+ claimed.add(row.id)
+ if not claimed:
+ # Every parent is null: the store predates the tree, or it has not been
+ # rebuilt since. An outline built from that would be a flat list
+ # dressed up as a hierarchy, so none is served.
+ return None, {}
+ for siblings in children.values():
+ siblings.sort(key=lambda r: (r.display_order or 0, r.target_path or "", r.id))
+ candidates = [r for r in rows if r.id not in claimed and r.id in children]
+ root = next(
+ (r for r in candidates if r.page_type == "repo_overview"),
+ candidates[0] if candidates else None,
+ )
+ return root, children
+
+
+def _count_descendants(row: Any, children: dict[str, list[Any]], seen: set[str]) -> int:
+ """Size of a subtree, guarding against a parent cycle rather than recursing into one."""
+ if row.id in seen:
+ return 0
+ seen.add(row.id)
+ return sum(1 + _count_descendants(c, children, seen) for c in children.get(row.id, []))
+
+
+def _outline_node(
+ row: Any, children: dict[str, list[Any]], depth: int, collector: OmissionCollector
+) -> dict[str, Any]:
+ node: dict[str, Any] = {
+ "section": row.section_number,
+ "page_id": row.id,
+ "title": row.title,
+ "page_type": row.page_type,
+ }
+ if row.target_path:
+ node["target_path"] = row.target_path
+ kids = children.get(row.id, [])
+ if kids:
+ node["descendants"] = _count_descendants(row, children, set())
+ if kids and depth > 0:
+ cap = _OUTLINE_CHILD_CAP
+ if len(kids) > cap:
+ collector.add(
+ f"outline children of {row.id} beyond cap={cap} ({len(kids) - cap} dropped)",
+ "\n".join(f"{k.section_number} {k.title}: {k.target_path}" for k in kids[cap:]),
+ )
+ node["children"] = [_outline_node(k, children, depth - 1, collector) for k in kids[:cap]]
+ return node
+
+
+def _build_outline(rows: list[Any], depth: int, collector: OmissionCollector) -> dict[str, Any]:
+ """The stored page tree, rooted at the repo overview.
+
+ This is the same hierarchy the web app and the editor extension render:
+ onboarding pages, then the architecture diagram, then the dependency spine
+ of layers with their modules, files and cycles underneath. Each entry
+ carries the dotted ``section`` it was assigned at generation time, so a
+ page id quoted anywhere else in this response can be located in it.
+ """
+ root, children = _outline_index(rows)
+ if root is None:
+ return {}
+ top = children.get(root.id, [])
+ reachable = 1 + _count_descendants(root, children, set())
+ if len(top) > _OUTLINE_TOP_CAP:
+ collector.add(
+ f"outline top-level entries beyond cap={_OUTLINE_TOP_CAP} "
+ f"({len(top) - _OUTLINE_TOP_CAP} dropped)",
+ "\n".join(
+ f"{r.section_number} {r.title}: {r.target_path}" for r in top[_OUTLINE_TOP_CAP:]
+ ),
+ )
+ outline: dict[str, Any] = {
+ "root": {"page_id": root.id, "title": root.title},
+ "total_pages": len(rows),
+ "sections": [
+ _outline_node(r, children, depth - 1, collector) for r in top[:_OUTLINE_TOP_CAP]
+ ],
+ }
+ if len(top) > _OUTLINE_TOP_CAP:
+ # Siblings are ordered by type rank, so the served entries are the
+ # spine (onboarding, diagram, layers, modules) and what falls off the
+ # end is the long tail of cycles and loose files. Say so rather than
+ # letting the list read as the whole top rung.
+ outline["sections_total"] = len(top)
+ outline["sections_truncated"] = True
+ # Pages the tree has no place for — a dangling parent, or a page generated
+ # since the last rebuild. Reported rather than quietly missing, so the
+ # section count is never read as the page count.
+ unplaced = len(rows) - reachable
+ if unplaced > 0:
+ outline["unplaced_pages"] = unplaced
+ return outline
+
+
async def _build_reading_order(session: Any, repository: Any) -> list[dict[str, Any]]:
"""Canonical onboarding spine — only slots that actually produced a page."""
ro_result = await session.execute(
@@ -537,6 +690,12 @@ async def _build_reading_order(session: Any, repository: Any) -> list[dict[str,
"title": p.title,
"page_id": p.id,
"target_path": p.target_path,
+ # Where this page sits in the outline. The two orders differ on
+ # purpose: reading order is the onboarding curriculum, keyed by
+ # slot, and it starts at the overview and the architecture
+ # guide, which the outline places as the root and a diagram
+ # rather than as steps one and two.
+ "section": p.section_number,
}
)
return reading_order
@@ -689,7 +848,9 @@ def _dedupe_tour_steps(tour: list[dict[str, Any]]) -> list[dict[str, Any]]:
return deduped
-def _build_guided_tour(overview_page: Page, result: dict[str, Any]) -> None:
+def _build_guided_tour(
+ overview_page: Page, result: dict[str, Any], sections: dict[str, str | None]
+) -> None:
"""Attach the topology-driven guided tour + layer order from overview page metadata."""
from repowise.core.generation.models import compute_page_id
@@ -699,19 +860,24 @@ def _build_guided_tour(overview_page: Page, result: dict[str, Any]) -> None:
ov_meta = {}
tour = _dedupe_tour_steps(ov_meta.get("guided_tour") or [])
if tour:
- result["guided_tour"] = [
- {
- "order": s.get("order"),
- "title": s.get("title"),
- "kind": s.get("kind"),
- "reason": s.get("reason"),
- "target_path": s.get("target_path"),
- "page_id": compute_page_id(
- s.get("page_type", "file_page"), s.get("target_path", "")
- ),
- }
- for s in tour
- ]
+ steps = []
+ for s in tour:
+ page_id = compute_page_id(s.get("page_type", "file_page"), s.get("target_path", ""))
+ steps.append(
+ {
+ "order": s.get("order"),
+ "title": s.get("title"),
+ "kind": s.get("kind"),
+ "reason": s.get("reason"),
+ "target_path": s.get("target_path"),
+ "page_id": page_id,
+ # A tour step is a walk of the import graph, so it crosses
+ # the outline rather than following it; the section says
+ # which part of the tree each stop landed in.
+ "section": sections.get(page_id),
+ }
+ )
+ result["guided_tour"] = steps
result["guided_tour_hint"] = (
"Topology-ordered walk of the codebase: read these page_ids "
"in order — entry points first, then the files they import, "
@@ -726,9 +892,10 @@ def _build_guided_tour(overview_page: Page, result: dict[str, Any]) -> None:
async def get_overview(repo: str | None = None, include: list[str] | None = None) -> dict:
"""Architecture map for an unfamiliar repo — first call when you don't know your way around.
- Returns the synthesised overview plus key modules, entry points, repo-wide
- git health (hotspot count, churn trend, bus-factor distribution), the
- knowledge map (top owners, knowledge silos), and the community summary.
+ Returns the synthesised overview plus the wiki outline (the stored page
+ tree, top rung), key modules, entry points, repo-wide git health (hotspot
+ count, churn trend, bus-factor distribution), the knowledge map (top
+ owners, knowledge silos), and the community summary.
Skip this on subsequent calls — once you have the map, jump straight to
``get_context`` / ``get_answer``.
@@ -745,7 +912,8 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
Args:
repo: Repository alias, path, or ID. Use ``"all"`` for workspace overview.
include: Opt-in extras. ``"content"`` returns the full overview essay in
- ``content_md`` instead of the compact summary section.
+ ``content_md`` instead of the compact summary section. ``"outline"``
+ expands the page tree one rung deeper (modules under their layer).
"""
if repo == "all":
return await _workspace_overview()
@@ -776,6 +944,9 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
community_summary = _build_community_summary(all_nodes)
architecture = await _build_architecture(session, repository)
reading_order = await _build_reading_order(session, repository)
+ tree_rows = await _load_tree_rows(session, repository)
+ sections = {r.id: r.section_number for r in tree_rows}
+ outline = _build_outline(tree_rows, 2 if "outline" in set(include or []) else 1, collector)
title = _resolve_title(overview_page, repository)
code_health = await _build_code_health(session, repository)
key_decisions_section = await _build_key_decisions(session, repository, exclude_spec)
@@ -793,6 +964,9 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
"name": p.title,
"path": p.target_path,
"description": _module_description(p.content),
+ "page_id": p.id,
+ "section": p.section_number,
+ "parent_page_id": p.parent_page_id,
}
for p in module_pages
],
@@ -808,6 +982,17 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
'Call get_overview(include=["content"]) for the full walkthrough.'
)
+ if outline:
+ result["outline"] = outline
+ result["outline_hint"] = (
+ "The stored page tree — the same outline the web app and the "
+ "editor extension render. Every 'section' in this response "
+ "indexes into it, and 'descendants' is how much sits below an "
+ "entry. Top rung only by default; call "
+ 'get_overview(include=["outline"]) for one level deeper, then '
+ "get_context on an entry's target_path to read it."
+ )
+
if architecture:
result["architecture"] = architecture
@@ -826,7 +1011,7 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
# from the import graph (entry points first, then inward, infra last).
# Persisted on the repo_overview page metadata at generation time.
if overview_page:
- _build_guided_tour(overview_page, result)
+ _build_guided_tour(overview_page, result, sections)
# Append workspace context footer when in workspace mode
ws_footer = _build_workspace_footer()
diff --git a/packages/ui/__tests__/docs/doc-nav.test.ts b/packages/ui/__tests__/docs/doc-nav.test.ts
new file mode 100644
index 000000000..dafe49133
--- /dev/null
+++ b/packages/ui/__tests__/docs/doc-nav.test.ts
@@ -0,0 +1,176 @@
+import { describe, it, expect } from "vitest";
+import { computeDocNav } from "../../src/docs/doc-nav.js";
+import type { DocPage } from "@repowise-dev/types/docs";
+
+function makePage(overrides: Partial<DocPage> = {}): DocPage {
+ return {
+ id: "p1",
+ repository_id: "r1",
+ page_type: "file_page",
+ title: "Page",
+ content: "",
+ target_path: "src/foo.ts",
+ source_hash: "h",
+ model_name: "m",
+ provider_name: "g",
+ input_tokens: 0,
+ output_tokens: 0,
+ cached_tokens: 0,
+ generation_level: 1,
+ version: 1,
+ confidence: 0.9,
+ freshness_status: "fresh",
+ metadata: {},
+ human_notes: null,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ ...overrides,
+ };
+}
+
+const ROOT = makePage({
+ id: "repo_overview:demo",
+ page_type: "repo_overview",
+ title: "Repository Overview: demo",
+ target_path: "demo",
+ parent_page_id: null,
+});
+const LAYER = makePage({
+ id: "layer_page:layer:runtime",
+ page_type: "layer_page",
+ title: "Layer: Runtime",
+ target_path: "layer:runtime",
+ parent_page_id: ROOT.id,
+ display_order: 2,
+});
+const MODULE = makePage({
+ id: "module_page:community-7",
+ page_type: "module_page",
+ // A community-clustered module: its target_path is a clustering ordinal, so
+ // no file path can ever be a prefix of it. Path splitting cannot find this
+ // ancestor at all; the stored parent can.
+ title: "Module: runtime/engine",
+ target_path: "community-7",
+ parent_page_id: LAYER.id,
+ display_order: 1,
+});
+const FILE_B = makePage({
+ id: "file_page:runtime/engine/b.py",
+ title: "b.py",
+ target_path: "runtime/engine/b.py",
+ parent_page_id: MODULE.id,
+ display_order: 1,
+});
+const FILE_A = makePage({
+ id: "file_page:runtime/engine/a.py",
+ title: "a.py",
+ target_path: "runtime/engine/a.py",
+ parent_page_id: MODULE.id,
+ display_order: 2,
+});
+
+const PAGES = [ROOT, LAYER, MODULE, FILE_B, FILE_A];
+
+describe("computeDocNav", () => {
+ it("walks stored parents rather than splitting the path", () => {
+ const nav = computeDocNav(FILE_B, PAGES);
+ expect(nav.breadcrumbs.map((b) => b.label)).toEqual([
+ "Runtime",
+ "runtime/engine",
+ "b.py",
+ ]);
+ // Every ancestor crumb links to a real page, which is the point: a path
+ // segment often has no page behind it.
+ expect(nav.breadcrumbs.map((b) => b.pageId)).toEqual([
+ LAYER.id,
+ MODULE.id,
+ FILE_B.id,
+ ]);
+ });
+
+ it("omits the repo root, which the caller prepends itself", () => {
+ const nav = computeDocNav(MODULE, PAGES);
+ expect(nav.breadcrumbs.map((b) => b.pageId)).toEqual([LAYER.id, MODULE.id]);
+ });
+
+ it("orders siblings by stored order, not by path", () => {
+ // b.py is stored first even though a.py sorts first alphabetically.
+ const nav = computeDocNav(FILE_B, PAGES);
+ expect(nav.prev).toBeUndefined();
+ expect(nav.next?.pageId).toBe(FILE_A.id);
+ expect(computeDocNav(FILE_A, PAGES).prev?.pageId).toBe(FILE_B.id);
+ });
+
+ it("stops at a parent cycle instead of looping forever", () => {
+ const a = makePage({ id: "a", target_path: "a.py", title: "a.py", parent_page_id: "b" });
+ const b = makePage({ id: "b", target_path: "b.py", title: "b.py", parent_page_id: "a" });
+ const nav = computeDocNav(a, [a, b]);
+ expect(nav.breadcrumbs.length).toBeLessThanOrEqual(3);
+ expect(nav.breadcrumbs.at(-1)?.pageId).toBe("a");
+ });
+
+ it("falls back to the path split when the store has no tree", () => {
+ // Pages written before the hierarchy existed carry no parent at all.
+ const mod = makePage({
+ id: "module_page:src",
+ page_type: "module_page",
+ title: "Module: src",
+ target_path: "src",
+ });
+ const file = makePage({ id: "f", target_path: "src/foo.ts", title: "foo.ts" });
+ const nav = computeDocNav(file, [mod, file]);
+ expect(nav.breadcrumbs.map((b) => b.label)).toEqual(["src", "foo.ts"]);
+ expect(nav.breadcrumbs[0]?.pageId).toBe(mod.id);
+ });
+
+ it("keeps the directory trail for a page hanging off the repo root", () => {
+ // The tree places files no module claimed directly under the overview. A
+ // lone basename crumb would say less than the path the page still carries.
+ const loose = makePage({
+ id: "file_page:docs/design/contrast_check.py",
+ title: "contrast_check.py",
+ target_path: "docs/design/contrast_check.py",
+ parent_page_id: ROOT.id,
+ });
+ const nav = computeDocNav(loose, [ROOT, loose]);
+ expect(nav.breadcrumbs.map((b) => b.label)).toEqual([
+ "docs",
+ "design",
+ "contrast_check.py",
+ ]);
+ });
+
+ it("labels ancestors with their page type so callers need not guess", () => {
+ const nav = computeDocNav(FILE_B, PAGES);
+ expect(nav.breadcrumbs.map((b) => b.pageType)).toEqual([
+ "layer_page",
+ "module_page",
+ "file_page",
+ ]);
+ });
+
+ it("keeps a cycle page's derived name rather than its raw graph id", () => {
+ const cycle = makePage({
+ id: "scc_page:scc-1050",
+ page_type: "scc_page",
+ title: "Circular Dependency: scc-1050",
+ // No back-ticked member paths in the content, so sccDisplayLabel has
+ // nothing to derive from and falls back to the title.
+ content: "These modules import each other.",
+ target_path: "scc-1050",
+ parent_page_id: LAYER.id,
+ });
+ const nav = computeDocNav(cycle, [ROOT, LAYER, cycle]);
+ expect(nav.breadcrumbs.at(-1)?.label).toBe("Circular Dependency: scc-1050");
+ });
+
+ it("shows a single label for a page with no path and no parent", () => {
+ const overview = makePage({
+ id: "o",
+ page_type: "repo_overview",
+ title: "Overview",
+ target_path: "",
+ });
+ expect(computeDocNav(overview, [overview]).breadcrumbs).toEqual([{ label: "Overview" }]);
+ });
+});
diff --git a/packages/ui/__tests__/docs/docs-tree.test.tsx b/packages/ui/__tests__/docs/docs-tree.test.tsx
index 8f2ef69a6..929de027a 100644
--- a/packages/ui/__tests__/docs/docs-tree.test.tsx
+++ b/packages/ui/__tests__/docs/docs-tree.test.tsx
@@ -35,6 +35,77 @@ function makePage(overrides: Partial<DocPage> = {}): DocPage {
};
}
+// A stored tree whose sibling order deliberately DISAGREES with the alphabet:
+// the dependency spine puts "Zebra Runtime" above "Alpha API". A fixture whose
+// spine and alphabet agree cannot tell the two orderings apart, so it would
+// pass whether or not the component reads the stored order at all.
+const ROOT = makePage({
+ id: "repo_overview:demo",
+ page_type: "repo_overview",
+ title: "Repository Overview: demo",
+ target_path: "demo",
+ parent_page_id: null,
+ display_order: 0,
+ section_number: null,
+});
+const ONBOARDING = makePage({
+ id: "onboarding:onboarding/getting_started",
+ page_type: "onboarding",
+ title: "Getting Started",
+ target_path: "onboarding/getting_started",
+ metadata: { subkind: "getting_started" },
+ parent_page_id: ROOT.id,
+ display_order: 1,
+ section_number: "1",
+});
+const LAYER_RUNTIME = makePage({
+ id: "layer_page:layer:runtime",
+ page_type: "layer_page",
+ title: "Layer: Zebra Runtime",
+ target_path: "layer:runtime",
+ parent_page_id: ROOT.id,
+ display_order: 2,
+ section_number: "2",
+});
+const LAYER_API = makePage({
+ id: "layer_page:layer:api",
+ page_type: "layer_page",
+ title: "Layer: Alpha API",
+ target_path: "layer:api",
+ parent_page_id: ROOT.id,
+ display_order: 3,
+ section_number: "3",
+});
+const MODULE = makePage({
+ id: "module_page:runtime/engine",
+ page_type: "module_page",
+ title: "Module: runtime/engine",
+ target_path: "runtime/engine",
+ parent_page_id: LAYER_RUNTIME.id,
+ display_order: 1,
+ section_number: "2.1",
+});
+const DEEP_FILE = makePage({
+ id: "file_page:runtime/engine/resolvers/dotnet/index.py",
+ page_type: "file_page",
+ title: "index.py",
+ target_path: "runtime/engine/resolvers/dotnet/index.py",
+ parent_page_id: MODULE.id,
+ display_order: 1,
+ section_number: "2.1.1",
+});
+
+const SPINE = [ROOT, ONBOARDING, LAYER_RUNTIME, LAYER_API, MODULE, DEEP_FILE];
+
+/** Rendered row labels, in document order. */
+function rowLabels(): string[] {
+ return screen.getAllByRole("button").map((b) => b.textContent ?? "");
+}
+
+function indexOfRow(fragment: string): number {
+ return rowLabels().findIndex((label) => label.includes(fragment));
+}
+
describe("DocsTree", () => {
it("renders page nodes from the supplied pages array", () => {
render(
@@ -65,65 +136,203 @@ describe("DocsTree", () => {
expect(onSelectPage).toHaveBeenCalledWith(target);
});
- it("claims deep files for their nearest module ancestor", () => {
- const mod = makePage({
- id: "module_page:core/ingestion",
- page_type: "module_page",
- title: "Module: core/ingestion",
- target_path: "core/ingestion",
- });
- const deepFile = makePage({
- id: "file_page:core/ingestion/resolvers/dotnet/index.py",
- page_type: "file_page",
- title: "index.py",
- target_path: "core/ingestion/resolvers/dotnet/index.py",
- });
+ it("orders top-level rows by the stored spine, not alphabetically", () => {
+ render(
+ <DocsTree pages={SPINE} selectedPageId={null} onSelectPage={() => {}} />,
+ );
+ // Every layer is a top-level row, so this asserts on what a reader sees
+ // without expanding anything — the failure mode that let a layer-ordering
+ // bug ship green twice.
+ const overview = indexOfRow("Repository Overview: demo");
+ const onboarding = indexOfRow("Getting Started");
+ const zebra = indexOfRow("Zebra Runtime");
+ const alpha = indexOfRow("Alpha API");
+ expect(overview).toBeGreaterThanOrEqual(0);
+ expect(overview).toBeLessThan(onboarding);
+ expect(onboarding).toBeLessThan(zebra);
+ expect(zebra).toBeLessThan(alpha);
+ // Reversing the stored order must reverse the render, or the assertion
+ // above is only reading the array we happened to pass in.
+ expect("Zebra Runtime".localeCompare("Alpha API")).toBeGreaterThan(0);
+ });
+
+ it("follows the stored order when it is the reverse of the input array", () => {
+ // Same pages, passed in alphabetical order, with the spine unchanged.
render(
<DocsTree
- pages={[mod, deepFile]}
+ pages={[ROOT, LAYER_API, LAYER_RUNTIME, ONBOARDING, MODULE, DEEP_FILE]}
selectedPageId={null}
onSelectPage={() => {}}
/>,
);
- // Curated module name renders (path-shaped, not a raw graph id).
- const modNode = screen.getByText("core/ingestion");
- expect(modNode).toBeInTheDocument();
- // Expanding the module reveals the deep file, named relative to the
- // module dir so nested files stay unambiguous.
- fireEvent.click(modNode);
- expect(
- screen.getByText("resolvers/dotnet/index.py"),
- ).toBeInTheDocument();
+ expect(indexOfRow("Zebra Runtime")).toBeLessThan(indexOfRow("Alpha API"));
});
- it("prefers the deepest module when modules nest", () => {
- const outer = makePage({
- id: "module_page:core",
- page_type: "module_page",
- title: "Module: core",
- target_path: "core",
- });
- const inner = makePage({
- id: "module_page:core/ingestion",
- page_type: "module_page",
- title: "Module: core/ingestion",
- target_path: "core/ingestion",
- });
- const file = makePage({
- id: "file_page:core/ingestion/parser.py",
- page_type: "file_page",
- title: "parser.py",
- target_path: "core/ingestion/parser.py",
+ it("shows the stored section number on the top rung", () => {
+ render(
+ <DocsTree pages={SPINE} selectedPageId={null} onSelectPage={() => {}} />,
+ );
+ expect(rowLabels().some((l) => l.startsWith("2") && l.includes("Zebra Runtime"))).toBe(true);
+ expect(rowLabels().some((l) => l.startsWith("3") && l.includes("Alpha API"))).toBe(true);
+ });
+
+ it("nests modules under their stored layer and files under their module", () => {
+ render(
+ <DocsTree pages={SPINE} selectedPageId={null} onSelectPage={() => {}} />,
+ );
+ // The module is not visible until its layer is expanded.
+ expect(screen.queryByText("runtime/engine")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByText("Zebra Runtime"));
+ fireEvent.click(screen.getByText("runtime/engine"));
+ // Named relative to its module, so files with the same basename in
+ // different resolver directories stay distinguishable.
+ expect(screen.getByText("resolvers/dotnet/index.py")).toBeInTheDocument();
+ });
+
+ it("hides tombstoned pages, which the tree deliberately leaves unplaced", () => {
+ const gone = makePage({
+ id: "file_page:deleted.py",
+ target_path: "deleted.py",
+ title: "deleted.py",
+ freshness_status: "tombstone",
+ parent_page_id: null,
+ display_order: 0,
});
render(
<DocsTree
- pages={[outer, inner, file]}
+ pages={[...SPINE, gone]}
+ selectedPageId={null}
+ onSelectPage={() => {}}
+ />,
+ );
+ expect(screen.queryByText("deleted.py")).not.toBeInTheDocument();
+ });
+
+ it("keeps pages the stored tree does not reach, grouped by type", () => {
+ // A store whose tree has not been rebuilt: every parent is null. Nothing
+ // may disappear just because it has no recorded place.
+ render(
+ <DocsTree
+ pages={[
+ makePage({ id: "a", target_path: "src/a.ts", title: "a.ts" }),
+ makePage({
+ id: "m",
+ page_type: "module_page",
+ target_path: "src",
+ title: "Module: src",
+ }),
+ ]}
+ selectedPageId={null}
+ onSelectPage={() => {}}
+ />,
+ );
+ expect(screen.getByText("Module (1)")).toBeInTheDocument();
+ expect(screen.getByText("File (1)")).toBeInTheDocument();
+ expect(screen.getByText("a.ts")).toBeInTheDocument();
+ expect(screen.getByText("src")).toBeInTheDocument();
+ });
+
+ it("survives a parent cycle instead of dropping the pages in it", () => {
+ const a = makePage({ id: "a", target_path: "a.ts", title: "a.ts", parent_page_id: "b" });
+ const b = makePage({ id: "b", target_path: "b.ts", title: "b.ts", parent_page_id: "a" });
+ render(
+ <DocsTree pages={[...SPINE, a, b]} selectedPageId={null} onSelectPage={() => {}} />,
+ );
+ expect(screen.getByText("File (2)")).toBeInTheDocument();
+ });
+
+ it("collapses a long run of leaves so it cannot bury the spine", () => {
+ // This repo's own overview carries 53 cycle pages and 55 loose file pages
+ // as direct children; listed inline they push the layers out of sight.
+ const cycles = Array.from({ length: 20 }, (_, i) =>
+ makePage({
+ id: `scc_page:${i}`,
+ page_type: "scc_page",
+ title: `Circular Dependency: scc-${i}`,
+ target_path: `scc-${i}`,
+ parent_page_id: ROOT.id,
+ display_order: 10 + i,
+ section_number: `${10 + i}`,
+ }),
+ );
+ render(
+ <DocsTree
+ pages={[...SPINE, ...cycles]}
+ selectedPageId={null}
+ onSelectPage={() => {}}
+ />,
+ );
+ expect(screen.getByText("SCC (20)")).toBeInTheDocument();
+ // Collapsed, and still after the layers it used to bury.
+ expect(screen.queryByText("scc-0")).not.toBeInTheDocument();
+ expect(indexOfRow("Zebra Runtime")).toBeLessThan(indexOfRow("SCC (20)"));
+ // The layers themselves are never bucketed — they have children, so they
+ // are the hierarchy rather than a list.
+ expect(screen.getByText("Zebra Runtime")).toBeInTheDocument();
+ expect(screen.getByText("Alpha API")).toBeInTheDocument();
+ });
+
+ it("leaves a short run of leaves inline", () => {
+ const few = Array.from({ length: 3 }, (_, i) =>
+ makePage({
+ id: `infra_page:${i}`,
+ page_type: "infra_page",
+ title: `infra-${i}.yml`,
+ target_path: `deploy/infra-${i}.yml`,
+ parent_page_id: ROOT.id,
+ display_order: 10 + i,
+ }),
+ );
+ render(
+ <DocsTree pages={[...SPINE, ...few]} selectedPageId={null} onSelectPage={() => {}} />,
+ );
+ expect(screen.queryByText(/^Infra \(/)).not.toBeInTheDocument();
+ expect(screen.getByText("infra-0.yml")).toBeInTheDocument();
+ });
+
+ it("does not bucket the whole file layer on a deterministic-mode wiki", () => {
+ // Every file page is template-generated. The "Auto-documented" group
+ // exists to keep that tail from drowning AI-written pages; with no
+ // AI-written file pages to protect it would swallow the entire leaf level.
+ const auto = (id: string, path: string) =>
+ makePage({
+ id,
+ target_path: path,
+ title: path,
+ parent_page_id: MODULE.id,
+ display_order: 1,
+ is_deterministic: true,
+ });
+ render(
+ <DocsTree
+ pages={[ROOT, LAYER_RUNTIME, MODULE, auto("f1", "runtime/engine/a.py"), auto("f2", "runtime/engine/b.py")]}
+ selectedPageId={null}
+ onSelectPage={() => {}}
+ />,
+ );
+ expect(screen.queryByText(/Auto-documented/)).not.toBeInTheDocument();
+ fireEvent.click(screen.getByText("Zebra Runtime"));
+ fireEvent.click(screen.getByText("runtime/engine"));
+ expect(screen.getByText("a.py")).toBeInTheDocument();
+ });
+
+ it("still groups the coverage tail when AI-written file pages exist", () => {
+ render(
+ <DocsTree
+ pages={[
+ ...SPINE,
+ makePage({
+ id: "auto1",
+ target_path: "runtime/engine/generated.py",
+ title: "generated.py",
+ parent_page_id: MODULE.id,
+ is_deterministic: true,
+ }),
+ ]}
selectedPageId={null}
onSelectPage={() => {}}
/>,
);
- fireEvent.click(screen.getByText("core/ingestion"));
- // File appears under the inner module (relative name), not the outer one.
- expect(screen.getByText("parser.py")).toBeInTheDocument();
+ expect(screen.getByText(/Auto-documented \(1\)/)).toBeInTheDocument();
});
});
diff --git a/packages/ui/src/docs/doc-nav.ts b/packages/ui/src/docs/doc-nav.ts
index 0a71160ad..5336e2b74 100644
--- a/packages/ui/src/docs/doc-nav.ts
+++ b/packages/ui/src/docs/doc-nav.ts
@@ -1,16 +1,33 @@
// Framework-neutral navigation helpers for the wiki reader.
//
-// These derive a hierarchical breadcrumb trail (repo / module / file) and
-// sibling prev/next links from the flat page list the API already returns —
-// no extra endpoint needed. The host app turns the returned ``pageId`` values
-// into hrefs (route shape differs between the CLI web app and hosted frontend).
+// The breadcrumb trail and the sibling prev/next links are read from the
+// stored page tree (``parent_page_id`` / ``display_order``), the same one the
+// docs tree renders and ``get_overview`` serves, so a page's ancestry is the
+// same wherever it is shown. It used to be re-derived here by splitting
+// ``target_path`` and matching module pages by path prefix, which was a third
+// independent guess at the hierarchy.
+//
+// A store written before the tree existed has no parents at all; those pages
+// fall back to the path split, so an un-rebuilt wiki keeps working breadcrumbs
+// rather than losing them until it is re-indexed.
+//
+// The host app turns the returned ``pageId`` values into hrefs (route shape
+// differs between the CLI web app and hosted frontend).
import type { DocPage } from "@repowise-dev/types/docs";
+import { treeLabel } from "./page-labels";
export interface DocNavSegment {
label: string;
/** Present when this segment maps to a real page that can be linked. */
pageId?: string;
+ /**
+ * Page type of the linked page. Ancestors in the stored tree are whatever
+ * the tree put there — a module, but equally a layer or the file a symbol
+ * was spotted in — so a caller that wants "the module this sits in" has to
+ * ask rather than assume the second-to-last crumb is one.
+ */
+ pageType?: string;
}
export interface DocSiblingLink {
@@ -30,13 +47,66 @@ function parentDir(path: string): string {
return i === -1 ? "" : path.slice(0, i);
}
+/** Ancestors of ``page``, outermost first, excluding the root and the page. */
+function ancestors(page: DocPage, byId: Map<string, DocPage>): DocPage[] {
+ const chain: DocPage[] = [];
+ const seen = new Set<string>([page.id]);
+ let current = byId.get(page.parent_page_id ?? "");
+ while (current && !seen.has(current.id)) {
+ seen.add(current.id);
+ // The repo root is the crumb the caller prepends; repeating it here would
+ // show the repository name twice.
+ if (current.parent_page_id) chain.unshift(current);
+ current = byId.get(current.parent_page_id ?? "");
+ }
+ return chain;
+}
+
+/** The label a page carries in a trail — the same one the docs tree shows. */
+function crumbLabel(page: DocPage): string {
+ return treeLabel(page, undefined);
+}
+
/**
- * Derive breadcrumbs + sibling prev/next for ``page`` given the full page
- * list. Breadcrumb ancestors link to their ``module_page`` when one exists,
- * so readers can zoom out a level at a time.
+ * Breadcrumbs + sibling prev/next for ``page`` given the full page list.
+ *
+ * Ancestors are walked up ``parent_page_id`` and each links to a real page, so
+ * a reader can zoom out one documented level at a time — a module, then the
+ * layer it sits in — rather than through directory names that may have no page
+ * behind them.
*/
export function computeDocNav(page: DocPage, pages: DocPage[]): DocNavInfo {
- // Special / synthetic pages (overview, onboarding, architecture) have no
+ const byId = new Map(pages.map((p) => [p.id, p]));
+ const chain = page.parent_page_id ? ancestors(page, byId) : [];
+
+ // Only when there is a documented ancestor to show. A page hanging directly
+ // off the repo root has none, and a lone basename crumb would say less than
+ // the directory trail the path still carries, so those keep the path split.
+ if (chain.length > 0) {
+ const breadcrumbs: DocNavSegment[] = [
+ ...chain.map((a) => ({
+ label: crumbLabel(a),
+ pageId: a.id,
+ pageType: a.page_type,
+ })),
+ { label: crumbLabel(page), pageId: page.id, pageType: page.page_type },
+ ];
+
+ // Siblings are the pages sharing this parent, in stored order. Unlike the
+ // old same-type/same-directory rule, "next" walks the outline the reader
+ // is actually looking at.
+ const siblings = pages
+ .filter((p) => p.parent_page_id === page.parent_page_id)
+ .sort(
+ (a, b) =>
+ (a.display_order ?? 0) - (b.display_order ?? 0) ||
+ (a.target_path || a.title).localeCompare(b.target_path || b.title),
+ );
+ return { breadcrumbs, ...siblingLinks(siblings, page) };
+ }
+
+ // No stored parent: either a root/synthetic page, or a store predating the
+ // tree. Special pages (overview, onboarding, architecture) have no
// meaningful filesystem path — show a single label, no siblings.
if (!page.target_path) {
return { breadcrumbs: [{ label: page.title }] };
@@ -69,9 +139,6 @@ export function computeDocNav(page: DocPage, pages: DocPage[]): DocNavInfo {
});
}
- // Sibling prev/next: pages of the same type sharing the immediate parent
- // directory, ordered by path. Keeps "next" within a coherent group rather
- // than jumping across unrelated page types.
const dir = parentDir(page.target_path);
const siblings = pages
.filter(
@@ -82,13 +149,19 @@ export function computeDocNav(page: DocPage, pages: DocPage[]): DocNavInfo {
)
.sort((a, b) => a.target_path.localeCompare(b.target_path));
+ return { breadcrumbs, ...siblingLinks(siblings, page) };
+}
+
+function siblingLinks(
+ siblings: DocPage[],
+ page: DocPage,
+): { prev?: DocSiblingLink; next?: DocSiblingLink } {
const idx = siblings.findIndex((p) => p.id === page.id);
- const result: DocNavInfo = { breadcrumbs };
- if (idx !== -1) {
- const prev = siblings[idx - 1];
- const next = siblings[idx + 1];
- if (prev) result.prev = { pageId: prev.id, title: prev.title };
- if (next) result.next = { pageId: next.id, title: next.title };
- }
- return result;
+ if (idx === -1) return {};
+ const prev = siblings[idx - 1];
+ const next = siblings[idx + 1];
+ return {
+ ...(prev ? { prev: { pageId: prev.id, title: prev.title } } : {}),
+ ...(next ? { next: { pageId: next.id, title: next.title } } : {}),
+ };
}
diff --git a/packages/ui/src/docs/docs-reader.tsx b/packages/ui/src/docs/docs-reader.tsx
index 59072f4a4..461eb60b0 100644
--- a/packages/ui/src/docs/docs-reader.tsx
+++ b/packages/ui/src/docs/docs-reader.tsx
@@ -192,12 +192,23 @@ function DocsReaderBody({
[page.content, persona],
);
+ // The nearest ancestor that is actually a module. Breadcrumbs now come from
+ // the stored tree, whose ancestors can be a layer or the file a symbol was
+ // spotted in; showing either as "in <name>" would repeat the layer chip
+ // rendered right beside it, or claim a file is a module.
const moduleSeg = useMemo(
() =>
[...nav.breadcrumbs]
.slice(0, -1)
.reverse()
- .find((s) => s.pageId && s.pageId !== page.id),
+ .find(
+ (s) =>
+ s.pageId &&
+ s.pageId !== page.id &&
+ // Older callers (and the path-split fallback) carry no page type;
+ // those segments were always module-or-directory, so they stand.
+ (s.pageType === undefined || s.pageType === "module_page"),
+ ),
[nav.breadcrumbs, page.id],
);
diff --git a/packages/ui/src/docs/docs-tree.tsx b/packages/ui/src/docs/docs-tree.tsx
index cf1fcdc6e..365d4ce07 100644
--- a/packages/ui/src/docs/docs-tree.tsx
+++ b/packages/ui/src/docs/docs-tree.tsx
@@ -11,13 +11,9 @@ import {
Filter,
FolderTree,
Network,
- Layers,
- BookOpen,
- FileText,
} from "lucide-react";
import {
ALL_PAGE_TYPES,
- ONBOARDING_ORDER,
ONBOARDING_SLOT_TITLES,
getOnboardingSlot,
getPageTypeIcon,
@@ -25,6 +21,7 @@ import {
isDeterministicPage,
type OnboardingSlot,
} from "../lib/page-types";
+import { RAW_GRAPH_ID, displayLabel, treeLabel } from "./page-labels";
import { cn } from "../lib/cn";
import { statusBadgeClasses, type FreshnessStatus } from "../lib/confidence";
import type { DocPage } from "@repowise-dev/types/docs";
@@ -53,6 +50,8 @@ interface TreeNode {
isDir: boolean;
page?: DocPage;
children: TreeNode[];
+ /** Dotted outline number from the stored tree ("2.4.1"), when the page has one. */
+ section?: string;
}
interface DocsTreeProps {
@@ -88,20 +87,22 @@ function buildOnboardingFolder(pages: DocPage[]): TreeNode | null {
}
if (bySlot.size === 0) return null;
- // Render in canonical reading order. Slots without a page (gated out at
- // generation time) are silently skipped.
- const children: TreeNode[] = [];
- for (const slot of ONBOARDING_ORDER) {
- const page = bySlot.get(slot);
- if (!page) continue;
- children.push({
+ // Reading order comes from the stored tree (`display_order`, assigned once
+ // at generation time), not from a slot list duplicated in TypeScript. A
+ // store written before the tree existed has every order at 0; the title
+ // tiebreak keeps that case stable rather than dependent on map insertion.
+ const children: TreeNode[] = [...bySlot.entries()]
+ .sort(
+ ([, a], [, b]) =>
+ (a.display_order ?? 0) - (b.display_order ?? 0) || a.title.localeCompare(b.title),
+ )
+ .map(([slot, page]) => ({
name: ONBOARDING_SLOT_TITLES[slot],
path: page.id,
isDir: false,
page,
children: [],
- });
- }
+ }));
return {
name: "Onboarding",
@@ -330,6 +331,15 @@ function buildAutoGroup(deterministicPages: DocPage[]): TreeNode | null {
// Split off the deterministic coverage-tail file pages so the main tree is
// built only from the human/AI-written pages. Deterministic pages are always
// file_pages, so nothing else is affected.
+//
+// The split only makes sense when there ARE written file pages to protect. On
+// a deterministic-mode wiki (`repowise init --index-only`) every file page is
+// template-generated, and a per-page predicate with no repo-level guard swept
+// the entire file layer into one collapsed "Auto-documented" bucket — the
+// tree's whole leaf level, hidden behind one toggle. That condition is read
+// off the pages here rather than threaded in as repo `docs_mode`, because the
+// pages already answer the question and both host apps would otherwise have to
+// fetch and forward a field they have no other use for.
function partitionDeterministic(pages: DocPage[]): {
regular: DocPage[];
deterministic: DocPage[];
@@ -343,338 +353,203 @@ function partitionDeterministic(pages: DocPage[]): {
regular.push(page);
}
}
+ const anyWrittenFilePage = regular.some((p) => p.page_type === "file_page");
+ if (deterministic.length > 0 && !anyWrittenFilePage) {
+ return { regular: pages, deterministic: [] };
+ }
return { regular, deterministic };
}
// ---------------------------------------------------------------------------
-// Domain (semantic) tree
+// Domain (semantic) tree — read from the store, not derived here
// ---------------------------------------------------------------------------
//
-// A narrative spine grouped by *meaning* rather than folder structure:
+// The hierarchy used to be rebuilt in this file: a hardcoded four-section
+// spine, a majority vote over each module's files to guess its layer, and
+// longest-prefix path matching to guess which module owned a file. It is now
+// computed once at generation time (`core/generation/page_tree.py`) and stored
+// on every page as parent_page_id / display_order / section_number, so this
+// component, the editor extension and the MCP server all read one outline
+// instead of each deriving a different one.
//
-// Guided Tour → onboarding slots in canonical reading order
-// Architecture → layer / knowledge-graph / SCC pages (the zoom-out)
-// Modules → each module_page with its files nested underneath
-// Reference → loose files, symbols, API contracts, infra
+// Shape on a repo with a curated knowledge graph:
//
-// Section keys are namespaced with "@section:" so they never collide with a
-// real target_path and get their own icon in TreeItem.
-
-const SECTION_KEYS = {
- tour: "@section:tour",
- architecture: "@section:architecture",
- modules: "@section:modules",
- reference: "@section:reference",
-} as const;
-
-export const DOMAIN_SECTION_KEYS = Object.values(SECTION_KEYS);
-
-// Layers ordered top→bottom by dependency direction, persisted on the repo
-// overview page at generation time. Used to order the Architecture section and
-// the Modules section so the tree reads as a dependency hierarchy rather than
-// alphabetically. Returns a rank lookup (lower = closer to the top).
+// Repository Overview the root, rendered first
+// 1 onboarding pages canonical reading order
+// 7 architecture diagram
+// 8 layer pages dependency spine
+// 8.1 module pages → file pages → symbol spotlights
+// 8.9 cycle pages
//
-// Keyed on layer_id, not layer_name. layer_name is display text the LLM
-// enrichment pass rewrites, so it drifts between generations. Measured
-// 2026-07-23, 11 curated layers against 62 distinct layer_name values, and
-// only 82 of 1108 file pages resolved to a rank. layer_id is a stable slug.
-function layerRankLookup(pages: DocPage[]): (layerId: string) => number {
- const overview = pages.find((p) => p.page_type === "repo_overview");
- // layer_order_ids is the join key. layer_order holds display names and is
- // only a fallback for a store generated before the ids were persisted, where
- // ranking stays as good as it ever was rather than silently going flat.
- const raw = overview?.metadata?.["layer_order_ids"] ?? overview?.metadata?.["layer_order"];
- const order = Array.isArray(raw) ? (raw.filter((x) => typeof x === "string") as string[]) : [];
- const index = new Map(order.map((id, i) => [id, i]));
- return (layerId: string) => index.get(layerId) ?? Number.MAX_SAFE_INTEGER;
-}
-
-// The layer a module belongs to = the most common layer_id across its files.
-function dominantLayer(files: DocPage[]): string {
- const counts = new Map<string, number>();
- for (const f of files) {
- const layer = f.metadata?.["layer_id"];
- if (typeof layer === "string" && layer) {
- counts.set(layer, (counts.get(layer) ?? 0) + 1);
- }
+// A rung the repo has no pages for simply does not appear.
+
+// Bucket key for a run of same-type siblings, and for pages the stored tree
+// does not reach. Namespaced like the other synthetic keys so it can never
+// collide with a real page id; the parent id is part of the key so two
+// parents' buckets of the same type expand independently.
+const TYPE_GROUP_PREFIX = "@group:type:";
+
+const typeGroupKey = (parentId: string, pageType: string) =>
+ `${TYPE_GROUP_PREFIX}${parentId}:${pageType}`;
+
+// Unreachable pages are bucketed under the empty parent, and those buckets
+// open by default: on a store whose tree has never been built they are the
+// whole tree, so leaving them shut would show almost nothing.
+const STRAY_GROUP_KEYS = ALL_PAGE_TYPES.map((t) => typeGroupKey("", t));
+
+// How many same-type leaves may sit side by side before they are collapsed
+// into one row. This repo's overview has 53 cycle pages and 55 loose file
+// pages directly beneath it; listed inline they bury the eleven layers that
+// are the actual spine. A run of leaves is a list, not a hierarchy, so it gets
+// one row. Anything with children of its own is never bucketed — that IS the
+// hierarchy, however many of them there are.
+const LEAF_RUN_LIMIT = 8;
+
+function groupLeafRuns(parentId: string, nodes: TreeNode[]): TreeNode[] {
+ const runs = new Map<string, TreeNode[]>();
+ for (const node of nodes) {
+ if (node.children.length > 0 || !node.page) continue;
+ const bucket = runs.get(node.page.page_type);
+ if (bucket) bucket.push(node);
+ else runs.set(node.page.page_type, [node]);
}
- let best = "";
- let bestN = 0;
- for (const [layer, n] of counts) {
- if (n > bestN) {
- best = layer;
- bestN = n;
- }
+ const bucketed = new Set<string>();
+ for (const [type, run] of runs) {
+ if (run.length > LEAF_RUN_LIMIT) for (const n of run) bucketed.add(n.path);
+ else runs.delete(type);
}
- return best;
-}
+ if (bucketed.size === 0) return nodes;
-// ---------------------------------------------------------------------------
-// Display labels — replace raw graph ids with derived names
-// ---------------------------------------------------------------------------
-//
-// Generation titles carry raw graph ids ("Module: community-207",
-// "Circular Dependency: scc-103"). The human-readable names live on the page
-// itself — module titles already carry the derived path, and SCC members are
-// listed in the cycle description — so the tree derives display labels
-// client-side instead of leaking ids. metadata.derived_label, when present,
-// always wins (future-proofing for generation-side labels).
-
-const RAW_GRAPH_ID = /^(?:community|scc)[-_\s]?\d+$/i;
-
-function sccDisplayLabel(page: DocPage): string {
- // Cycle members appear back-ticked in the generated description; prefer
- // the "Files Involved" section when present so prose mentions don't leak in.
- const involved = page.content.split(/^##\s+Files Involved\s*$/im)[1];
- const section = involved ? involved.split(/^##\s/m)[0] ?? involved : page.content;
- const paths = [...section.matchAll(/`([^`\s]+\/[^`\s]+)`/g)].map((m) => m[1]!);
- if (paths.length === 0) return page.title;
-
- // Common directory of the members, shown as its last two segments —
- // "Cycle: generation/page_generator" reads better than "scc-103".
- let common = (paths[0] ?? "").split("/").slice(0, -1);
- for (const p of paths.slice(1)) {
- const parts = p.split("/").slice(0, -1);
- let i = 0;
- while (i < common.length && i < parts.length && common[i] === parts[i]) i++;
- common = common.slice(0, i);
+ const out: TreeNode[] = [];
+ const emitted = new Set<string>();
+ for (const node of nodes) {
+ if (!bucketed.has(node.path)) {
+ out.push(node);
+ continue;
+ }
+ // The bucket takes the position of the first of its run, so the spine
+ // keeps its stored order rather than having every group shunted to the end.
+ const type = node.page!.page_type;
+ if (emitted.has(type)) continue;
+ emitted.add(type);
+ const run = runs.get(type)!;
+ out.push({
+ name: `${getPageTypeLabel(type)} (${run.length})`,
+ path: typeGroupKey(parentId, type),
+ isDir: true,
+ children: run,
+ });
}
- const dir = common.slice(-2).join("/");
- return dir ? `Cycle: ${dir}` : page.title;
+ return out;
}
-function displayLabel(page: DocPage): string {
- const metaLabel = page.metadata?.["derived_label"];
- if (typeof metaLabel === "string" && metaLabel) return metaLabel;
-
- if (page.page_type === "module_page") {
- const name = page.title.replace(/^Module:\s*/i, "");
- if (name && !RAW_GRAPH_ID.test(name)) return name;
- const fallback = page.target_path.split("/").pop() ?? page.target_path;
- return RAW_GRAPH_ID.test(fallback) ? page.title : fallback;
- }
- if (page.page_type === "scc_page") return sccDisplayLabel(page);
- if (page.page_type === "layer_page") return page.title.replace(/^Layer:\s*/i, "");
- return page.title;
+function compareSiblings(a: DocPage, b: DocPage): number {
+ return (
+ (a.display_order ?? 0) - (b.display_order ?? 0) ||
+ (a.target_path || a.title).localeCompare(b.target_path || b.title)
+ );
}
-// Collapsible sub-groups inside the Architecture section. Namespaced with
-// "@group:" so they never collide with target_paths or "@section:" keys —
-// and, unlike sections, they are NOT auto-expanded (40 layers / 38 cycles
-// would otherwise drown the spine).
-const GROUP_KEYS = {
- layers: "@group:layers",
- sccs: "@group:sccs",
-} as const;
-
-function buildDomainTree(pages: DocPage[]): TreeNode[] {
- const sections: TreeNode[] = [];
- const rankOf = layerRankLookup(pages);
-
- // ---- Guided Tour (reuse the canonical onboarding ordering) ----
- const onboarding = buildOnboardingFolder(pages);
- const tourIds = new Set<string>();
- const tourChildren: TreeNode[] = onboarding ? [...onboarding.children] : [];
- for (const c of tourChildren) if (c.page) tourIds.add(c.page.id);
-
- // Guarantee the repo overview heads the tour even when it wasn't promoted
- // into an onboarding slot — it's the canonical front door.
- const overview = pages.find((p) => p.page_type === "repo_overview");
- if (overview && !tourIds.has(overview.id)) {
- tourChildren.unshift({
- name: overview.title || "Overview",
- path: overview.id,
- isDir: false,
- page: overview,
- children: [],
- });
- tourIds.add(overview.id);
+function buildStoredTree(pages: DocPage[]): TreeNode[] {
+ // A tombstoned page documents a file that no longer exists. It keeps its row
+ // and its content, but the tree deliberately has no place for it, so it must
+ // be excluded here rather than treated as an unplaced page.
+ const visible = pages.filter((p) => p.freshness_status !== "tombstone");
+ const byId = new Map(visible.map((p) => [p.id, p]));
+
+ const childrenOf = new Map<string, DocPage[]>();
+ const claimed = new Set<string>();
+ for (const page of visible) {
+ const parentId = page.parent_page_id;
+ if (!parentId || parentId === page.id || !byId.has(parentId)) continue;
+ const bucket = childrenOf.get(parentId);
+ if (bucket) bucket.push(page);
+ else childrenOf.set(parentId, [page]);
+ claimed.add(page.id);
}
- if (tourChildren.length > 0) {
- sections.push({
- name: "Guided Tour",
- path: SECTION_KEYS.tour,
- isDir: true,
- children: tourChildren,
- });
+ // The root is the page nothing claims that other pages hang off. A store
+ // written before the tree existed has no such page — every parent is null —
+ // and falls through to the grouped tail below.
+ const rootCandidates = visible.filter((p) => !claimed.has(p.id) && childrenOf.has(p.id));
+ const root =
+ rootCandidates.find((p) => p.page_type === "repo_overview") ?? rootCandidates[0] ?? null;
+
+ // Reached, not just claimed: a parent cycle would otherwise silently swallow
+ // every page in it. Anything the walk misses lands in the tail instead.
+ const reached = new Set<string>();
+ function toNode(page: DocPage, parent: DocPage | undefined): TreeNode {
+ reached.add(page.id);
+ const children = groupLeafRuns(
+ page.id,
+ (childrenOf.get(page.id) ?? [])
+ .filter((c) => !reached.has(c.id))
+ .sort(compareSiblings)
+ .map((c) => toNode(c, page)),
+ );
+ return {
+ name: treeLabel(page, parent),
+ path: page.id,
+ isDir: children.length > 0,
+ page,
+ children,
+ ...(page.section_number ? { section: page.section_number } : {}),
+ };
}
- // ---- Architecture (diagrams up top; layers and cycles in collapsible
- // sub-groups so 40 layers / 38 SCCs don't drown the spine) ----
- const archTypes = new Set(["layer_page", "architecture_diagram", "scc_page"]);
- const archPages = pages.filter((p) => archTypes.has(p.page_type) && !tourIds.has(p.id));
-
- const toLeaf = (p: DocPage): TreeNode => ({
- name: displayLabel(p),
- path: p.id,
- isDir: false,
- page: p,
- children: [],
- });
-
- const diagramLeaves = archPages
- .filter((p) => p.page_type === "architecture_diagram")
- .sort((a, b) => a.title.localeCompare(b.title))
- .map(toLeaf);
- // Order layer pages top→bottom by dependency direction.
- const layerLeaves = archPages
- .filter((p) => p.page_type === "layer_page")
- .sort((a, b) => {
- // target_path is the stable "layer:<slug>" id the page is keyed by.
- // Scraping the name off the title cannot rank, because the title
- // carries the display name and the spine is keyed on the id.
- const ra = rankOf(a.target_path);
- const rb = rankOf(b.target_path);
- return ra - rb || a.title.localeCompare(b.title);
- })
- .map(toLeaf);
- const sccLeaves = archPages
- .filter((p) => p.page_type === "scc_page")
- .map(toLeaf)
- .sort((a, b) => a.name.localeCompare(b.name));
-
- const archChildren: TreeNode[] = [...diagramLeaves];
- if (layerLeaves.length > 0) {
- archChildren.push({
- name: `Layers (${layerLeaves.length})`,
- path: GROUP_KEYS.layers,
- isDir: true,
- children: layerLeaves,
- });
- }
- if (sccLeaves.length > 0) {
- archChildren.push({
- name: `Circular dependencies (${sccLeaves.length})`,
- path: GROUP_KEYS.sccs,
- isDir: true,
- children: sccLeaves,
- });
- }
- if (archChildren.length > 0) {
- sections.push({
- name: "Architecture",
- path: SECTION_KEYS.architecture,
- isDir: true,
- children: archChildren,
+ const top: TreeNode[] = [];
+ if (root) {
+ reached.add(root.id);
+ top.push({
+ name: treeLabel(root, undefined),
+ path: root.id,
+ isDir: false,
+ page: root,
+ children: [],
});
+ top.push(
+ ...groupLeafRuns(
+ root.id,
+ (childrenOf.get(root.id) ?? [])
+ .slice()
+ .sort(compareSiblings)
+ .map((child) => toNode(child, root)),
+ ),
+ );
}
- // ---- Modules (each module_page with the files it contains) ----
- const modulePages = pages
- .filter((p) => p.page_type === "module_page" && p.target_path)
- .sort((a, b) => a.target_path.localeCompare(b.target_path));
- const modulePaths = new Set(modulePages.map((p) => p.target_path));
- const claimedFileIds = new Set<string>();
-
- // Claim each file page by its NEAREST module ancestor, not just the direct
- // parent dir — curated modules are directory subtrees whose files can sit
- // several levels deep (e.g. module "core/ingestion" owning
- // "core/ingestion/resolvers/dotnet/index.py").
- const sortedModulePaths = [...modulePaths].sort((a, b) => b.length - a.length);
- const fileToModule = new Map<string, string>();
- for (const p of pages) {
- if (p.page_type !== "file_page" || !p.target_path) continue;
- const owner = sortedModulePaths.find((mp) => p.target_path.startsWith(mp + "/"));
- if (owner) fileToModule.set(p.id, owner);
+ // Pages the walk never reached. Grouped by type rather than dropped: an
+ // unplaced page is still a page. On a store whose tree has not been built
+ // yet this grouping IS the tree, which is a fair rendering of a wiki that
+ // genuinely has no recorded hierarchy.
+ const strayByType = new Map<string, DocPage[]>();
+ for (const page of visible) {
+ if (reached.has(page.id)) continue;
+ const bucket = strayByType.get(page.page_type);
+ if (bucket) bucket.push(page);
+ else strayByType.set(page.page_type, [page]);
}
-
- const moduleChildren: TreeNode[] = modulePages.map((mod) => {
- const files = pages
- .filter((p) => fileToModule.get(p.id) === mod.target_path)
- .sort((a, b) => a.target_path.localeCompare(b.target_path));
- for (const f of files) claimedFileIds.add(f.id);
- return {
- name: displayLabel(mod) || mod.target_path.split("/").pop() || mod.target_path,
- path: mod.id,
+ const orderedTypes = [
+ ...ALL_PAGE_TYPES.filter((t) => strayByType.has(t)),
+ ...[...strayByType.keys()].filter((t) => !ALL_PAGE_TYPES.includes(t)).sort(),
+ ];
+ for (const type of orderedTypes) {
+ const group = strayByType.get(type)!;
+ top.push({
+ name: `${getPageTypeLabel(type)} (${group.length})`,
+ path: typeGroupKey("", type),
isDir: true,
- page: mod,
- children: files.map((f) => ({
- // Path relative to the module dir, so deep files stay unambiguous
- // ("resolvers/dotnet/index.py", not three siblings named "index.py").
- name: f.target_path.startsWith(mod.target_path + "/")
- ? f.target_path.slice(mod.target_path.length + 1)
- : f.target_path.split("/").pop() || f.target_path,
- path: f.id,
+ children: group.sort(compareSiblings).map((p) => ({
+ name: treeLabel(p, undefined),
+ path: p.id,
isDir: false,
- page: f,
+ page: p,
children: [],
})),
- };
- });
- // Order modules top→bottom by the dependency layer of their files, so the
- // module list mirrors the architecture spine instead of sorting by path.
- moduleChildren.sort((a, b) => {
- const la = dominantLayer(a.children.map((c) => c.page).filter(Boolean) as DocPage[]);
- const lb = dominantLayer(b.children.map((c) => c.page).filter(Boolean) as DocPage[]);
- return rankOf(la) - rankOf(lb) || a.name.localeCompare(b.name);
- });
- if (moduleChildren.length > 0) {
- sections.push({
- name: "Modules",
- path: SECTION_KEYS.modules,
- isDir: true,
- children: moduleChildren,
});
}
- // ---- Reference (everything not already surfaced above) ----
- const surfacedTypes = new Set([
- "module_page",
- "repo_overview",
- ...archTypes,
- ]);
- const refChildren: TreeNode[] = pages
- .filter(
- (p) =>
- !tourIds.has(p.id) &&
- !claimedFileIds.has(p.id) &&
- !surfacedTypes.has(p.page_type) &&
- // module-claimed dirs are not pages themselves; skip module dirs
- !modulePaths.has(p.target_path),
- )
- .sort((a, b) => (a.target_path || a.title).localeCompare(b.target_path || b.title))
- .map((p) => ({
- name: p.target_path ? p.target_path.split("/").pop() || p.target_path : p.title,
- path: p.id,
- isDir: false,
- page: p,
- children: [],
- }));
- if (refChildren.length > 0) {
- sections.push({
- name: "Reference",
- path: SECTION_KEYS.reference,
- isDir: true,
- children: refChildren,
- });
- }
-
- return sections;
-}
-
-// Ordinal shown next to each domain section so the spine reads as a numbered
-// 1 → 4 reading order (Guided Tour → Architecture → Modules → Reference).
-const SECTION_NUMBER: Record<string, number> = {
- [SECTION_KEYS.tour]: 1,
- [SECTION_KEYS.architecture]: 2,
- [SECTION_KEYS.modules]: 3,
- [SECTION_KEYS.reference]: 4,
-};
-
-function sectionIcon(path: string) {
- switch (path) {
- case SECTION_KEYS.tour:
- return Compass;
- case SECTION_KEYS.architecture:
- return Layers;
- case SECTION_KEYS.modules:
- return Network;
- case SECTION_KEYS.reference:
- return FileText;
- default:
- return BookOpen;
- }
+ return top;
}
// ---------------------------------------------------------------------------
@@ -787,23 +662,16 @@ function TreeItem({
) : (
<span className="w-3 shrink-0" />
)}
- {node.path.startsWith("@section:") ? (
- (() => {
- const SectionIcon = sectionIcon(node.path);
- const num = SECTION_NUMBER[node.path];
- return (
- <>
- {num != null && (
- <span className="shrink-0 font-mono text-[10px] text-[var(--color-text-tertiary)] tabular-nums">
- {num}
- </span>
- )}
- <SectionIcon className="h-3.5 w-3.5 shrink-0 text-[var(--color-accent-primary)]" />
- </>
- );
- })()
- ) : node.path === ONBOARDING_DIR_KEY ? (
+ <SectionNumber depth={depth} section={node.section} />
+ {node.path === ONBOARDING_DIR_KEY ? (
<Compass className="h-3.5 w-3.5 shrink-0 text-[var(--color-accent-primary)]" />
+ ) : node.page ? (
+ // A dir that is itself a page (layer, module, cycle) keeps its page
+ // type's icon — a folder glyph would say less than the type does.
+ <PageIcon
+ pageType={node.page.page_type}
+ className="h-3.5 w-3.5 shrink-0 text-[var(--color-accent-primary)]"
+ />
) : isExpanded ? (
<FolderOpen className="h-3.5 w-3.5 shrink-0 text-[var(--color-accent-primary)] opacity-70" />
) : (
@@ -812,10 +680,8 @@ function TreeItem({
<span
className={cn(
"truncate font-medium",
- (node.path === ONBOARDING_DIR_KEY || node.path.startsWith("@section:")) &&
+ (node.path === ONBOARDING_DIR_KEY || depth === 0) &&
"text-[var(--color-text-primary)]",
- node.path.startsWith("@section:") &&
- "text-xs uppercase tracking-wider",
)}
>
{node.name}
@@ -859,6 +725,7 @@ function TreeItem({
)}
style={{ paddingLeft: `${depth * 16 + 8 + 16}px` }}
>
+ <SectionNumber depth={depth} section={node.section} />
<PageIcon
pageType={node.page?.page_type ?? "file_page"}
className={cn(
@@ -874,6 +741,17 @@ function TreeItem({
);
}
+// The stored dotted number, shown on the top rung only. Deeper rows are
+// already placed by indentation, and "14.3.2" on every file row is noise.
+function SectionNumber({ depth, section }: { depth: number; section?: string | undefined }) {
+ if (depth !== 0 || !section) return null;
+ return (
+ <span className="shrink-0 font-mono text-[10px] text-[var(--color-text-tertiary)] tabular-nums">
+ {section}
+ </span>
+ );
+}
+
function FreshnessDot({ status }: { status: FreshnessStatus }) {
// Fresh is the expected state — only flag pages that need attention, so a
// healthy tree stays visually quiet instead of showing hundreds of dots.
@@ -897,12 +775,14 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc
// first, filesystem second. The folder view is a toggle for power users.
const [viewMode, setViewMode] = useState<ViewMode>("domain");
const [expandedDirs, setExpandedDirs] = useState<Set<string>>(() => {
- // Auto-expand first two levels, the Onboarding folder, and every domain
- // section so both views open in a useful state; then ADD any previously
- // expanded dirs from localStorage. Union (not replace) — the key is
- // shared across repos, so a stale saved set must never collapse another
- // repo's default-open sections.
- const dirs = new Set<string>(DOMAIN_SECTION_KEYS);
+ // Auto-expand first two levels, the Onboarding folder, and the by-type
+ // buckets that hold pages the stored tree does not reach (on a store whose
+ // tree has not been built yet, those buckets are the whole tree, so
+ // leaving them collapsed would show almost nothing). Then ADD any
+ // previously expanded dirs from localStorage. Union (not replace) — the
+ // key is shared across repos, so a stale saved set must never collapse
+ // another repo's default-open rows.
+ const dirs = new Set<string>(STRAY_GROUP_KEYS);
dirs.add(ONBOARDING_DIR_KEY);
for (const page of pages) {
const parts = page.target_path.split("/");
@@ -949,7 +829,7 @@ export function DocsTree({ pages, selectedPageId, onSelectPage, className }: Doc
const tree = useMemo(() => {
// Build the main tree from the human/AI-written pages only, then append the
// collapsed auto group when the reader has opted in.
- const base = viewMode === "domain" ? buildDomainTree(regular) : buildTree(regular);
+ const base = viewMode === "domain" ? buildStoredTree(regular) : buildTree(regular);
if (showDeterministic && autoGroup) base.push(autoGroup);
return base;
}, [regular, viewMode, showDeterministic, autoGroup]);
diff --git a/packages/ui/src/docs/page-labels.ts b/packages/ui/src/docs/page-labels.ts
new file mode 100644
index 000000000..284ce148c
--- /dev/null
+++ b/packages/ui/src/docs/page-labels.ts
@@ -0,0 +1,78 @@
+// Display labels for wiki pages — replace raw graph ids with derived names.
+//
+// Generation titles carry raw graph ids ("Module: community-207",
+// "Circular Dependency: scc-103"). The human-readable names live on the page
+// itself — module titles already carry the derived path, and SCC members are
+// listed in the cycle description — so labels are derived client-side instead
+// of leaking ids. metadata.derived_label, when present, always wins
+// (future-proofing for generation-side labels).
+//
+// This lives apart from the tree component because the breadcrumb trail
+// (`doc-nav.ts`, framework-neutral) needs the same labels and must not pull in
+// React to get them.
+
+import type { DocPage } from "@repowise-dev/types/docs";
+
+export const RAW_GRAPH_ID = /^(?:community|scc)[-_\s]?\d+$/i;
+
+export function sccDisplayLabel(page: DocPage): string {
+ // Cycle members appear back-ticked in the generated description; prefer
+ // the "Files Involved" section when present so prose mentions don't leak in.
+ const involved = page.content.split(/^##\s+Files Involved\s*$/im)[1];
+ const section = involved ? involved.split(/^##\s/m)[0] ?? involved : page.content;
+ const paths = [...section.matchAll(/`([^`\s]+\/[^`\s]+)`/g)].map((m) => m[1]!);
+ if (paths.length === 0) return page.title;
+
+ // Common directory of the members, shown as its last two segments —
+ // "Cycle: generation/page_generator" reads better than "scc-103".
+ let common = (paths[0] ?? "").split("/").slice(0, -1);
+ for (const p of paths.slice(1)) {
+ const parts = p.split("/").slice(0, -1);
+ let i = 0;
+ while (i < common.length && i < parts.length && common[i] === parts[i]) i++;
+ common = common.slice(0, i);
+ }
+ const dir = common.slice(-2).join("/");
+ return dir ? `Cycle: ${dir}` : page.title;
+}
+
+// Page types whose target_path is a real file. Everything else is named by its
+// title (or, for module / layer / cycle pages, the label derived from it): an
+// overview's path is the repo name and an onboarding page's is a slot, and
+// neither reads as a row label.
+const PATH_NAMED_TYPES = new Set(["file_page", "api_contract", "infra_page"]);
+
+/**
+ * What a page is called in a tree row or a breadcrumb, given the page it hangs
+ * off. A file under its module is named relative to it, so three files called
+ * index.py in different resolver directories stay distinguishable.
+ */
+export function treeLabel(page: DocPage, parent: DocPage | undefined): string {
+ const path = page.target_path;
+ if (page.page_type === "symbol_spotlight" && path.includes("::")) {
+ // "path/to/file.py::Symbol" — the file is the parent row, so the symbol is
+ // the only part that carries information here.
+ return path.split("::")[1] || page.title;
+ }
+ if (!path || !PATH_NAMED_TYPES.has(page.page_type)) return displayLabel(page);
+ const parentPath = parent?.target_path;
+ if (parentPath && path.startsWith(parentPath + "/")) {
+ return path.slice(parentPath.length + 1);
+ }
+ return path.split("/").pop() || path;
+}
+
+export function displayLabel(page: DocPage): string {
+ const metaLabel = page.metadata?.["derived_label"];
+ if (typeof metaLabel === "string" && metaLabel) return metaLabel;
+
+ if (page.page_type === "module_page") {
+ const name = page.title.replace(/^Module:\s*/i, "");
+ if (name && !RAW_GRAPH_ID.test(name)) return name;
+ const fallback = page.target_path.split("/").pop() ?? page.target_path;
+ return RAW_GRAPH_ID.test(fallback) ? page.title : fallback;
+ }
+ if (page.page_type === "scc_page") return sccDisplayLabel(page);
+ if (page.page_type === "layer_page") return page.title.replace(/^Layer:\s*/i, "");
+ return page.title;
+}
diff --git a/packages/ui/src/lib/page-types.ts b/packages/ui/src/lib/page-types.ts
index 99397eae4..aba29d421 100644
--- a/packages/ui/src/lib/page-types.ts
+++ b/packages/ui/src/lib/page-types.ts
@@ -82,29 +82,19 @@ export const AI_WRITTEN_BADGE_TITLE =
// Onboarding collection
// ---------------------------------------------------------------------------
//
-// Keep this list in lockstep with the Python side
-// (`packages/core/src/repowise/core/generation/onboarding/slots.py`).
// Two slots — project_overview and architecture_guide — are *promoted*: their
// content lives in the existing repo_overview / architecture_diagram pages,
-// tagged via `metadata.onboarding_slot`. The other six are dedicated
+// tagged via `metadata.onboarding_slot`. The other seven are dedicated
// `page_type === "onboarding"` pages with `metadata.subkind` discriminating
// them.
+//
+// This map is display text only. The *reading order* used to be duplicated
+// here as an ONBOARDING_ORDER array kept in lockstep with `slots.py` by
+// comment alone; it now arrives on the pages themselves as `display_order`,
+// assigned once at generation time, so there is one ordering rather than two
+// that can drift.
-export const ONBOARDING_ORDER = [
- "project_overview",
- "architecture_guide",
- "guided_tour",
- "getting_started",
- "codebase_map",
- "key_concepts",
- "how_it_works",
- "development_guide",
- "active_landscape",
-] as const;
-
-export type OnboardingSlot = (typeof ONBOARDING_ORDER)[number];
-
-export const ONBOARDING_SLOT_TITLES: Record<OnboardingSlot, string> = {
+export const ONBOARDING_SLOT_TITLES = {
project_overview: "Project Overview",
architecture_guide: "Architecture Guide",
guided_tour: "Guided Tour",
@@ -114,7 +104,16 @@ export const ONBOARDING_SLOT_TITLES: Record<OnboardingSlot, string> = {
how_it_works: "How It Works",
development_guide: "Development Guide",
active_landscape: "Active Landscape",
-};
+} as const;
+
+export type OnboardingSlot = keyof typeof ONBOARDING_SLOT_TITLES;
+
+function isOnboardingSlot(value: unknown): value is OnboardingSlot {
+ // hasOwn, not `in`: `"toString" in obj` is true for every object, and a page
+ // whose subkind happened to be a prototype member would then resolve to a
+ // function where a title is expected.
+ return typeof value === "string" && Object.hasOwn(ONBOARDING_SLOT_TITLES, value);
+}
/**
* Return the onboarding slot a page belongs to, or null if it isn't part of
@@ -128,17 +127,10 @@ export const ONBOARDING_SLOT_TITLES: Record<OnboardingSlot, string> = {
export function getOnboardingSlot(page: DocPage): OnboardingSlot | null {
const meta = page.metadata ?? {};
const fromSlot = meta["onboarding_slot"];
- if (typeof fromSlot === "string" && (ONBOARDING_ORDER as readonly string[]).includes(fromSlot)) {
- return fromSlot as OnboardingSlot;
- }
+ if (isOnboardingSlot(fromSlot)) return fromSlot;
if (page.page_type === "onboarding") {
const subkind = meta["subkind"];
- if (
- typeof subkind === "string" &&
- (ONBOARDING_ORDER as readonly string[]).includes(subkind)
- ) {
- return subkind as OnboardingSlot;
- }
+ if (isOnboardingSlot(subkind)) return subkind;
}
return null;
}
diff --git a/tests/unit/server/mcp/test_overview_outline.py b/tests/unit/server/mcp/test_overview_outline.py
new file mode 100644
index 000000000..3acec680b
--- /dev/null
+++ b/tests/unit/server/mcp/test_overview_outline.py
@@ -0,0 +1,197 @@
+"""get_overview serves the stored page tree.
+
+The tree is computed once at generation time and written onto the pages; this
+covers the reading side — that the outline is assembled from what is stored,
+not re-derived, that it degrades honestly on a store whose tree has never been
+built, and that a parent cycle cannot hang the walk.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from repowise.server.mcp_server._budget import OmissionCollector
+from repowise.server.mcp_server.tool_overview import (
+ _build_outline,
+ _module_order_key,
+ _outline_index,
+ _section_sort_key,
+)
+
+
+def _row(pid: str, **kw) -> SimpleNamespace:
+ base = {
+ "id": pid,
+ "title": pid,
+ "page_type": "file_page",
+ "target_path": pid,
+ "parent_page_id": None,
+ "display_order": 0,
+ "section_number": None,
+ }
+ base.update(kw)
+ return SimpleNamespace(**base)
+
+
+# A spine that disagrees with the alphabet: the dependency order puts "Zebra
+# Runtime" above "Alpha API". A fixture whose stored order and alphabetical
+# order agree cannot tell one from the other.
+ROOT = _row("repo_overview:demo", page_type="repo_overview", title="Repository Overview: demo")
+LAYER_RUNTIME = _row(
+ "layer_page:layer:runtime",
+ page_type="layer_page",
+ title="Layer: Zebra Runtime",
+ target_path="layer:runtime",
+ parent_page_id=ROOT.id,
+ display_order=1,
+ section_number="1",
+)
+LAYER_API = _row(
+ "layer_page:layer:api",
+ page_type="layer_page",
+ title="Layer: Alpha API",
+ target_path="layer:api",
+ parent_page_id=ROOT.id,
+ display_order=2,
+ section_number="2",
+)
+MODULE = _row(
+ "module_page:runtime/engine",
+ page_type="module_page",
+ title="Module: runtime/engine",
+ target_path="runtime/engine",
+ parent_page_id=LAYER_RUNTIME.id,
+ display_order=1,
+ section_number="1.1",
+)
+FILE = _row(
+ "file_page:runtime/engine/loop.py",
+ target_path="runtime/engine/loop.py",
+ parent_page_id=MODULE.id,
+ display_order=1,
+ section_number="1.1.1",
+)
+
+SPINE = [ROOT, LAYER_RUNTIME, LAYER_API, MODULE, FILE]
+
+
+def _collector(tmp_path) -> OmissionCollector:
+ return OmissionCollector("get_overview", repo_root=tmp_path)
+
+
+def test_outline_follows_the_stored_order_not_the_alphabet(tmp_path):
+ outline = _build_outline(SPINE, 1, _collector(tmp_path))
+ assert outline["root"]["page_id"] == ROOT.id
+ assert [s["title"] for s in outline["sections"]] == [
+ "Layer: Zebra Runtime",
+ "Layer: Alpha API",
+ ]
+ assert [s["section"] for s in outline["sections"]] == ["1", "2"]
+ # Guard against a fixture that would pass either way.
+ assert "Layer: Zebra Runtime" > "Layer: Alpha API"
+
+
+def test_outline_is_shallow_by_default_but_reports_subtree_size(tmp_path):
+ outline = _build_outline(SPINE, 1, _collector(tmp_path))
+ runtime = outline["sections"][0]
+ assert "children" not in runtime
+ # The module and the file below it are both counted, so a caller can see
+ # there is more there without paying for it.
+ assert runtime["descendants"] == 2
+ assert outline["total_pages"] == len(SPINE)
+
+
+def test_outline_opens_one_rung_deeper_on_request(tmp_path):
+ outline = _build_outline(SPINE, 2, _collector(tmp_path))
+ runtime = outline["sections"][0]
+ assert [c["page_id"] for c in runtime["children"]] == [MODULE.id]
+ # Still bounded: the module's own children are a count, not a listing.
+ assert "children" not in runtime["children"][0]
+ assert runtime["children"][0]["descendants"] == 1
+
+
+def test_no_outline_when_the_tree_has_never_been_built(tmp_path):
+ # Every parent null — what the migration leaves behind until the next
+ # index or update run. A flat list dressed as a hierarchy would be a lie.
+ flat = [_row("a"), _row("b"), _row("repo_overview:demo", page_type="repo_overview")]
+ assert _build_outline(flat, 1, _collector(tmp_path)) == {}
+ assert _outline_index(flat) == (None, {})
+
+
+def test_dangling_parent_does_not_claim_a_page(tmp_path):
+ orphan = _row("file_page:orphan.py", parent_page_id="module_page:deleted")
+ outline = _build_outline([*SPINE, orphan], 1, _collector(tmp_path))
+ # It is not a child of anything, and it is not silently promoted to a
+ # top-level section either: it simply has no place in the tree. That it is
+ # missing is reported rather than left for the caller to notice.
+ assert orphan.id not in [s["page_id"] for s in outline["sections"]]
+ assert outline["unplaced_pages"] == 1
+
+
+def test_parent_cycle_terminates(tmp_path):
+ a = _row("a", parent_page_id="b")
+ b = _row("b", parent_page_id="a")
+ outline = _build_outline([*SPINE, a, b], 2, _collector(tmp_path))
+ assert [s["page_id"] for s in outline["sections"]] == [LAYER_RUNTIME.id, LAYER_API.id]
+ assert outline["unplaced_pages"] == 2
+
+
+def test_children_beyond_the_cap_go_to_the_omission_store(tmp_path):
+ many = [
+ _row(
+ f"module_page:m{i:02d}",
+ page_type="module_page",
+ parent_page_id=LAYER_RUNTIME.id,
+ display_order=i,
+ section_number=f"1.{i}",
+ )
+ for i in range(1, 26)
+ ]
+ collector = _collector(tmp_path)
+ outline = _build_outline([*SPINE, *many], 2, collector)
+ runtime = outline["sections"][0]
+ assert len(runtime["children"]) == 10
+ # Truncated, not silently: the count is honest and the rest is recoverable.
+ assert runtime["descendants"] == 27
+ payload: dict = {}
+ collector.attach(payload)
+ assert payload
+
+
+def test_top_level_truncation_is_declared_and_recoverable(tmp_path):
+ # A repo's overview really does carry a long tail directly: this one has 53
+ # cycle pages and 55 loose file pages under the root.
+ tail = [
+ _row(f"scc_page:s{i:03d}", page_type="scc_page", parent_page_id=ROOT.id, display_order=i)
+ for i in range(1, 61)
+ ]
+ collector = _collector(tmp_path)
+ outline = _build_outline([*SPINE, *tail], 1, collector)
+ assert len(outline["sections"]) == 40
+ assert outline["sections_total"] == 62
+ assert outline["sections_truncated"] is True
+ # The recoverable blob is what was dropped, not a superset that contradicts
+ # its own "N dropped" header.
+ body = "\n".join(text for _label, text in collector._chunks)
+ assert "s060" in body
+ assert "Layer: Zebra Runtime" not in body
+
+
+def test_key_modules_lead_with_the_top_of_the_spine_not_the_alphabet():
+ # get_overview caps key_modules at 8, so which 8 depends entirely on this
+ # order. Alphabetically "auth" would lead; by the spine it is last.
+ modules = [
+ _row("m_auth", page_type="module_page", title="Module: auth", section_number="14.1"),
+ _row("m_zoo", page_type="module_page", title="Module: zoo", section_number="2.1"),
+ _row("m_none", page_type="module_page", title="Module: unplaced"),
+ ]
+ assert [m.id for m in sorted(modules, key=_module_order_key)] == [
+ "m_zoo",
+ "m_auth",
+ "m_none",
+ ]
+
+
+def test_section_sort_key_is_numeric_and_puts_unplaced_last():
+ ordered = sorted(["8.10", "8.9", None, "10.1", "2"], key=_section_sort_key)
+ assert ordered == ["2", "8.9", "8.10", "10.1", None]