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): persist page hierarchy in the data model (#1014)

Raghav Chamadiyac1bc079e5219
diff --git a/packages/api-client/src/types/pages.ts b/packages/api-client/src/types/pages.ts
index ac40cf677..75823a25d 100644
--- a/packages/api-client/src/types/pages.ts
+++ b/packages/api-client/src/types/pages.ts
@@ -30,6 +30,13 @@ export interface PageResponse {
is_deterministic: boolean;
/** 2 = in-budget template, 3 = coverage tail; null on model-written pages. */
doc_tier: number | null;
+ /** Position in the wiki outline, computed once at generation time so every
+ * reader navigates the same tree. Optional: pages written before the wiki
+ * carried a tree have no placement, which reads as flat. */
+ parent_page_id?: string | null;
+ display_order?: number;
+ section_number?: string | null;
+ structural_key?: string | null;
}
export interface PageVersionResponse {
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py b/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py
index 2f8b8c8de..bdb836e92 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/deterministic.py
@@ -382,6 +382,15 @@ async def _persist_async(
except Exception as exc:
degraded.append(f"Stale-page decay: {exc}")
+ # Placement depends on the whole page set, which on an incremental
+ # run lives in the store rather than in the pages just generated.
+ try:
+ from repowise.core.pipeline.page_tree_sync import rebuild_page_tree
+
+ await rebuild_page_tree(session, repo_id)
+ except Exception as exc:
+ degraded.append(f"Page tree rebuild: {exc}")
+
# Real DB total, not an accumulation: regeneration upserts, so
# adding len(generated_pages) each run inflates the count forever.
total = len(generated_pages)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
index f2a44c7ae..538ad1d7d 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py
@@ -432,6 +432,15 @@ async def _persist_full_update_async(
except Exception as exc:
_skip("Stale-page decay", exc)
+ # Placement depends on the whole page set, which on an incremental
+ # run lives in the store rather than in the pages just generated.
+ try:
+ from repowise.core.pipeline.page_tree_sync import rebuild_page_tree
+
+ await rebuild_page_tree(session, repo_id)
+ except Exception as exc:
+ _skip("Page tree rebuild", exc)
+
# Refreshed knowledge graph — same writers as the init pipeline
# (full-replace layers/tour/curated meta).
if knowledge_graph_result is not None:
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
index 1737e2f43..ceed2a150 100644
--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -285,6 +285,14 @@ async def _run_upgrade(
# 6. Persist pages + a GenerationJob marker, then build the FTS index.
async with get_session(sf) as session:
await upsert_pages_from_generated(session, generated_pages, repo_id)
+ try:
+ from repowise.core.pipeline.page_tree_sync import rebuild_page_tree
+
+ await rebuild_page_tree(session, repo_id)
+ except Exception:
+ # Placement is navigation, not content. An upgrade that produced
+ # pages should not fail because they could not be ordered.
+ pass
try:
from datetime import UTC, datetime
diff --git a/packages/core/alembic/versions/0042_page_hierarchy.py b/packages/core/alembic/versions/0042_page_hierarchy.py
new file mode 100644
index 000000000..7915ba852
--- /dev/null
+++ b/packages/core/alembic/versions/0042_page_hierarchy.py
@@ -0,0 +1,53 @@
+"""Add hierarchy columns to wiki_pages so the outline lives in the data model.
+
+Hierarchy used to be reassembled by every reader from page_type and
+target_path prefixes, which meant the web app, the editor extension and the
+MCP server each derived their own tree and could disagree. These four columns
+let one tree be computed once at generation time and read everywhere.
+
+All four are additive and optional: existing rows keep working with a null
+parent and display_order 0, which reads as a flat wiki, exactly what those
+rows describe today. Nothing 404s mid-rollout.
+
+Revision ID: 0042
+Revises: 0041
+Create Date: 2026-07-23
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0042"
+down_revision: str | None = "0041"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ # No foreign key on parent_page_id: SQLite cannot add one to an existing
+ # table, and the generated-page sweep deletes parents whose structural key
+ # moved. The tree builder enforces consistency instead.
+ op.add_column("wiki_pages", sa.Column("parent_page_id", sa.Text(), nullable=True))
+ op.add_column(
+ "wiki_pages",
+ sa.Column("display_order", sa.Integer(), nullable=False, server_default="0"),
+ )
+ op.add_column("wiki_pages", sa.Column("section_number", sa.Text(), nullable=True))
+ op.add_column("wiki_pages", sa.Column("structural_key", sa.Text(), nullable=True))
+
+ op.create_index("ix_wiki_pages_parent_page_id", "wiki_pages", ["parent_page_id"])
+ op.create_index("ix_wiki_pages_structural_key", "wiki_pages", ["structural_key"])
+
+
+def downgrade() -> None:
+ op.drop_index("ix_wiki_pages_structural_key", table_name="wiki_pages")
+ op.drop_index("ix_wiki_pages_parent_page_id", table_name="wiki_pages")
+ op.drop_column("wiki_pages", "structural_key")
+ op.drop_column("wiki_pages", "section_number")
+ op.drop_column("wiki_pages", "display_order")
+ op.drop_column("wiki_pages", "parent_page_id")
diff --git a/packages/core/src/repowise/core/generation/models.py b/packages/core/src/repowise/core/generation/models.py
index 06af080c8..c957a3982 100644
--- a/packages/core/src/repowise/core/generation/models.py
+++ b/packages/core/src/repowise/core/generation/models.py
@@ -10,6 +10,7 @@ import graph stays one-directional:
from __future__ import annotations
import hashlib
+from collections.abc import Iterable
from dataclasses import dataclass, field
from datetime import UTC, datetime
from typing import Literal
@@ -281,6 +282,13 @@ class GeneratedPage:
# MCP get_context as the default narrative payload (content is gated behind
# include=["full_doc"]).
summary: str = ""
+ # Where this page sits in the wiki. Left unset by generators that do not
+ # place their pages; the tree builder fills them in before persistence.
+ # See the matching columns on the Page model for what each one means.
+ parent_page_id: str | None = None
+ display_order: int = 0
+ section_number: str | None = None
+ structural_key: str | None = None
@property
def total_tokens(self) -> int:
@@ -314,22 +322,43 @@ def compute_page_id(page_type: str, target_path: str) -> str:
return f"{page_type}:{target_path}"
-def scc_page_slug(members: list[str]) -> str:
- """Return the ``target_path`` for a cycle's ``scc_page``, keyed by contents.
+# Page types identified by their members or by a curated id rather than by a
+# file path. Two things key on this and they must not drift apart: generation
+# stamps ``structural_key`` on these pages, and the persist layer sweeps them,
+# because an identity that can move strands the old row as a duplicate on the
+# next index. A new page type of this shape belongs here and nowhere else.
+STRUCTURALLY_KEYED_PAGE_TYPES: tuple[str, ...] = ("module_page", "layer_page", "scc_page")
+
- An SCC has no name of its own, so the page id used to be the component's
- position in the list the graph layer handed over. That position moved
- whenever the cycle set changed, or (before the graph layer sorted its
- components) between two runs at the same commit. A moved id means the
- update path deletes and recreates the page instead of updating it, losing
- its history.
+def member_structural_key(members: Iterable[str], *, prefix: str) -> str:
+ """Return a stable identity for a page defined by the files it covers.
- Hashing the sorted member paths ties the id to the one thing that actually
- identifies the cycle. It survives a re-ordering, an unrelated cycle
- appearing or disappearing, and a change of detection algorithm.
+ A page that groups files has no name of its own, so anything derived from
+ its position in a list, or from a title someone might rewrite, moves
+ between runs. A moved id means the update path deletes and recreates the
+ page instead of updating it, losing its history, and leaves the old row
+ behind as a duplicate.
+
+ Hashing the sorted member paths ties the identity to the one thing that
+ actually says which page this is. It survives a re-ordering of the
+ members, an unrelated group appearing or disappearing, a change of
+ grouping algorithm, and any amount of re-titling.
+
+ Adding or removing a member deliberately does change the key: the page now
+ covers a different thing, so the old identity should be retired rather
+ than quietly reused.
"""
digest = hashlib.sha256("\n".join(sorted(members)).encode("utf-8")).hexdigest()
- return f"scc-{digest[:12]}"
+ return f"{prefix}-{digest[:12]}"
+
+
+def scc_page_slug(members: list[str]) -> str:
+ """Return the ``target_path`` for a cycle's ``scc_page``, keyed by contents.
+
+ The original case for :func:`member_structural_key`: a cycle is identified
+ by its members and nothing else.
+ """
+ return member_structural_key(members, prefix="scc")
def _parse_datetime(ts: str) -> datetime:
diff --git a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
index 37d4b919d..6f15e2af0 100644
--- a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
+++ b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
@@ -19,7 +19,11 @@ from typing import TYPE_CHECKING, Any
import structlog
from ..context_assembler import FilePageContext
-from ..models import GeneratedPage
+from ..models import (
+ STRUCTURALLY_KEYED_PAGE_TYPES,
+ GeneratedPage,
+ member_structural_key,
+)
from . import levels as _levels
from .helpers import (
_CODE_LANGUAGES,
@@ -634,6 +638,30 @@ class _GenerationRun:
deterministic run still gets mermaid repair, interlinking, related
pages and tour links over the pages it did produce.
"""
+ _stamp_structural_keys(all_pages)
+
+ # Place every page in the tree that MCP, the web app and the editor
+ # extension all read, instead of each deriving its own from paths.
+ #
+ # Skipped whenever this run holds only part of the wiki. Placement
+ # depends on the pages that are NOT in hand (which module a file sits
+ # under, who its siblings are), so a partial answer here would
+ # overwrite a correct stored one. Both partial shapes have to be
+ # named: a scoped run sets only_page_ids, and an incremental docs
+ # update stops the ladder after level 2 with file_pages_only, which
+ # leaves no overview, no modules and no layers to resolve against.
+ # Those runs are placed by the post-persist rebuild instead.
+ partial_run = bool(self.only_page_ids) or bool(
+ getattr(self.config, "file_pages_only", False)
+ )
+ if not partial_run:
+ try:
+ from ..page_tree import assign_page_tree
+
+ assign_page_tree(all_pages, self.layer_order_ids)
+ except Exception as exc:
+ log.debug("page_tree.failed", error=str(exc))
+
# Post-generation: repair mermaid diagrams so illegal node IDs / unquoted
# labels in LLM output don't break the whole diagram in the renderer.
try:
@@ -704,6 +732,40 @@ class _GenerationRun:
return all_pages
+# How each structurally-keyed type derives its identity. Member-keyed types
+# hash the files they cover; a layer is identified by its curated id, which is
+# minted once and does not move.
+_MEMBER_KEYED_PREFIX = {"module_page": "module", "scc_page": "scc"}
+
+
+def _stamp_structural_keys(pages: list[GeneratedPage]) -> None:
+ """Record the structural identity of every page that has one.
+
+ Identity has to be the thing that actually says which page this is, and
+ for a page that groups files that is the member list. It cannot be the
+ target_path: a module's target_path is a directory only when a curated
+ knowledge graph named one, and otherwise it is a clustering ordinal that
+ shifts as soon as the clustering changes. Keying on the members means the
+ page survives being renumbered, renamed, or moved to a readable target.
+
+ A page keyed on a real file path has no identity separate from that path,
+ so it is left unset rather than given a copy of the path.
+ """
+ for page in pages:
+ if page.page_type not in STRUCTURALLY_KEYED_PAGE_TYPES:
+ continue
+ prefix = _MEMBER_KEYED_PREFIX.get(page.page_type)
+ members = page.metadata.get("file_paths") or []
+ members = [m for m in members if isinstance(m, str)]
+ if prefix and members:
+ page.structural_key = member_structural_key(members, prefix=prefix)
+ else:
+ # A layer, or a member-keyed page whose members are unknown. The
+ # curated id is the best identity available and is stable for a
+ # layer; for the others this is a fallback, not the design.
+ page.structural_key = page.target_path
+
+
def _compute_kg_file_scores(kg_ctx: Any) -> dict[str, float]:
"""Derive per-file KG bonus scores from tour membership and role."""
if not kg_ctx.available:
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 82d3f0765..0c76e6091 100644
--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py
+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py
@@ -141,15 +141,22 @@ class PerTypeGenerationMixin:
"most_active_commits_90d": most_active.get("commit_count_90d", 0),
}
page_target = target_path or module_path
+ # The files this page covers. Its own identity and its place in the
+ # tree both derive from them: a module's target_path can be a
+ # clustering ordinal rather than a directory, in which case the member
+ # list is the only thing that says where the page belongs.
+ members = sorted(fc.file_path for fc in file_contexts)
if self._config.deterministic:
- return self._deterministic_module_page(
+ page = self._deterministic_module_page(
ctx, page_target, f"Module: {module_path}", module_git_summary
)
+ page.metadata["file_paths"] = members
+ return page
user_prompt = self._render("module_page.j2", ctx=ctx, module_git_summary=module_git_summary)
response = await self._call_provider(
"module_page", user_prompt, str(uuid.uuid4()), target_path=page_target
)
- return self._build_generated_page(
+ page = self._build_generated_page(
"module_page",
page_target,
f"Module: {module_path}",
@@ -157,6 +164,8 @@ class PerTypeGenerationMixin:
compute_source_hash(user_prompt),
GENERATION_LEVELS["module_page"],
)
+ page.metadata["file_paths"] = members
+ return page
async def generate_scc_page(
self,
@@ -165,13 +174,16 @@ class PerTypeGenerationMixin:
file_contexts: list[FilePageContext],
) -> GeneratedPage:
ctx = self._assembler.assemble_scc_page(scc_id, scc_files, file_contexts)
+ members = sorted(scc_files)
if self._config.deterministic:
- return self._deterministic_scc_page(ctx, scc_id, f"Circular Dependency: {scc_id}")
+ page = self._deterministic_scc_page(ctx, scc_id, f"Circular Dependency: {scc_id}")
+ page.metadata["file_paths"] = members
+ return page
user_prompt = self._render("scc_page.j2", ctx=ctx)
response = await self._call_provider(
"scc_page", user_prompt, str(uuid.uuid4()), target_path=scc_id
)
- return self._build_generated_page(
+ page = self._build_generated_page(
"scc_page",
scc_id,
f"Circular Dependency: {scc_id}",
@@ -179,6 +191,8 @@ class PerTypeGenerationMixin:
compute_source_hash(user_prompt),
GENERATION_LEVELS["scc_page"],
)
+ page.metadata["file_paths"] = members
+ return page
async def generate_repo_overview(
self,
diff --git a/packages/core/src/repowise/core/generation/page_tree.py b/packages/core/src/repowise/core/generation/page_tree.py
new file mode 100644
index 000000000..45eac9956
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/page_tree.py
@@ -0,0 +1,315 @@
+"""Place every generated page in one tree.
+
+The wiki has always had a hierarchy; it just lived in the reader. The web app
+built a four-section spine in TypeScript, the editor extension reused that
+component, breadcrumbs were re-derived from path strings a second time, and
+the MCP server could not see any of it. Three readers deriving a tree from the
+same flat list is three chances to disagree, and the agent surface got nothing.
+
+This computes the tree once, from the pages themselves, and writes it onto
+them. Parents are real pages rather than synthetic section rows, so the tree
+adds no pages and changes no ids: re-indexing an unchanged repo still produces
+exactly the rows it did before.
+
+The shape follows what the readers were already doing:
+
+ repo overview
+ onboarding pages (canonical reading order)
+ architecture diagram
+ layer pages (dependency order from the layer spine)
+ module pages (grouped under their dominant layer)
+ file pages (under the nearest module, by member or path)
+ api contracts, infra pages
+ symbol spotlights (under the file they document)
+ cycle pages
+ anything unplaced
+
+A rung only appears when the pages for it exist. A repo indexed without a
+curated knowledge graph has no layer pages, so its modules sit directly under
+the overview and the tree is two levels shallower.
+
+Everything is ordered by a total sort key, never by dict insertion, because a
+tree that reshuffles between two runs of the same commit is the same defect as
+an id that moves.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+from typing import Any
+
+from .models import GeneratedPage
+
+
+@dataclass
+class TreeNode:
+ """The part of a page the tree cares about.
+
+ Lets the placement run over rows loaded from the store as well as over
+ freshly generated pages, so an incremental update can rebuild the tree
+ from the complete page set rather than from the handful it regenerated.
+ ``GeneratedPage`` already carries these attributes and is passed directly.
+ """
+
+ page_id: str
+ page_type: str
+ target_path: str
+ metadata: dict[str, Any] = field(default_factory=dict)
+ parent_page_id: str | None = None
+ display_order: int = 0
+ section_number: str | None = None
+
+
+# Rank of each page type among siblings sharing a parent. Lower sorts first.
+# Onboarding is ranked by its slot rather than this table.
+_TYPE_RANK: dict[str, int] = {
+ "onboarding": 0,
+ "architecture_diagram": 1,
+ "layer_page": 2,
+ "module_page": 3,
+ "scc_page": 4,
+ "api_contract": 5,
+ "infra_page": 6,
+ "file_page": 7,
+ "symbol_spotlight": 8,
+}
+
+_UNRANKED = len(_TYPE_RANK)
+
+
+def _onboarding_rank(page: GeneratedPage) -> int:
+ """Position of an onboarding page in the canonical reading order."""
+ from .onboarding.slots import ONBOARDING_ORDER
+
+ slot = str(page.metadata.get("onboarding_slot") or "")
+ if not slot:
+ # The slot is the tail of the target path for dedicated onboarding pages.
+ slot = page.target_path.rsplit("/", 1)[-1]
+ try:
+ return ONBOARDING_ORDER.index(slot)
+ except ValueError:
+ return len(ONBOARDING_ORDER)
+
+
+def _sort_key(page: GeneratedPage, layer_rank: dict[str, int]) -> tuple:
+ """Total order among siblings.
+
+ Ends in the page id so two pages that tie on every meaningful signal still
+ have a defined order, which is what keeps the tree stable across runs.
+ """
+ if page.page_type == "onboarding":
+ rank = _onboarding_rank(page)
+ elif page.page_type == "layer_page":
+ rank = layer_rank.get(page.target_path, len(layer_rank))
+ else:
+ rank = 0
+ return (
+ _TYPE_RANK.get(page.page_type, _UNRANKED),
+ rank,
+ page.target_path,
+ page.page_id,
+ )
+
+
+def _dominant_layer(paths: Iterable[str], layer_of_file: dict[str, str]) -> str:
+ """The layer most of these files belong to.
+
+ Ties break on the layer id so the winner does not depend on iteration
+ order. A module straddling two layers has to land somewhere, and landing
+ in the same place every run matters more than which one it picks.
+ """
+ counts: dict[str, int] = {}
+ for path in paths:
+ layer = layer_of_file.get(path)
+ if layer:
+ counts[layer] = counts.get(layer, 0) + 1
+ if not counts:
+ return ""
+ return sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]
+
+
+def _nearest_module(path: str, module_paths: list[str]) -> str:
+ """The deepest module page whose target path contains *path*.
+
+ ``module_paths`` must be sorted longest first so the first match is the
+ most specific one.
+ """
+ for mod in module_paths:
+ if path == mod or path.startswith(mod + "/"):
+ return mod
+ return ""
+
+
+def assign_page_tree(
+ pages: list[GeneratedPage] | list[TreeNode], layer_order_ids: list[str] | None = None
+) -> None:
+ """Fill in ``parent_page_id``, ``display_order`` and ``section_number``.
+
+ Mutates the pages in place. Every parent it assigns is a page in the set:
+ each rule resolves against a different source, so the result is checked
+ rather than trusted. On a partial set that means a page whose real parent
+ was not regenerated gets the nearest ancestor that is present, or none,
+ which is why callers working from a subset rebuild from the store instead.
+ """
+ by_type: dict[str, list[GeneratedPage]] = {}
+ for page in pages:
+ by_type.setdefault(page.page_type, []).append(page)
+
+ # Sorted, not "whichever came first": repo_overview is not swept, so a
+ # store can hold a stale one from a renamed repo, and a root that flips
+ # between runs reshuffles the whole tree.
+ overviews = sorted(by_type.get("repo_overview", []), key=lambda p: p.page_id)
+ root = overviews[0] if overviews else None
+ root_id = root.page_id if root is not None else None
+
+ layer_rank = {lid: i for i, lid in enumerate(layer_order_ids or [])}
+ layer_ids = {p.target_path for p in by_type.get("layer_page", [])}
+
+ # A file's layer comes from the provenance stamped on it at generation
+ # time. Keyed on layer_id, never the display name, which drifts.
+ layer_of_file: dict[str, str] = {}
+ for page in by_type.get("file_page", []):
+ lid = page.metadata.get("layer_id")
+ if isinstance(lid, str) and lid:
+ layer_of_file[page.target_path] = lid
+
+ def layer_parent(layer_id: str) -> str | None:
+ return f"layer_page:{layer_id}" if layer_id in layer_ids else root_id
+
+ # --- Modules sit under their dominant layer ----------------------------
+ module_paths: list[str] = []
+ # Which module claims each file. A module's target_path is a directory
+ # only when a curated knowledge graph named one; otherwise it is a
+ # clustering ordinal like "community-3", which no file path can ever be a
+ # prefix of. The member list is the only signal that works in both cases,
+ # so it is the primary one and the path prefix is the fallback for pages
+ # generated before members were recorded.
+ module_of_file: dict[str, str] = {}
+ module_pages = by_type.get("module_page", [])
+ for page in module_pages:
+ members = page.metadata.get("file_paths") or page.metadata.get("files") or []
+ members = [m for m in members if isinstance(m, str)]
+ module_paths.append(page.target_path)
+ for member in members:
+ # A file claimed by two modules goes to the one whose id sorts
+ # first, so the winner does not depend on iteration order.
+ current = module_of_file.get(member)
+ if current is None or page.page_id < current:
+ module_of_file[member] = page.page_id
+ module_paths.sort(key=len, reverse=True)
+
+ def file_parent(path: str) -> str | None:
+ owner = module_of_file.get(path)
+ if owner:
+ return owner
+ mod = _nearest_module(path, module_paths)
+ if mod:
+ return f"module_page:{mod}"
+ layer = layer_of_file.get(path)
+ if layer:
+ return layer_parent(layer)
+ return root_id
+
+ for page_type in ("file_page", "api_contract", "infra_page"):
+ for page in by_type.get(page_type, []):
+ page.parent_page_id = file_parent(page.target_path)
+
+ # Now that every file has found a module, a module that recorded no
+ # members can borrow theirs. Pages written before members were recorded
+ # would otherwise report an empty membership and land on the root, which
+ # would keep every wiki indexed before this change permanently flat.
+ claimed: dict[str, list[str]] = {}
+ for page in by_type.get("file_page", []):
+ if page.parent_page_id and page.parent_page_id.startswith("module_page:"):
+ claimed.setdefault(page.parent_page_id, []).append(page.target_path)
+
+ for page in module_pages:
+ members = page.metadata.get("file_paths") or page.metadata.get("files") or []
+ members = [m for m in members if isinstance(m, str)]
+ if not members:
+ members = claimed.get(page.page_id, [])
+ page.parent_page_id = layer_parent(_dominant_layer(members, layer_of_file))
+
+ # A spotlight belongs to the file it documents: "path/to/file.py::Symbol".
+ # The file's own page may not exist: selection can spotlight a symbol in a
+ # file that did not earn a page of its own. Fall back to where that file
+ # would have sat rather than pointing at a row that is not there.
+ file_page_ids = {p.page_id for p in by_type.get("file_page", [])}
+ for page in by_type.get("symbol_spotlight", []):
+ owner = page.target_path.split("::", 1)[0]
+ owner_id = f"file_page:{owner}" if owner else ""
+ if owner_id in file_page_ids:
+ page.parent_page_id = owner_id
+ else:
+ page.parent_page_id = file_parent(owner) if owner else root_id
+
+ # A cycle spans files, often across modules. Hang it off the layer its
+ # members mostly live in rather than picking one member's module.
+ for page in by_type.get("scc_page", []):
+ members = page.metadata.get("files") or page.metadata.get("file_paths") or []
+ members = [m for m in members if isinstance(m, str)]
+ page.parent_page_id = layer_parent(_dominant_layer(members, layer_of_file))
+
+ for page in by_type.get("layer_page", []):
+ page.parent_page_id = root_id
+ for page_type in ("onboarding", "architecture_diagram"):
+ for page in by_type.get(page_type, []):
+ page.parent_page_id = root_id
+
+ if root is not None:
+ root.parent_page_id = None
+
+ # Last line of defence: a parent that is not in the set breaks every walk
+ # of the tree, and the rules above each resolve against a different
+ # source. Rather than trust them all to agree, drop any edge that does not
+ # land on a real page. Falling back to the root reads as "somewhere in
+ # this wiki", which is true; a dangling id reads as a page that exists.
+ known = {p.page_id for p in pages}
+ for page in pages:
+ if page.parent_page_id is not None and page.parent_page_id not in known:
+ page.parent_page_id = root_id if page.page_id != root_id else None
+
+ _number(pages, root_id, layer_rank)
+
+
+def _number(
+ pages: list[GeneratedPage] | list[TreeNode],
+ root_id: str | None,
+ layer_rank: dict[str, int],
+) -> None:
+ """Assign sibling order and dotted section numbers by walking the tree."""
+ children: dict[str | None, list[GeneratedPage]] = {}
+ for page in pages:
+ children.setdefault(page.parent_page_id, []).append(page)
+ for siblings in children.values():
+ siblings.sort(key=lambda p: _sort_key(p, layer_rank))
+
+ numbered: set[str] = set()
+
+ def walk(parent_id: str | None, prefix: str) -> None:
+ for index, page in enumerate(children.get(parent_id, []), start=1):
+ page.display_order = index
+ page.section_number = f"{prefix}{index}" if prefix else str(index)
+ numbered.add(page.page_id)
+ walk(page.page_id, f"{page.section_number}.")
+
+ if root_id is not None:
+ root = next(p for p in pages if p.page_id == root_id)
+ root.display_order = 0
+ root.section_number = None
+ numbered.add(root_id)
+ walk(root_id, "")
+
+ # Anything the walk did not reach: an incremental run holding pages whose
+ # parent was not regenerated, or a page the tree has no place for. Number
+ # them within their own group so they still carry an order rather than
+ # silently sharing zero, but leave section_number unset, because a dotted
+ # number that is not anchored to the root would be a lie.
+ for _parent_id, siblings in sorted(children.items(), key=lambda kv: kv[0] or ""):
+ index = 0
+ for page in siblings:
+ if page.page_id in numbered:
+ continue
+ index += 1
+ page.display_order = index
diff --git a/packages/core/src/repowise/core/persistence/crud/pages.py b/packages/core/src/repowise/core/persistence/crud/pages.py
index 7113f8874..ee61a31ee 100644
--- a/packages/core/src/repowise/core/persistence/crud/pages.py
+++ b/packages/core/src/repowise/core/persistence/crud/pages.py
@@ -47,6 +47,10 @@ def _apply_page_upsert(
confidence: float,
freshness_status: str,
meta_json: str,
+ parent_page_id: str | None,
+ display_order: int,
+ section_number: str | None,
+ structural_key: str | None,
created_at: datetime,
updated_at: datetime,
now: datetime,
@@ -63,15 +67,26 @@ def _apply_page_upsert(
# Idempotent no-op: content, prompt hash and model all unchanged, so
# do not bump the version or spawn a PageVersion snapshot; only refresh
# the cheap derived fields (metadata enrichment lands here).
+ #
+ # "Cheap derived" means anything describing where a page sits rather
+ # than what it says. Those fields come from the repo's structure, not
+ # from the page's own bytes, so they can legitimately change while the
+ # content hash does not: a renamed page, or one whose siblings moved.
+ # A field left out here is frozen at whatever the first run wrote.
if (
existing.content == content
and existing.source_hash == source_hash
and existing.model_name == model_name
):
+ existing.title = title
existing.summary = summary
existing.target_path = target_path
existing.freshness_status = freshness_status
existing.metadata_json = meta_json
+ existing.parent_page_id = parent_page_id
+ existing.display_order = display_order
+ existing.section_number = section_number
+ existing.structural_key = structural_key
return existing
# Archive the current state before overwriting
@@ -110,6 +125,10 @@ def _apply_page_upsert(
existing.confidence = confidence
existing.freshness_status = freshness_status
existing.metadata_json = meta_json
+ existing.parent_page_id = parent_page_id
+ existing.display_order = display_order
+ existing.section_number = section_number
+ existing.structural_key = structural_key
existing.updated_at = updated_at
return existing
@@ -132,6 +151,10 @@ def _apply_page_upsert(
confidence=confidence,
freshness_status=freshness_status,
metadata_json=meta_json,
+ parent_page_id=parent_page_id,
+ display_order=display_order,
+ section_number=section_number,
+ structural_key=structural_key,
created_at=created_at,
updated_at=updated_at,
)
@@ -159,6 +182,10 @@ async def upsert_page(
confidence: float = 1.0,
freshness_status: str = "fresh",
metadata: dict | None = None,
+ parent_page_id: str | None = None,
+ display_order: int = 0,
+ section_number: str | None = None,
+ structural_key: str | None = None,
created_at: datetime | None = None,
updated_at: datetime | None = None,
) -> Page:
@@ -194,6 +221,10 @@ async def upsert_page(
confidence=confidence,
freshness_status=freshness_status,
meta_json=meta_json,
+ parent_page_id=parent_page_id,
+ display_order=display_order,
+ section_number=section_number,
+ structural_key=structural_key,
created_at=created_at or now,
updated_at=updated_at or now,
now=now,
@@ -262,6 +293,10 @@ async def upsert_page_from_generated(
confidence=gp.confidence, # type: ignore[attr-defined]
freshness_status=gp.freshness_status, # type: ignore[attr-defined]
metadata=gp.metadata, # type: ignore[attr-defined]
+ parent_page_id=getattr(gp, "parent_page_id", None),
+ display_order=getattr(gp, "display_order", 0),
+ section_number=getattr(gp, "section_number", None),
+ structural_key=getattr(gp, "structural_key", None),
created_at=_parse_dt(gp.created_at), # type: ignore[attr-defined]
updated_at=_parse_dt(gp.updated_at), # type: ignore[attr-defined]
)
@@ -337,6 +372,10 @@ async def upsert_pages_from_generated(
confidence=gp.confidence,
freshness_status=gp.freshness_status,
meta_json=json.dumps(gp.metadata or {}),
+ parent_page_id=getattr(gp, "parent_page_id", None),
+ display_order=getattr(gp, "display_order", 0),
+ section_number=getattr(gp, "section_number", None),
+ structural_key=getattr(gp, "structural_key", None),
created_at=_parse_dt(gp.created_at) or now,
updated_at=_parse_dt(gp.updated_at) or now,
now=now,
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index da5301dd6..320f8c592 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -135,6 +135,31 @@ class Page(Base):
metadata_json: Mapped[str] = mapped_column(Text, nullable=False, default="{}")
# Developer-authored notes that survive LLM re-generation.
human_notes: Mapped[str | None] = mapped_column(Text, nullable=True)
+
+ # --- Where the page sits in the wiki -----------------------------------
+ # Hierarchy lives here rather than being reassembled by each reader from
+ # page_type and target_path prefixes, so MCP, the web app and the editor
+ # extension all navigate the same tree.
+ #
+ # parent_page_id references another page's id but carries no foreign key,
+ # because the generated-page sweep deletes parents whose structural key
+ # moved and the surviving children have to outlive them. Placement drops
+ # any edge that does not land on a real page, so a dangling parent is
+ # prevented where the tree is built rather than by the database.
+ parent_page_id: Mapped[str | None] = mapped_column(Text, nullable=True, index=True)
+ # Rank among siblings sharing a parent. Reading order, deliberately not
+ # generation_level, which is a build dependency order and unrelated.
+ display_order: Mapped[int] = mapped_column(
+ Integer, nullable=False, default=0, server_default="0"
+ )
+ # Dotted position in the outline, e.g. "2.4.1". Display only: it is
+ # recomputed from the tree, so nothing may key on it.
+ section_number: Mapped[str | None] = mapped_column(Text, nullable=True)
+ # The stable identity a structurally-keyed page is derived from, kept
+ # alongside the id so a key change is visible rather than only inferable
+ # from a page that stopped being reproduced.
+ structural_key: Mapped[str | None] = mapped_column(Text, nullable=True, index=True)
+
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.py
index fac897c55..578f496cd 100644
--- a/packages/core/src/repowise/core/pipeline/incremental.py
+++ b/packages/core/src/repowise/core/pipeline/incremental.py
@@ -909,6 +909,15 @@ async def persist_incremental_index(
except Exception as exc:
_skip("Tombstone marking", exc)
+ # Placement depends on the whole page set, which on an incremental
+ # run lives in the store rather than in the pages just generated.
+ try:
+ from repowise.core.pipeline.page_tree_sync import rebuild_page_tree
+
+ await rebuild_page_tree(session, repo_id)
+ except Exception as exc:
+ _skip("Page tree rebuild", exc)
+
if git_meta_map:
try:
from repowise.core.persistence.crud import (
diff --git a/packages/core/src/repowise/core/pipeline/page_tree_sync.py b/packages/core/src/repowise/core/pipeline/page_tree_sync.py
new file mode 100644
index 000000000..f1ab801c1
--- /dev/null
+++ b/packages/core/src/repowise/core/pipeline/page_tree_sync.py
@@ -0,0 +1,110 @@
+"""Rebuild the stored page tree from the complete page set.
+
+Placement is a property of the whole wiki, not of one page: which module a
+file sits under depends on which module pages exist, and a page's order
+depends on its siblings. An incremental update only holds the handful of
+pages it regenerated, so computing the tree from that set alone would answer
+with whatever happened to be in memory, and each update would flatten a little
+more of the tree.
+
+So the tree is rebuilt from the store after persisting, where the whole set
+lives. That makes added, deleted and renamed files fall out for free: the row
+set is simply what it is at that moment, and the tree describes it.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Any
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+
+async def rebuild_page_tree(session: Any, repo_id: str) -> int:
+ """Recompute and store parent, order and section for every page of a repo.
+
+ Returns the number of rows whose placement changed. Safe to call after any
+ write to wiki_pages, and cheap enough to call unconditionally: it reads
+ four small columns plus metadata and writes only what moved.
+ """
+ from sqlalchemy import select
+
+ from repowise.core.generation.page_tree import TreeNode, assign_page_tree
+ from repowise.core.persistence.models import Page
+
+ rows = (
+ (
+ await session.execute(
+ select(
+ Page.id,
+ Page.page_type,
+ Page.target_path,
+ Page.metadata_json,
+ Page.parent_page_id,
+ Page.display_order,
+ Page.section_number,
+ Page.freshness_status,
+ ).where(Page.repository_id == repo_id)
+ )
+ )
+ .tuples()
+ .all()
+ )
+ if not rows:
+ return 0
+
+ nodes: list[TreeNode] = []
+ before: dict[str, tuple[str | None, int, str | None]] = {}
+ layer_order_ids: list[str] = []
+
+ for pid, page_type, target, meta_json, parent, order, section, freshness in rows:
+ # A tombstoned page documents a file that no longer exists. Leaving it
+ # in the tree would show deleted files in the navigation, so it keeps
+ # its row and its content but loses its place.
+ if freshness == "tombstone":
+ before[pid] = (parent, order, section)
+ continue
+ try:
+ metadata = json.loads(meta_json or "{}")
+ except (json.JSONDecodeError, TypeError):
+ metadata = {}
+ if page_type == "repo_overview" and not layer_order_ids:
+ spine = metadata.get("layer_order_ids")
+ if isinstance(spine, list):
+ layer_order_ids = [s for s in spine if isinstance(s, str)]
+ before[pid] = (parent, order, section)
+ nodes.append(
+ TreeNode(
+ page_id=pid,
+ page_type=page_type or "",
+ target_path=target or "",
+ metadata=metadata if isinstance(metadata, dict) else {},
+ )
+ )
+
+ assign_page_tree(nodes, layer_order_ids)
+
+ placed = {n.page_id: (n.parent_page_id, n.display_order, n.section_number) for n in nodes}
+ changed = 0
+ for pid, current in before.items():
+ # A tombstoned page is not in ``placed``; unplace it rather than
+ # leaving whatever it carried from when its file still existed.
+ wanted = placed.get(pid, (None, 0, None))
+ if wanted != current:
+ changed += 1
+
+ if not changed:
+ return 0
+
+ for page in (
+ (await session.execute(select(Page).where(Page.repository_id == repo_id))).scalars().all()
+ ):
+ parent, order, section = placed.get(page.id, (None, 0, None))
+ page.parent_page_id = parent
+ page.display_order = order
+ page.section_number = section
+
+ logger.info("page_tree_rebuilt", repo_id=repo_id, pages=len(nodes), changed=changed)
+ return changed
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index 12aa10e25..bb2bb4ab7 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -13,6 +13,8 @@ from typing import Any
import structlog
+from repowise.core.generation.models import STRUCTURALLY_KEYED_PAGE_TYPES
+
logger = structlog.get_logger(__name__)
# Max page ids per UPDATE ... IN (...) so a large cascade cannot exceed
@@ -528,7 +530,11 @@ async def _prune_stale_file_rows(
# clustering ordinals, layer pages on display names. Those keys shift between
# runs, so re-runs mint fresh page ids and the previous rows linger as
# duplicates unless swept against the current run's output.
-_SWEPT_GENERATED_PAGE_TYPES = ("module_page", "layer_page", "scc_page")
+#
+# Same list generation stamps ``structural_key`` from, imported rather than
+# repeated: a type present in one and missing from the other is exactly the
+# bug the sweep exists to prevent.
+_SWEPT_GENERATED_PAGE_TYPES = STRUCTURALLY_KEYED_PAGE_TYPES
async def _sweep_stale_generated_pages(
@@ -1061,6 +1067,12 @@ async def persist_pipeline_result(
getattr(result, "authoritative_page_types", None),
)
+ # Placement depends on the whole page set, so it is computed here rather
+ # than during generation, after the sweep has retired anything stale.
+ from .page_tree_sync import rebuild_page_tree
+
+ await rebuild_page_tree(session, repo_id)
+
logger.info(
"pipeline_result_persisted",
repo_id=repo_id,
diff --git a/packages/core/src/repowise/core/pipeline/scoped_generation.py b/packages/core/src/repowise/core/pipeline/scoped_generation.py
index c8696218e..118be7bff 100644
--- a/packages/core/src/repowise/core/pipeline/scoped_generation.py
+++ b/packages/core/src/repowise/core/pipeline/scoped_generation.py
@@ -231,6 +231,12 @@ async def execute_scoped_generation(
marked_stale = 0
async with get_session(session_factory) as session:
await upsert_pages_from_generated(session, generated_pages, repo_id)
+ # A scoped run holds only the pages it was asked for, so it cannot
+ # work out where they sit. Placement comes from the store, which has
+ # the whole set; without this the pages it touched lose their place.
+ from .page_tree_sync import rebuild_page_tree
+
+ await rebuild_page_tree(session, repo_id)
# Dependents this run did not regenerate go stale, not wrong.
marked_stale = await mark_page_ids_stale(session, repo_id, plan.stale_ids)
# Heal backlinks + related-pages across the whole wiki, LLM-free. The
diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.py
index 34a5f2f31..2ecaac4dc 100644
--- a/packages/server/src/repowise/server/job_executor.py
+++ b/packages/server/src/repowise/server/job_executor.py
@@ -489,6 +489,14 @@ async def execute_job(
await upsert_pages_from_generated(session, incremental_pages, repo_id)
+ # These pages were generated from a changed-file subset, so
+ # they carry the placement a partial set could work out, which
+ # is none. They land after persist_pipeline_result already
+ # rebuilt the tree, so rebuild again or they stay unplaced.
+ from repowise.core.pipeline.page_tree_sync import rebuild_page_tree
+
+ await rebuild_page_tree(session, repo_id)
+
# Drop swept pages from the vector store *before* the SQL session
# commits. The vector store is a separate engine/file (pgvector DB,
# LanceDB dir, or in-memory), so there is no SQLite write-lock
diff --git a/packages/server/src/repowise/server/schemas/pages.py b/packages/server/src/repowise/server/schemas/pages.py
index 775a668cd..494d72f7b 100644
--- a/packages/server/src/repowise/server/schemas/pages.py
+++ b/packages/server/src/repowise/server/schemas/pages.py
@@ -34,6 +34,12 @@ class PageResponse(BaseModel):
is_deterministic: bool = False
doc_tier: int | None = None
human_notes: str | None = None
+ # Position in the wiki outline. Older rows carry no placement, which reads
+ # as a flat wiki and is what those rows actually describe.
+ parent_page_id: str | None = None
+ display_order: int = 0
+ section_number: str | None = None
+ structural_key: str | None = None
created_at: datetime
updated_at: datetime
@@ -61,6 +67,10 @@ class PageResponse(BaseModel):
is_deterministic=obj.provider_name == "template", # type: ignore[attr-defined]
doc_tier=metadata.get("doc_tier"),
human_notes=obj.human_notes, # type: ignore[attr-defined]
+ parent_page_id=obj.parent_page_id, # type: ignore[attr-defined]
+ display_order=obj.display_order, # type: ignore[attr-defined]
+ section_number=obj.section_number, # type: ignore[attr-defined]
+ structural_key=obj.structural_key, # type: ignore[attr-defined]
created_at=obj.created_at, # type: ignore[attr-defined]
updated_at=obj.updated_at, # type: ignore[attr-defined]
)
diff --git a/packages/types/src/docs.ts b/packages/types/src/docs.ts
index 8721d6338..a32c35eef 100644
--- a/packages/types/src/docs.ts
+++ b/packages/types/src/docs.ts
@@ -36,6 +36,15 @@ export interface DocPage {
is_deterministic?: boolean;
doc_tier?: number | null;
human_notes: string | null;
+ /**
+ * Position in the wiki outline, computed once at generation time so every
+ * reader navigates the same tree. Optional: pages written before the wiki
+ * carried a tree have no placement, which reads as flat.
+ */
+ parent_page_id?: string | null;
+ display_order?: number;
+ section_number?: string | null;
+ structural_key?: string | null;
created_at: string;
updated_at: string;
}
diff --git a/tests/integration/test_wiki_idempotence.py b/tests/integration/test_wiki_idempotence.py
new file mode 100644
index 000000000..824da6351
--- /dev/null
+++ b/tests/integration/test_wiki_idempotence.py
@@ -0,0 +1,428 @@
+"""Two consecutive full indexes of an unchanged tree must converge.
+
+``test_generation_determinism.py`` proves the *generator* mints the same page
+ids twice. That is necessary and not sufficient: the ids then go through an
+upsert keyed on ``page_id`` and a sweep that retires structurally-keyed pages
+the run did not reproduce. A page type whose key drifts, or one that is missing
+from the sweep list, produces a store that grows on every re-index while the
+generator looks perfectly stable.
+
+These tests close that gap at the store level: generate twice, persist both
+runs into the same database through the real persist pair, and assert the row
+set is byte-identical. That is the only guard against silently doubling the
+wiki, and it is the contract any new structurally-keyed page type has to meet
+before it ships.
+
+Read ``test_persist_sweep_pages.py`` for the sweep's own unit behaviour. This
+file exercises the composition, on real generated output.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.generation.context_assembler import ContextAssembler
+from repowise.core.generation.models import GeneratedPage, GenerationConfig
+from repowise.core.generation.page_generator import PageGenerator
+from repowise.core.ingestion.graph import GraphBuilder
+from repowise.core.ingestion.models import PackageInfo, ParsedFile, RepoStructure
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.traverser import FileTraverser
+from repowise.core.persistence.database import init_db
+from repowise.core.persistence.models import Page
+from repowise.core.pipeline.persist import (
+ _SWEPT_GENERATED_PAGE_TYPES,
+ _sweep_stale_generated_pages,
+)
+
+SAMPLE_REPO = Path(__file__).parents[1] / "fixtures" / "sample_repo"
+
+
+# ---------------------------------------------------------------------------
+# Generation
+# ---------------------------------------------------------------------------
+
+
+def _parse_sample_repo() -> tuple[list[ParsedFile], dict[str, bytes]]:
+ traverser = FileTraverser(SAMPLE_REPO)
+ parser = ASTParser()
+ parsed_files: list[ParsedFile] = []
+ source_map: dict[str, bytes] = {}
+ for fi in traverser.traverse():
+ try:
+ src = Path(fi.abs_path).read_bytes()
+ parsed_files.append(parser.parse_file(fi, src))
+ source_map[fi.path] = src
+ except Exception:
+ pass
+ return parsed_files, source_map
+
+
+async def _generate(parsed_files, source_map, tmp) -> list[GeneratedPage]:
+ """One full generation run over the sample repo, no LLM."""
+ from repowise.core.providers.llm.template import TemplateProvider
+
+ builder = GraphBuilder()
+ for p in parsed_files:
+ builder.add_file(p)
+ builder.build()
+
+ packages = [
+ PackageInfo(
+ name=d.name, path=d.name, language="unknown", entry_points=[], manifest_file=""
+ )
+ for d in SAMPLE_REPO.iterdir()
+ if d.is_dir()
+ ]
+ repo_structure = RepoStructure(
+ is_monorepo=len(packages) > 1,
+ packages=packages,
+ root_language_distribution={"python": 0.7, "typescript": 0.3},
+ total_files=len(parsed_files),
+ total_loc=sum(
+ len(source_map.get(p.file_info.path, b"").splitlines()) for p in parsed_files
+ ),
+ entry_points=[],
+ )
+ config = GenerationConfig(deterministic=True, max_concurrency=3, jobs_dir=str(tmp / "jobs"))
+ generator = PageGenerator(TemplateProvider(), ContextAssembler(config), config)
+ return await generator.generate_all(
+ parsed_files, source_map, builder, repo_structure, "sample_repo", job_system=None
+ )
+
+
+# ---------------------------------------------------------------------------
+# Persistence
+# ---------------------------------------------------------------------------
+
+
+def _authority(pages: list[GeneratedPage]) -> set[str]:
+ """The swept types this run is entitled to speak for.
+
+ Full authority, which is stricter than what ``orchestrator`` would grant
+ this fixture: it makes the sweep as aggressive as it can be, so an
+ unstable id has the best possible chance of showing up as a stranded row.
+ Deliberately not a copy of the orchestrator's rule, which depends on
+ curated-KG state this fixture does not have.
+ """
+ return set(_SWEPT_GENERATED_PAGE_TYPES)
+
+
+async def _persist_full_run(sf, repo_id: str, pages: list[GeneratedPage]) -> list[str]:
+ """The page half of a full index: upsert, sweep, then rebuild the tree.
+
+ Deliberately the same three steps in the same order as
+ ``persist_pipeline_result``. The rebuild is part of it: leave it out and
+ deleting the production call stays green, which is how it was missed.
+ """
+ from repowise.core.persistence import upsert_pages_from_generated
+ from repowise.core.pipeline.page_tree_sync import rebuild_page_tree
+
+ async with sf() as session:
+ await upsert_pages_from_generated(session, pages, repo_id)
+ swept = await _sweep_stale_generated_pages(session, repo_id, pages, _authority(pages))
+ await rebuild_page_tree(session, repo_id)
+ await session.commit()
+ return swept
+
+
+async def _page_rows(sf, repo_id: str) -> list[tuple[str, str, str]]:
+ async with sf() as session:
+ rows = await session.execute(
+ select(Page.id, Page.page_type, Page.target_path)
+ .where(Page.repository_id == repo_id)
+ .order_by(Page.id)
+ )
+ return [tuple(r) for r in rows.all()]
+
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
[email protected](scope="module")
+async def engine():
+ eng = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(eng)
+ yield eng
+ await eng.dispose()
+
+
[email protected](scope="module")
+def sf(engine):
+ return async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+
+
[email protected](scope="module")
+async def two_indexes(sf, tmp_path_factory):
+ """Index the same tree twice into one store, snapshotting rows after each."""
+ from repowise.core.persistence.crud import upsert_repository
+
+ tmp = tmp_path_factory.mktemp("wiki_idempotence")
+ parsed_files, source_map = _parse_sample_repo()
+
+ async with sf() as session:
+ repo = await upsert_repository(
+ session,
+ name="sample_repo",
+ local_path=str(SAMPLE_REPO),
+ url="https://github.com/example/sample_repo",
+ )
+ repo_id = repo.id
+ await session.commit()
+
+ first_pages = await _generate(parsed_files, source_map, tmp / "a")
+ first_swept = await _persist_full_run(sf, repo_id, first_pages)
+ first_rows = await _page_rows(sf, repo_id)
+
+ second_pages = await _generate(parsed_files, source_map, tmp / "b")
+ second_swept = await _persist_full_run(sf, repo_id, second_pages)
+ second_rows = await _page_rows(sf, repo_id)
+
+ return {
+ "repo_id": repo_id,
+ "first_pages": first_pages,
+ "second_pages": second_pages,
+ "first_rows": first_rows,
+ "second_rows": second_rows,
+ "first_swept": first_swept,
+ "second_swept": second_swept,
+ "sf": sf,
+ }
+
+
+# ---------------------------------------------------------------------------
+# The gate
+# ---------------------------------------------------------------------------
+
+
+class TestReindexIdempotence:
+ async def test_the_run_produced_something(self, two_indexes):
+ """Guards the rest of the class from passing vacuously on an empty run."""
+ assert two_indexes["first_pages"]
+ assert two_indexes["first_rows"]
+
+ async def test_page_count_is_unchanged_by_the_second_index(self, two_indexes):
+ """The headline contract. A growing count is the wiki doubling."""
+ assert len(two_indexes["second_rows"]) == len(two_indexes["first_rows"])
+
+ async def test_page_ids_are_unchanged_by_the_second_index(self, two_indexes):
+ """Stronger than the count: the same rows, not merely as many."""
+ assert two_indexes["second_rows"] == two_indexes["first_rows"]
+
+ async def test_second_index_sweeps_nothing(self, two_indexes):
+ """Nothing to retire means no id moved between the two runs.
+
+ A non-empty sweep here would still leave the counts equal (one row
+ retired, one minted), so this is the assertion that localises an
+ unstable key rather than just detecting growth.
+ """
+ assert two_indexes["second_swept"] == []
+
+ async def test_no_duplicate_target_path_within_a_page_type(self, two_indexes):
+ """Two ids for one thing is the doubling failure wearing a disguise.
+
+ Distinct page types legitimately share a target_path (a file page and
+ its api_contract), so the uniqueness claim is per type.
+ """
+ seen: dict[tuple[str, str], int] = {}
+ for _id, page_type, target in two_indexes["second_rows"]:
+ seen[(page_type, target)] = seen.get((page_type, target), 0) + 1
+ assert [k for k, n in seen.items() if n > 1] == []
+
+ async def test_every_swept_type_present_is_reproduced_identically(self, two_indexes):
+ """Per-type restatement, so a failure names the type that drifted."""
+
+ def by_type(rows):
+ out: dict[str, set[str]] = {}
+ for _id, page_type, _target in rows:
+ out.setdefault(page_type, set()).add(_id)
+ return out
+
+ first, second = by_type(two_indexes["first_rows"]), by_type(two_indexes["second_rows"])
+ for page_type in _SWEPT_GENERATED_PAGE_TYPES:
+ assert first.get(page_type) == second.get(page_type), page_type
+
+ async def test_second_index_does_not_grow_the_version_history(self, two_indexes):
+ """An unchanged tree must take the idempotent-touch branch.
+
+ If re-indexing archived a version per page it would mean the content
+ hash moved, which is the same instability as a moving id one level
+ down, and it grows the store without bound.
+ """
+ from repowise.core.persistence.models import PageVersion
+
+ sf = two_indexes["sf"]
+ async with sf() as session:
+ total = await session.scalar(
+ select(func.count())
+ .select_from(PageVersion)
+ .where(PageVersion.repository_id == two_indexes["repo_id"])
+ )
+ assert total == 0
+
+
+class TestStructuralKeys:
+ """Every page whose identity is structural must say so on the row.
+
+ The three swept page types are already keyed on structure through their
+ target_path. Recording that in its own column is what lets identity and
+ location stop being the same string: a page can then keep a real directory
+ as its target_path, which is what readers and links need, while its
+ identity follows its members.
+ """
+
+ async def test_member_keyed_pages_key_on_members_not_on_their_target(self, two_indexes):
+ """The point of the column.
+
+ A module's target_path is a clustering ordinal unless a curated
+ knowledge graph named a directory, and that ordinal is exactly what
+ moves between runs. A structural key equal to the target would record
+ the unstable value and be a copy of the page id besides.
+ """
+ from repowise.core.generation.models import member_structural_key
+
+ checked = 0
+ for page in two_indexes["second_pages"]:
+ if page.page_type not in ("module_page", "scc_page"):
+ continue
+ members = page.metadata.get("file_paths") or []
+ assert members, f"{page.page_id} recorded no members"
+ prefix = "module" if page.page_type == "module_page" else "scc"
+ assert page.structural_key == member_structural_key(members, prefix=prefix)
+ checked += 1
+ assert checked, "sample repo produced no member-keyed pages"
+
+ async def test_a_module_key_is_not_just_its_target_path(self, two_indexes):
+ """Guards the above against being satisfied by a copy."""
+ modules = [p for p in two_indexes["second_pages"] if p.page_type == "module_page"]
+ assert modules
+ assert all(p.structural_key != p.target_path for p in modules)
+
+ async def test_file_pages_have_no_structural_key(self, two_indexes):
+ """A file page is identified by its path. Nothing structural to record."""
+ sf = two_indexes["sf"]
+ async with sf() as session:
+ rows = await session.execute(
+ select(Page.id, Page.structural_key).where(
+ Page.repository_id == two_indexes["repo_id"],
+ Page.page_type == "file_page",
+ )
+ )
+ assert [pid for pid, key in rows.all() if key is not None] == []
+
+ async def test_structural_keys_are_stable_across_the_two_indexes(self, two_indexes):
+ """The whole point: the key must not move when nothing moved."""
+ first = {p.page_id: p.structural_key for p in two_indexes["first_pages"]}
+ second = {p.page_id: p.structural_key for p in two_indexes["second_pages"]}
+ assert first == second
+
+
+class TestTreeOnRealOutput:
+ """The synthetic tree tests cover the shape rules. These check the tree
+ that a real generation run actually produces, and that it survives a
+ second index unchanged."""
+
+ async def test_the_tree_has_real_depth(self, two_indexes):
+ """A flat wiki where every page hangs off the overview satisfies
+ "has a parent" and is exactly the failure this must catch.
+
+ The bar is one rung below the top, not two: this repo is indexed
+ without a curated knowledge graph, so it has no layer pages and its
+ modules sit directly under the overview. Files under modules is the
+ deepest this fixture can go, and it is the rung that was broken.
+ """
+ depths = [
+ p.section_number.count(".")
+ for p in two_indexes["second_pages"]
+ if p.section_number
+ ]
+ assert depths, "generation produced no tree"
+ assert max(depths) >= 1, f"tree is only {max(depths) + 1} levels deep"
+
+ async def test_most_file_pages_sit_under_a_module(self, two_indexes):
+ """Modules here are keyed by a clustering ordinal, not a directory, so
+ this only passes if placement uses the recorded member list rather
+ than a path prefix. It was zero before members were recorded."""
+ files = [p for p in two_indexes["second_pages"] if p.page_type == "file_page"]
+ under_module = [
+ p for p in files if (p.parent_page_id or "").startswith("module_page:")
+ ]
+ assert len(under_module) >= len(files) // 3, (
+ f"only {len(under_module)} of {len(files)} file pages found a module"
+ )
+
+ async def test_module_pages_have_children(self, two_indexes):
+ modules = {
+ p.page_id for p in two_indexes["second_pages"] if p.page_type == "module_page"
+ }
+ assert modules
+ parented = {p.parent_page_id for p in two_indexes["second_pages"]}
+ assert modules & parented, "no page sits under any module"
+
+ async def test_no_page_points_at_a_parent_that_does_not_exist(self, two_indexes):
+ """A dangling parent breaks every walk of the tree."""
+ known = {pid for pid, _, _ in two_indexes["second_rows"]}
+ sf = two_indexes["sf"]
+ async with sf() as session:
+ rows = await session.execute(
+ select(Page.id, Page.parent_page_id).where(
+ Page.repository_id == two_indexes["repo_id"],
+ Page.parent_page_id.is_not(None),
+ )
+ )
+ dangling = [(pid, parent) for pid, parent in rows.all() if parent not in known]
+ assert dangling == []
+
+ async def test_the_tree_has_no_cycles(self, two_indexes):
+ sf = two_indexes["sf"]
+ async with sf() as session:
+ rows = await session.execute(
+ select(Page.id, Page.parent_page_id).where(
+ Page.repository_id == two_indexes["repo_id"]
+ )
+ )
+ parent = dict(rows.all())
+ for start in parent:
+ seen, node = set(), start
+ while node is not None:
+ assert node not in seen, f"cycle through {start}"
+ seen.add(node)
+ node = parent.get(node)
+
+ async def test_the_tree_is_identical_after_the_second_index(self, two_indexes):
+ """Placement is derived from structure, so an unchanged repo must
+ place its pages exactly where the previous run did."""
+
+ def placement(pages):
+ return {
+ p.page_id: (p.parent_page_id, p.display_order, p.section_number) for p in pages
+ }
+
+ assert placement(two_indexes["second_pages"]) == placement(two_indexes["first_pages"])
+
+ async def test_placement_reached_the_database(self, two_indexes):
+ """The tree is only useful if it is stored, not just computed."""
+ expected = {
+ p.page_id: (p.parent_page_id, p.display_order, p.section_number)
+ for p in two_indexes["second_pages"]
+ }
+ sf = two_indexes["sf"]
+ async with sf() as session:
+ rows = await session.execute(
+ select(
+ Page.id, Page.parent_page_id, Page.display_order, Page.section_number
+ ).where(Page.repository_id == two_indexes["repo_id"])
+ )
+ stored = {pid: (parent, order, section) for pid, parent, order, section in rows.all()}
+ assert stored == expected
diff --git a/tests/unit/generation/test_page_tree.py b/tests/unit/generation/test_page_tree.py
new file mode 100644
index 000000000..5ff14d015
--- /dev/null
+++ b/tests/unit/generation/test_page_tree.py
@@ -0,0 +1,272 @@
+"""The wiki tree: shape, ordering, and stability across runs."""
+
+from __future__ import annotations
+
+import random
+
+from repowise.core.generation.models import GeneratedPage
+from repowise.core.generation.page_tree import assign_page_tree
+
+
+def _page(page_type: str, target: str, **metadata) -> GeneratedPage:
+ return GeneratedPage(
+ page_id=f"{page_type}:{target}",
+ page_type=page_type,
+ title=target,
+ content="body",
+ source_hash="h" * 64,
+ model_name="m",
+ provider_name="template",
+ input_tokens=0,
+ output_tokens=0,
+ cached_tokens=0,
+ generation_level=0,
+ target_path=target,
+ created_at="2026-07-23T00:00:00+00:00",
+ updated_at="2026-07-23T00:00:00+00:00",
+ metadata=dict(metadata),
+ )
+
+
+def _wiki() -> list[GeneratedPage]:
+ """A small wiki with two layers, two modules and files under each."""
+ return [
+ _page("repo_overview", "demo"),
+ _page("onboarding", "onboarding/getting_started"),
+ _page("onboarding", "onboarding/project_overview"),
+ _page("architecture_diagram", "demo"),
+ _page("layer_page", "layer:service"),
+ _page("layer_page", "layer:ui"),
+ _page("module_page", "src/ingest", file_paths=["src/ingest/a.py", "src/ingest/b.py"]),
+ _page("module_page", "src/web", file_paths=["src/web/app.tsx"]),
+ _page("file_page", "src/ingest/a.py", layer_id="layer:service"),
+ _page("file_page", "src/ingest/b.py", layer_id="layer:service"),
+ _page("file_page", "src/web/app.tsx", layer_id="layer:ui"),
+ _page("file_page", "scripts/tool.py", layer_id="layer:service"),
+ _page("symbol_spotlight", "src/ingest/a.py::Parser"),
+ ]
+
+
+# Deliberately the reverse of alphabetical order, so a test that claims the
+# spine beats the alphabet actually discriminates between them.
+LAYER_ORDER = ["layer:ui", "layer:service"]
+
+
+def _by_id(pages):
+ return {p.page_id: p for p in pages}
+
+
+class TestShape:
+ def test_overview_is_the_root(self):
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ assert _by_id(pages)["repo_overview:demo"].parent_page_id is None
+
+ def test_every_other_page_has_a_parent(self):
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ orphans = [
+ p.page_id
+ for p in pages
+ if p.page_type != "repo_overview" and p.parent_page_id is None
+ ]
+ assert orphans == []
+
+ def test_every_parent_exists(self):
+ """A dangling parent is worse than no parent: it breaks the walk."""
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ known = {p.page_id for p in pages}
+ dangling = [
+ (p.page_id, p.parent_page_id)
+ for p in pages
+ if p.parent_page_id is not None and p.parent_page_id not in known
+ ]
+ assert dangling == []
+
+ def test_file_sits_under_its_nearest_module(self):
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ assert _by_id(pages)["file_page:src/ingest/a.py"].parent_page_id == "module_page:src/ingest"
+
+ def test_module_sits_under_its_dominant_layer(self):
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ assert _by_id(pages)["module_page:src/ingest"].parent_page_id == "layer_page:layer:service"
+ assert _by_id(pages)["module_page:src/web"].parent_page_id == "layer_page:layer:ui"
+
+ def test_file_with_no_module_falls_back_to_its_layer(self):
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ assert _by_id(pages)["file_page:scripts/tool.py"].parent_page_id == "layer_page:layer:service"
+
+ def test_spotlight_sits_under_the_file_it_documents(self):
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ spotlight = _by_id(pages)["symbol_spotlight:src/ingest/a.py::Parser"]
+ assert spotlight.parent_page_id == "file_page:src/ingest/a.py"
+
+ def test_no_cycles(self):
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ parent = {p.page_id: p.parent_page_id for p in pages}
+ for start in parent:
+ seen, node = set(), start
+ while node is not None:
+ assert node not in seen, f"cycle through {start}"
+ seen.add(node)
+ node = parent.get(node)
+
+
+class TestOrdering:
+ def test_layers_follow_the_spine_not_the_alphabet(self):
+ """`layer:service` sorts first alphabetically; the spine puts
+ `layer:ui` first, and the spine must win."""
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ by_id = _by_id(pages)
+ assert (
+ by_id["layer_page:layer:ui"].display_order
+ < by_id["layer_page:layer:service"].display_order
+ )
+
+ def test_without_a_spine_layers_fall_back_to_a_stable_order(self):
+ pages = _wiki()
+ assign_page_tree(pages, [])
+ by_id = _by_id(pages)
+ assert (
+ by_id["layer_page:layer:service"].display_order
+ < by_id["layer_page:layer:ui"].display_order
+ )
+
+ def test_onboarding_follows_the_canonical_reading_order(self):
+ """project_overview comes before getting_started in the slot order,
+ and after it in the alphabet."""
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ by_id = _by_id(pages)
+ assert (
+ by_id["onboarding:onboarding/project_overview"].display_order
+ < by_id["onboarding:onboarding/getting_started"].display_order
+ )
+
+ def test_siblings_are_numbered_from_one_without_gaps(self):
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ groups: dict[str | None, list[int]] = {}
+ for p in pages:
+ if p.page_type != "repo_overview":
+ groups.setdefault(p.parent_page_id, []).append(p.display_order)
+ for orders in groups.values():
+ assert sorted(orders) == list(range(1, len(orders) + 1))
+
+ def test_section_numbers_are_the_literal_dotted_path(self):
+ """Pinned literals. Prefix-nesting alone survives an off-by-one in the
+ numbering, and the dotted number is what a reader is told to cite."""
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ by_id = _by_id(pages)
+ assert by_id["onboarding:onboarding/project_overview"].section_number == "1"
+ assert by_id["layer_page:layer:ui"].section_number == "4"
+ assert by_id["module_page:src/web"].section_number == "4.1"
+ assert by_id["file_page:src/web/app.tsx"].section_number == "4.1.1"
+
+ def test_section_number_reflects_depth(self):
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ by_id = _by_id(pages)
+ layer = by_id["layer_page:layer:service"]
+ module = by_id["module_page:src/ingest"]
+ assert module.section_number.startswith(layer.section_number + ".")
+ assert by_id["file_page:src/ingest/a.py"].section_number.startswith(
+ module.section_number + "."
+ )
+
+
+class TestStability:
+ def test_input_order_does_not_change_the_tree(self):
+ """Pages arrive in completion order, which varies between runs."""
+ a, b = _wiki(), _wiki()
+ random.Random(7).shuffle(b)
+ assign_page_tree(a, LAYER_ORDER)
+ assign_page_tree(b, LAYER_ORDER)
+ placed = lambda ps: { # noqa: E731
+ p.page_id: (p.parent_page_id, p.display_order, p.section_number) for p in ps
+ }
+ assert placed(a) == placed(b)
+
+ def test_running_it_twice_is_a_no_op(self):
+ pages = _wiki()
+ assign_page_tree(pages, LAYER_ORDER)
+ first = {p.page_id: (p.parent_page_id, p.display_order, p.section_number) for p in pages}
+ assign_page_tree(pages, LAYER_ORDER)
+ second = {p.page_id: (p.parent_page_id, p.display_order, p.section_number) for p in pages}
+ assert first == second
+
+
+class TestPartialSets:
+ """An incremental run holds only the pages it regenerated."""
+
+ def test_a_lone_file_page_is_not_reparented_to_something_arbitrary(self):
+ pages = [_page("file_page", "src/ingest/a.py", layer_id="layer:service")]
+ # A sentinel, so a placement pass that never ran is distinguishable
+ # from one that deliberately assigned nothing.
+ pages[0].parent_page_id = "sentinel:not-a-page"
+ assign_page_tree(pages, LAYER_ORDER)
+ # No module, no layer page and no overview in the set: nothing to
+ # point at, so it points at nothing rather than at a wrong parent.
+ assert pages[0].parent_page_id is None
+
+ def test_a_partial_set_still_gets_an_order(self):
+ pages = [
+ _page("file_page", "src/ingest/a.py", layer_id="layer:service"),
+ _page("file_page", "src/ingest/b.py", layer_id="layer:service"),
+ ]
+ assign_page_tree(pages, LAYER_ORDER)
+ assert sorted(p.display_order for p in pages) == [1, 2]
+
+ def test_empty_input_is_harmless(self):
+ assign_page_tree([], LAYER_ORDER)
+
+
+class TestDanglingParents:
+ """Found on a real 1,775-page wiki, not on the fixture: a spotlight whose
+ file never earned a page of its own pointed at a row that did not exist."""
+
+ def test_spotlight_without_a_file_page_falls_back(self):
+ pages = [
+ _page("repo_overview", "demo"),
+ _page("layer_page", "layer:service"),
+ _page("module_page", "src/ingest", file_paths=["src/ingest/a.py"]),
+ _page("symbol_spotlight", "src/ingest/a.py::Parser"),
+ ]
+ assign_page_tree(pages, LAYER_ORDER)
+ spotlight = _by_id(pages)["symbol_spotlight:src/ingest/a.py::Parser"]
+ assert spotlight.parent_page_id == "module_page:src/ingest"
+ assert spotlight.parent_page_id in {p.page_id for p in pages}
+
+ def test_spotlight_with_no_home_at_all_lands_on_the_root(self):
+ pages = [
+ _page("repo_overview", "demo"),
+ _page("symbol_spotlight", "vendor/x.py::Thing"),
+ ]
+ assign_page_tree(pages, LAYER_ORDER)
+ assert _by_id(pages)["symbol_spotlight:vendor/x.py::Thing"].parent_page_id == (
+ "repo_overview:demo"
+ )
+
+ def test_no_page_ever_points_outside_the_set(self):
+ """The invariant, asserted over a set with several broken references."""
+ pages = [
+ _page("repo_overview", "demo"),
+ _page("symbol_spotlight", "gone.py::A"),
+ _page("file_page", "orphan.py", layer_id="layer:nonexistent"),
+ _page("scc_page", "scc-abc", files=["gone.py", "orphan.py"]),
+ ]
+ assign_page_tree(pages, LAYER_ORDER)
+ known = {p.page_id for p in pages}
+ assert [
+ (p.page_id, p.parent_page_id)
+ for p in pages
+ if p.parent_page_id is not None and p.parent_page_id not in known
+ ] == []
diff --git a/tests/unit/generation/test_structural_key.py b/tests/unit/generation/test_structural_key.py
new file mode 100644
index 000000000..9cdabc05e
--- /dev/null
+++ b/tests/unit/generation/test_structural_key.py
@@ -0,0 +1,68 @@
+"""Properties of the structural key, and the one list it shares with the sweep."""
+
+from __future__ import annotations
+
+from repowise.core.generation.models import (
+ STRUCTURALLY_KEYED_PAGE_TYPES,
+ member_structural_key,
+ scc_page_slug,
+)
+
+
+class TestMemberStructuralKey:
+ def test_member_order_does_not_matter(self):
+ assert member_structural_key(["b.py", "a.py"], prefix="grp") == member_structural_key(
+ ["a.py", "b.py"], prefix="grp"
+ )
+
+ def test_different_members_give_different_keys(self):
+ assert member_structural_key(["a.py", "b.py"], prefix="grp") != member_structural_key(
+ ["a.py", "c.py"], prefix="grp"
+ )
+
+ def test_membership_change_moves_the_key(self):
+ """Intended: the page now covers a different thing, so it is a new page."""
+ assert member_structural_key(["a.py"], prefix="grp") != member_structural_key(
+ ["a.py", "b.py"], prefix="grp"
+ )
+
+ def test_prefix_separates_namespaces(self):
+ """The same members under two groupings are not the same page."""
+ assert member_structural_key(["a.py"], prefix="scc") != member_structural_key(
+ ["a.py"], prefix="grp"
+ )
+
+ def test_key_carries_no_path_syntax(self):
+ """Ids flow into target_path, which the answer layer treats as a file
+ target unless it is obviously not one."""
+ key = member_structural_key(["pkg/a.py", "pkg/b.py"], prefix="grp")
+ assert key.startswith("grp-")
+ assert "/" not in key and "." not in key
+
+ def test_accepts_any_iterable(self):
+ assert member_structural_key(iter(["b.py", "a.py"]), prefix="grp") == (
+ member_structural_key({"a.py", "b.py"}, prefix="grp")
+ )
+
+
+class TestSccSlugUnchanged:
+ """The slug was the original of this pattern; generalising it must not
+ move any existing SCC page id."""
+
+ def test_slug_is_the_member_key_under_its_own_prefix(self):
+ members = ["pkg/a.py", "pkg/b.py"]
+ assert scc_page_slug(members) == member_structural_key(members, prefix="scc")
+
+ def test_slug_value_is_pinned(self):
+ """Pinned literal, so a refactor that changes the hash is loud.
+
+ Every SCC page in every existing store is keyed on this exact value.
+ """
+ assert scc_page_slug(["a.py", "b.py"]) == "scc-c643247e56f2"
+
+
+def test_the_sweep_uses_the_same_list_generation_stamps():
+ """A type in one list and not the other is the doubling bug itself."""
+ from repowise.core.pipeline.persist import _SWEPT_GENERATED_PAGE_TYPES
+
+ assert _SWEPT_GENERATED_PAGE_TYPES is STRUCTURALLY_KEYED_PAGE_TYPES
diff --git a/tests/unit/persistence/test_page_hierarchy_migration.py b/tests/unit/persistence/test_page_hierarchy_migration.py
new file mode 100644
index 000000000..5e71e8d40
--- /dev/null
+++ b/tests/unit/persistence/test_page_hierarchy_migration.py
@@ -0,0 +1,147 @@
+"""An existing wiki store gains the hierarchy columns without a manual step.
+
+Local stores are never migrated by Alembic: ``init_db`` reconciles the live
+schema against the ORM model and issues the missing ALTER TABLEs itself. That
+is the path every existing OSS user takes, so it is the one worth testing.
+Alembic covers the hosted Postgres deployments, which run it explicitly.
+
+The store here is built and then stripped back to its pre-hierarchy shape, so
+the test exercises a real upgrade rather than a fresh create.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.persistence.crud import get_page, upsert_page, upsert_repository
+from repowise.core.persistence.database import init_db
+
+_HIERARCHY_COLUMNS = ("parent_page_id", "display_order", "section_number", "structural_key")
+
+_PAGE_ID = "file_page:src/app.py"
+
+
+async def _columns(engine) -> set[str]:
+ async with engine.connect() as conn:
+ rows = await conn.execute(text("PRAGMA table_info(wiki_pages)"))
+ return {r[1] for r in rows.all()}
+
+
+async def legacy_store():
+ """A store holding one page, with the hierarchy columns removed again."""
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+
+ sf = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ async with sf() as session:
+ repo = await upsert_repository(
+ session, name="r", local_path="/tmp/r", url="https://example.com/r"
+ )
+ repo_id = repo.id
+ await upsert_page(
+ session,
+ page_id=_PAGE_ID,
+ repository_id=repo_id,
+ page_type="file_page",
+ title="app.py",
+ content="Body.",
+ target_path="src/app.py",
+ source_hash="h" * 64,
+ model_name="mock",
+ provider_name="mock",
+ )
+ await session.commit()
+
+ # Roll the schema back to its pre-hierarchy shape. The indexes go first:
+ # SQLite refuses to drop a column an index still references.
+ async with engine.begin() as conn:
+ await conn.execute(text("DROP INDEX IF EXISTS ix_wiki_pages_parent_page_id"))
+ await conn.execute(text("DROP INDEX IF EXISTS ix_wiki_pages_structural_key"))
+ for column in _HIERARCHY_COLUMNS:
+ await conn.execute(text(f"ALTER TABLE wiki_pages DROP COLUMN {column}"))
+
+ yield engine, repo_id
+ await engine.dispose()
+
+
+async def test_the_fixture_really_produced_a_legacy_store(legacy_store):
+ """Otherwise the upgrade below would be testing a fresh create."""
+ engine, _ = legacy_store
+ assert set(_HIERARCHY_COLUMNS).isdisjoint(await _columns(engine))
+
+
+async def test_init_db_adds_the_hierarchy_columns_to_an_existing_store(legacy_store):
+ engine, _ = legacy_store
+ await init_db(engine)
+ assert set(_HIERARCHY_COLUMNS) <= await _columns(engine)
+
+
+async def test_the_existing_page_survives_the_upgrade(legacy_store):
+ """A backfilled row must still be readable, and read as unplaced.
+
+ Null parent and order zero is the honest description of a page written
+ before the wiki had a tree, and it is what keeps the page serving instead
+ of 404ing while the rollout is half-done.
+ """
+ engine, _ = legacy_store
+ await init_db(engine)
+
+ sf = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ async with sf() as session:
+ page = await get_page(session, _PAGE_ID)
+
+ assert page is not None
+ assert page.title == "app.py"
+ assert page.parent_page_id is None
+ assert page.display_order == 0
+ assert page.section_number is None
+ assert page.structural_key is None
+
+
+async def test_an_upgraded_store_accepts_hierarchy_writes(legacy_store):
+ engine, repo_id = legacy_store
+ await init_db(engine)
+
+ sf = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ async with sf() as session:
+ await upsert_page(
+ session,
+ page_id=_PAGE_ID,
+ repository_id=repo_id,
+ page_type="file_page",
+ title="app.py",
+ content="Body.",
+ target_path="src/app.py",
+ source_hash="h" * 64,
+ model_name="mock",
+ provider_name="mock",
+ parent_page_id="module_page:src",
+ display_order=2,
+ section_number="1.3",
+ structural_key="grp-0123456789ab",
+ )
+ await session.commit()
+
+ async with sf() as session:
+ page = await get_page(session, _PAGE_ID)
+
+ assert page.parent_page_id == "module_page:src"
+ assert page.display_order == 2
+ assert page.section_number == "1.3"
+ assert page.structural_key == "grp-0123456789ab"
+
+
+async def test_reconciler_is_idempotent(legacy_store):
+ """Every CLI command calls init_db, so it runs constantly."""
+ engine, _ = legacy_store
+ await init_db(engine)
+ await init_db(engine)
+ assert set(_HIERARCHY_COLUMNS) <= await _columns(engine)
diff --git a/tests/unit/persistence/test_page_tree_sync.py b/tests/unit/persistence/test_page_tree_sync.py
new file mode 100644
index 000000000..14eba235f
--- /dev/null
+++ b/tests/unit/persistence/test_page_tree_sync.py
@@ -0,0 +1,202 @@
+"""Rebuilding the stored tree, which is what keeps updates from flattening it.
+
+An incremental update regenerates a handful of pages and persists them. Those
+pages carry whatever placement the generator could work out from the few pages
+it had in hand, which is not the tree. The rebuild recomputes placement from
+the complete row set afterwards, so an update leaves the tree correct rather
+than a little flatter each time.
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+from sqlalchemy import select
+
+from repowise.core.persistence.crud import upsert_page
+from repowise.core.persistence.models import Page
+from repowise.core.pipeline.page_tree_sync import rebuild_page_tree
+from tests.unit.persistence.helpers import insert_repo
+
+
+async def _add(session, repo_id, page_type, target, **metadata):
+ await upsert_page(
+ session,
+ page_id=f"{page_type}:{target}",
+ repository_id=repo_id,
+ page_type=page_type,
+ title=target,
+ content=f"body of {target}",
+ target_path=target,
+ source_hash="h" * 64,
+ model_name="m",
+ provider_name="template",
+ metadata=metadata or {},
+ )
+
+
+async def _placement(session, repo_id):
+ rows = await session.execute(
+ select(Page.id, Page.parent_page_id, Page.display_order, Page.section_number).where(
+ Page.repository_id == repo_id
+ )
+ )
+ return {pid: (parent, order, section) for pid, parent, order, section in rows.tuples().all()}
+
+
+async def wiki(async_session):
+ """A small persisted wiki: overview, one layer, one module, two files."""
+ repo = await insert_repo(async_session)
+ rid = repo.id
+ # Two layers, spine ordered opposite to the alphabet, so reading the
+ # spine off the stored overview is distinguishable from not reading it.
+ await _add(
+ async_session,
+ rid,
+ "repo_overview",
+ "demo",
+ layer_order_ids=["layer:service", "layer:api"],
+ )
+ await _add(async_session, rid, "layer_page", "layer:service")
+ await _add(async_session, rid, "layer_page", "layer:api")
+ await _add(
+ async_session,
+ rid,
+ "module_page",
+ "src/ingest",
+ file_paths=["src/ingest/a.py", "src/ingest/b.py"],
+ )
+ await _add(async_session, rid, "file_page", "src/ingest/a.py", layer_id="layer:service")
+ await _add(async_session, rid, "file_page", "src/ingest/b.py", layer_id="layer:service")
+ await async_session.commit()
+ await rebuild_page_tree(async_session, rid)
+ await async_session.commit()
+ return rid
+
+
+class TestRebuild:
+ async def test_it_places_pages(self, async_session, wiki):
+ placed = await _placement(async_session, wiki)
+ assert placed["file_page:src/ingest/a.py"][0] == "module_page:src/ingest"
+ assert placed["module_page:src/ingest"][0] == "layer_page:layer:service"
+ assert placed["layer_page:layer:service"][0] == "repo_overview:demo"
+ assert placed["repo_overview:demo"][0] is None
+
+ async def test_it_reads_the_layer_spine_off_the_stored_overview(self, async_session, wiki):
+ """`layer:api` sorts first alphabetically; the stored spine puts
+ `layer:service` first, so this fails if the spine is not read."""
+ placed = await _placement(async_session, wiki)
+ assert placed["layer_page:layer:service"][1] < placed["layer_page:layer:api"][1]
+
+ async def test_a_second_rebuild_changes_nothing(self, async_session, wiki):
+ before = await _placement(async_session, wiki)
+ changed = await rebuild_page_tree(async_session, wiki)
+ await async_session.commit()
+ assert changed == 0
+ assert await _placement(async_session, wiki) == before
+
+
+class TestUpdateDoesNotFlattenTheTree:
+ async def test_re_upserting_one_page_with_no_placement_is_repaired(
+ self, async_session, wiki
+ ):
+ """The exact incremental-update shape: one regenerated page arrives
+ carrying the placement a partial set could work out, which is none."""
+ before = await _placement(async_session, wiki)
+
+ await _add(async_session, wiki, "file_page", "src/ingest/a.py", layer_id="layer:service")
+ await async_session.commit()
+ flattened = await _placement(async_session, wiki)
+ assert flattened["file_page:src/ingest/a.py"][0] is None, "precondition"
+
+ await rebuild_page_tree(async_session, wiki)
+ await async_session.commit()
+ assert await _placement(async_session, wiki) == before
+
+
+class TestAddRemoveRename:
+ async def test_an_added_file_joins_the_tree(self, async_session, wiki):
+ await _add(async_session, wiki, "file_page", "src/ingest/c.py", layer_id="layer:service")
+ await async_session.commit()
+ await rebuild_page_tree(async_session, wiki)
+ await async_session.commit()
+
+ placed = await _placement(async_session, wiki)
+ assert placed["file_page:src/ingest/c.py"][0] == "module_page:src/ingest"
+
+ async def test_siblings_renumber_without_gaps_after_an_add(self, async_session, wiki):
+ await _add(async_session, wiki, "file_page", "src/ingest/c.py", layer_id="layer:service")
+ await async_session.commit()
+ await rebuild_page_tree(async_session, wiki)
+ await async_session.commit()
+
+ placed = await _placement(async_session, wiki)
+ orders = sorted(
+ order
+ for pid, (parent, order, _) in placed.items()
+ if parent == "module_page:src/ingest"
+ )
+ assert orders == [1, 2, 3]
+
+ async def test_a_tombstoned_page_leaves_the_tree(self, async_session, wiki):
+ """A deleted file must not keep showing up in the navigation."""
+ page = await async_session.get(Page, "file_page:src/ingest/b.py")
+ page.freshness_status = "tombstone"
+ page.metadata_json = json.dumps({"successor_paths": []})
+ await async_session.commit()
+
+ await rebuild_page_tree(async_session, wiki)
+ await async_session.commit()
+
+ placed = await _placement(async_session, wiki)
+ assert placed["file_page:src/ingest/b.py"] == (None, 0, None)
+ # And the surviving sibling closes the gap.
+ assert placed["file_page:src/ingest/a.py"][1] == 1
+
+ async def test_a_rename_moves_the_page_and_leaves_no_orphan(self, async_session, wiki):
+ """A rename reaches the tree as a tombstone plus a new page.
+
+ There is no continuity between them: the rebuild reads freshness, not
+ successor_paths, so the old page is simply unplaced and the new one is
+ placed on its own merits. That is what this pins.
+ """
+ old = await async_session.get(Page, "file_page:src/ingest/b.py")
+ old.freshness_status = "tombstone"
+ old.metadata_json = json.dumps({"successor_paths": ["src/web/b.py"]})
+ await _add(async_session, wiki, "module_page", "src/web", file_paths=["src/web/b.py"])
+ await _add(async_session, wiki, "file_page", "src/web/b.py", layer_id="layer:service")
+ await async_session.commit()
+
+ await rebuild_page_tree(async_session, wiki)
+ await async_session.commit()
+
+ placed = await _placement(async_session, wiki)
+ assert placed["file_page:src/web/b.py"][0] == "module_page:src/web"
+ assert placed["file_page:src/ingest/b.py"] == (None, 0, None)
+
+ async def test_no_dangling_parents_after_the_churn(self, async_session, wiki):
+ await _add(async_session, wiki, "file_page", "src/ingest/c.py", layer_id="layer:service")
+ await async_session.commit()
+ await rebuild_page_tree(async_session, wiki)
+ await async_session.commit()
+
+ placed = await _placement(async_session, wiki)
+ known = set(placed)
+ assert [
+ (pid, parent) for pid, (parent, _, _) in placed.items() if parent and parent not in known
+ ] == []
+
+ async def test_removing_the_module_reparents_its_files(self, async_session, wiki):
+ """The sweep deletes module pages whose key moved. Their files must
+ find a new home rather than point at a row that is gone."""
+ module = await async_session.get(Page, "module_page:src/ingest")
+ await async_session.delete(module)
+ await async_session.commit()
+
+ await rebuild_page_tree(async_session, wiki)
+ await async_session.commit()
+
+ placed = await _placement(async_session, wiki)
+ assert placed["file_page:src/ingest/a.py"][0] == "layer_page:layer:service"
diff --git a/tests/unit/persistence/test_page_tree_wiring.py b/tests/unit/persistence/test_page_tree_wiring.py
new file mode 100644
index 000000000..4dfe29d4b
--- /dev/null
+++ b/tests/unit/persistence/test_page_tree_wiring.py
@@ -0,0 +1,48 @@
+"""Every path that writes pages must rebuild the tree afterwards.
+
+Placement cannot be worked out by a run that holds part of the wiki, so it is
+recomputed from the store after persisting. That only holds if every persist
+path actually does it, and a missing call site is invisible: the pages are
+written, nothing raises, and the tree quietly loses the rows that run touched.
+
+Two call sites were missing when this was first written, and both were found
+by reading rather than by a failing test, because nothing asserted the wiring.
+This does.
+
+A source-level check is a blunt instrument. It is used here because the
+alternative is constructing a full pipeline result per path, and because the
+failure being prevented is precisely "somebody added a persist path and did
+not know about this rule" rather than anything about runtime behaviour.
+"""
+
+from __future__ import annotations
+
+import inspect
+
+import pytest
+
+_PERSIST_PATHS = [
+ ("repowise.core.pipeline.persist", "the full index"),
+ ("repowise.core.pipeline.incremental", "the incremental index"),
+ ("repowise.core.pipeline.scoped_generation", "a scoped regeneration"),
+ ("repowise.cli.commands.update_cmd.persistence", "the docs update"),
+ ("repowise.cli.commands.update_cmd.deterministic", "the template update"),
+ ("repowise.cli.commands.upgrade_flow", "the fast-to-full upgrade"),
+]
+
+
[email protected]("module_name,description", _PERSIST_PATHS)
+def test_persist_path_rebuilds_the_tree(module_name: str, description: str):
+ module = __import__(module_name, fromlist=["*"])
+ source = inspect.getsource(module)
+ # The call, not the name: an import line alone would satisfy a bare
+ # substring check and did, the first time this was written.
+ assert "rebuild_page_tree(" in source, (
+ f"{description} ({module_name}) writes pages without rebuilding the tree, "
+ "so the pages it touches lose their place"
+ )
+
+
+def test_the_writer_list_is_not_silently_empty():
+ """Guards the parametrisation itself."""
+ assert len(_PERSIST_PATHS) >= 6
diff --git a/tests/unit/persistence/test_page_upsert_refresh.py b/tests/unit/persistence/test_page_upsert_refresh.py
new file mode 100644
index 000000000..cf8cc51b8
--- /dev/null
+++ b/tests/unit/persistence/test_page_upsert_refresh.py
@@ -0,0 +1,160 @@
+"""Fields that must survive the idempotent-touch branch of a page upsert.
+
+``_apply_page_upsert`` has three branches: insert, archive-then-update, and an
+idempotent touch taken when content, prompt hash and model are all unchanged.
+The touch branch deliberately refreshes only a few cheap fields so that
+re-running a generation does not spawn a version snapshot per page.
+
+That is right for content, and wrong for anything that describes where a page
+sits rather than what it says. A page's display name and its position in the
+tree are derived from the repo's structure, not from its own bytes: adding a
+sibling file renumbers a page whose content did not change by a character. Such
+a page takes the touch branch, so any field the branch does not assign is
+frozen at whatever the first run wrote.
+
+These tests pin the fields that must not freeze.
+"""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.persistence.crud import get_page, upsert_page
+from tests.unit.persistence.helpers import insert_repo
+
+_COMMON = {
+ "page_type": "module_page",
+ "content": "Body that does not change.",
+ "target_path": "packages/core/ingestion",
+ "source_hash": "h" * 64,
+ "model_name": "mock",
+ "provider_name": "mock",
+}
+
+_PAGE_ID = "module_page:packages/core/ingestion"
+
+
+async def _upsert(session, **overrides):
+ await upsert_page(
+ session,
+ page_id=_PAGE_ID,
+ repository_id=overrides.pop("repository_id"),
+ **{**_COMMON, **overrides},
+ )
+
+
+async def repo_id(async_session):
+ repo = await insert_repo(async_session)
+ return repo.id
+
+
+async def test_the_second_upsert_really_takes_the_touch_branch(async_session, repo_id):
+ """Guards the rest of the file: if the branch changed, these stop testing it."""
+ await _upsert(async_session, repository_id=repo_id, title="Ingestion Pipeline")
+ await async_session.commit()
+ await _upsert(async_session, repository_id=repo_id, title="Code Ingestion")
+ await async_session.commit()
+
+ page = await get_page(async_session, _PAGE_ID)
+ # No version bump and no snapshot means the touch branch ran, not the
+ # archive-then-update branch.
+ assert page.version == 1
+
+
+async def test_title_is_refreshed_when_only_the_title_changed(async_session, repo_id):
+ """A rename must land.
+
+ Page identity is anchored to structure so that renaming is free and
+ non-destructive. That only holds if the new name is actually stored: a
+ concept page keyed on its members can be re-titled while its body is
+ byte-identical, and before this was fixed the store kept the first title
+ forever.
+ """
+ await _upsert(async_session, repository_id=repo_id, title="Ingestion Pipeline")
+ await async_session.commit()
+ await _upsert(async_session, repository_id=repo_id, title="Code Ingestion")
+ await async_session.commit()
+
+ page = await get_page(async_session, _PAGE_ID)
+ assert page.title == "Code Ingestion"
+
+
+async def test_repeated_upsert_of_an_unchanged_page_is_still_a_no_op(async_session, repo_id):
+ """The reason the touch branch exists must survive the fix."""
+ await _upsert(async_session, repository_id=repo_id, title="Ingestion Pipeline")
+ await async_session.commit()
+ await _upsert(async_session, repository_id=repo_id, title="Ingestion Pipeline")
+ await async_session.commit()
+
+ page = await get_page(async_session, _PAGE_ID)
+ assert page.version == 1
+ assert page.title == "Ingestion Pipeline"
+
+
+async def test_hierarchy_fields_are_refreshed_when_only_they_changed(async_session, repo_id):
+ """Where a page sits can change while what it says does not.
+
+ Adding a sibling renumbers this page without touching a byte of its
+ content, so the update arrives on the touch branch. A hierarchy field the
+ branch does not assign would stay at the first run's value and the tree
+ would quietly describe a repo that no longer exists.
+ """
+ await _upsert(
+ async_session,
+ repository_id=repo_id,
+ title="Ingestion Pipeline",
+ parent_page_id="layer_page:layer:service",
+ display_order=3,
+ section_number="2.1",
+ structural_key="grp-aaaaaaaaaaaa",
+ )
+ await async_session.commit()
+ await _upsert(
+ async_session,
+ repository_id=repo_id,
+ title="Ingestion Pipeline",
+ parent_page_id="layer_page:layer:ingest",
+ display_order=5,
+ section_number="3.2.1",
+ structural_key="grp-bbbbbbbbbbbb",
+ )
+ await async_session.commit()
+
+ page = await get_page(async_session, _PAGE_ID)
+ assert page.version == 1, "must have taken the touch branch"
+ assert page.parent_page_id == "layer_page:layer:ingest"
+ assert page.display_order == 5
+ assert page.section_number == "3.2.1"
+ assert page.structural_key == "grp-bbbbbbbbbbbb"
+
+
+async def test_hierarchy_fields_default_for_a_page_that_has_no_place_yet(
+ async_session, repo_id
+):
+ """Every existing page predates these columns, so the unset case is normal."""
+ await _upsert(async_session, repository_id=repo_id, title="Ingestion Pipeline")
+ await async_session.commit()
+
+ page = await get_page(async_session, _PAGE_ID)
+ assert page.parent_page_id is None
+ assert page.section_number is None
+ assert page.structural_key is None
+ assert page.display_order == 0
+
+
+async def test_content_change_still_archives_a_version(async_session, repo_id):
+ """The touch branch must not swallow a real edit."""
+ await _upsert(async_session, repository_id=repo_id, title="Ingestion Pipeline")
+ await async_session.commit()
+ await _upsert(
+ async_session,
+ repository_id=repo_id,
+ title="Ingestion Pipeline",
+ content="A different body.",
+ )
+ await async_session.commit()
+
+ page = await get_page(async_session, _PAGE_ID)
+ assert page.version == 2
+ assert page.content == "A different body."