Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(onboarding): orientation is six pages, and the cut reaches indexes already built (#1285)
Raghav Chamadiya287393dc9cba
diff --git a/docs/reference/CONFIG.md b/docs/reference/CONFIG.mdindex 15ae425ce..201642d37 100644--- a/docs/reference/CONFIG.md+++ b/docs/reference/CONFIG.md@@ -116,15 +116,20 @@ entries, no configured files are added; `onboarding/how_it_works` can still addexact excerpts automatically for symbols in its detected flows. The defaultshared `token_budget` is `8000`.-Keys name model-written synthesis pages: `repo_overview` or-`onboarding/<slot>` for `guided_tour`, `getting_started`, `codebase_map`,-`key_concepts`, `how_it_works`, `development_guide`, and `active_landscape`.+Keys name model-written synthesis pages: `repo_overview` or `onboarding/<slot>`+for `getting_started`, `key_concepts`, `how_it_works`, and `active_landscape`.`onboarding/project_overview` is invalid because that promoted slot is the`repo_overview` page. `onboarding/glossary` is accepted but has no effect: thatpage is rendered from mined vocabulary alone, with no model in its path, sothere is no prompt for extra evidence to reach. Unknown keys and malformedvalues fail generation with a configuration error instead of being ignored.+`onboarding/guided_tour`, `onboarding/codebase_map` and+`onboarding/development_guide` named pages that have since been retired. A+config still carrying one is accepted and the entry is ignored, with a warning+naming the key — an upgrade must not turn a previously valid config into a+failed generation. Remove the entry to silence it.+Each value is an ordered list of repository-relative paths. A file is eligibleonly when it was included in the indexed source map and contains non-emptyUTF-8 text. Absolute and parent-traversing paths, duplicate entries, missing ordiff --git a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.pyindex f043e7067..e68ca6b42 100644--- a/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py+++ b/packages/cli/src/repowise/cli/commands/update_cmd/persistence.py@@ -451,6 +451,8 @@ async def _persist_full_update_async(# Filled by the tombstone step; read by the full-text block after the# session closes, so it has to survive a step that was skipped.tombstoned_page_ids: list[str] = []+ # Same contract, for rows of a page that has been retired outright.+ swept_page_ids: list[str] = []try:await init_db(engine)sf = create_session_factory(engine)@@ -465,6 +467,29 @@ async def _persist_full_update_async(# streamed each page per-commit for durability.await upsert_pages_from_generated(session, generated_pages, repo_id)+ # Delete rows of pages that have been retired since this index was+ # built. Nothing else on the update path can reach them: an update+ # runs with ``file_pages_only``, so the ladder returns before the+ # repo-wide levels and never visits an onboarding row to notice it+ # should not exist. Without this the retirement reaches only users+ # who re-index, and everyone else keeps being served a page the+ # product no longer has.+ try:+ from repowise.core.pipeline.persist import sweep_retired_pages++ swept_page_ids = await sweep_retired_pages(session, repo_id)++ # Drop the embeddings before the SQL session commits, the same+ # ordering ``init`` uses: the vector store is a separate engine,+ # so there is no write-lock conflict, the delete is idempotent,+ # and an interrupted run self-heals forwards rather than leaving+ # an embedding whose page is gone. ``decision_vector_store`` is+ # the shared page/decision store despite the name.+ if swept_page_ids and decision_vector_store is not None:+ await decision_vector_store.delete_many(swept_page_ids)+ except Exception as exc:+ _skip("Retired page sweep", exc)+# Tombstone pages for deleted/renamed files — regeneration only# rewrites pages for files that still exist.try:@@ -761,6 +786,12 @@ async def _persist_full_update_async(# slot.if tombstoned_page_ids:await fts.delete_many(tombstoned_page_ids)+ # A swept page's FTS row outlives the page row unless it is deleted+ # here, and search hydrates title and snippet from the FTS copy+ # itself — so an orphan keeps answering queries in full, pointing+ # at a page that now 404s. Worse than never having swept it.+ if swept_page_ids:+ await fts.delete_many(swept_page_ids)except Exception as exc:_skip("Full-text search indexing", exc)return total_pagesdiff --git a/packages/core/src/repowise/core/generation/models.py b/packages/core/src/repowise/core/generation/models.pyindex 7317ca6fb..8931302e3 100644--- a/packages/core/src/repowise/core/generation/models.py+++ b/packages/core/src/repowise/core/generation/models.py@@ -17,8 +17,12 @@ from datetime import UTC, datetimefrom types import MappingProxyTypefrom typing import Any, Literal+import structlog+from repowise.core.reasoning import ReasoningMode, normalize_reasoning+logger = structlog.get_logger(__name__)+# ---------------------------------------------------------------------------# PageType and generation levels# ---------------------------------------------------------------------------@@ -68,6 +72,23 @@ def _source_evidence_page_keys() -> set[str]:}+def _retired_page_keys() -> set[str]:+ """Config keys that named a page which has since been retired.++ A key here was valid in a release the user has already run, so it cannot be+ treated as a typo: raising would turn an upgrade into a failed generation+ for a config that was correct when it was written. Derived from the+ retirement table rather than listed again, so a slot cannot be retired+ without this following.++ An onboarding page's config key is its ``target_path``, which is the half+ of the page id after the type.+ """+ from .page_redirects import RETIRED_IDS++ return {page_id.split(":", 1)[1] for page_id in RETIRED_IDS if page_id.startswith("onboarding:")}++def _normalize_evidence_files(raw_files: Mapping[str, Any], *, label: str) -> dict[str, tuple[str, ...]]:@@ -83,11 +104,26 @@ def _normalize_evidence_files(``str(...).strip()`` a key before the membership check. ``from_repo_config``always did; direct construction did not, so a padded key like``" repo_overview "`` is now trimmed and accepted where it used to raise.++ A key naming a *retired* page is dropped with a warning rather than raised+ on. The strictness here is aimed at a typo, which is only ever a mistake;+ a retired key is a config that was correct when it was written, and an+ upgrade that turns it into a failed generation punishes the user for a+ decision this project made."""valid_page_keys = _source_evidence_page_keys()+ retired_page_keys = _retired_page_keys()result: dict[str, tuple[str, ...]] = {}for raw_page_key, raw_paths in raw_files.items():page_key = str(raw_page_key).strip()+ if page_key in retired_page_keys:+ logger.warning(+ "generation_context_key_retired",+ label=label,+ page_key=page_key,+ detail="page has been retired; the entry is ignored, remove it to silence this",+ )+ continueif page_key not in valid_page_keys:raise ValueError(f"{label} keys must name repo_overview or a "diff --git a/packages/core/src/repowise/core/generation/onboarding/__init__.py b/packages/core/src/repowise/core/generation/onboarding/__init__.pyindex 44dc19950..c855aa716 100644--- a/packages/core/src/repowise/core/generation/onboarding/__init__.py+++ b/packages/core/src/repowise/core/generation/onboarding/__init__.py@@ -1,13 +1,12 @@"""Onboarding documentation collection.-A curated set of up to nine pages: Project Overview, Guided Tour, Getting-Started, Codebase Map, Key Concepts, How It Works, Development Guide, Active-Landscape and Glossary, designed to be the first thing a new contributor (or-LLM agent) reads.+A curated set of up to six pages: Project Overview, Getting Started, Key+Concepts, How It Works, Active Landscape and Glossary, designed to be the first+thing a new contributor (or LLM agent) reads.One slot ("project_overview") is *promoted*: it reuses the existing``repo_overview`` page, tagged via ``metadata.onboarding_slot``. The other-eight slots are new pages generated at level 8 with ``page_type='onboarding'``+five slots are new pages generated at level 8 with ``page_type='onboarding'``and a ``metadata.subkind`` discriminator.Architecture:@@ -27,11 +26,8 @@ from .slots import (ONBOARDING_ORDER,PROMOTED_SLOTS,SLOT_ACTIVE_LANDSCAPE,- SLOT_CODEBASE_MAP,- SLOT_DEVELOPMENT_GUIDE,SLOT_GETTING_STARTED,SLOT_GLOSSARY,- SLOT_GUIDED_TOUR,SLOT_HOW_IT_WORKS,SLOT_KEY_CONCEPTS,SLOT_PROJECT_OVERVIEW,@@ -44,11 +40,8 @@ __all__ = ["ONBOARDING_ORDER","PROMOTED_SLOTS","SLOT_ACTIVE_LANDSCAPE",- "SLOT_CODEBASE_MAP",- "SLOT_DEVELOPMENT_GUIDE","SLOT_GETTING_STARTED","SLOT_GLOSSARY",- "SLOT_GUIDED_TOUR","SLOT_HOW_IT_WORKS","SLOT_KEY_CONCEPTS","SLOT_PROJECT_OVERVIEW",diff --git a/packages/core/src/repowise/core/generation/onboarding/slots.py b/packages/core/src/repowise/core/generation/onboarding/slots.pyindex 157da656f..34becf6ef 100644--- a/packages/core/src/repowise/core/generation/onboarding/slots.py+++ b/packages/core/src/repowise/core/generation/onboarding/slots.py@@ -1,8 +1,8 @@"""Onboarding slot identifiers and reading order.-The Onboarding collection is a fixed set of nine curated slots. One slot is+The Onboarding collection is a fixed set of six curated slots. One slot is"promoted": it reuses the existing `repo_overview` page, tagged via-``metadata.onboarding_slot``. The other eight are new pages with+``metadata.onboarding_slot``. The other five are new pages with``page_type='onboarding'`` and a ``metadata.subkind`` discriminator.Slot identifiers are used three ways:@@ -10,9 +10,21 @@ Slot identifiers are used three ways:- as the trailing path of ``target_path = f"onboarding/{slot}"``,- as the ordering key in the web UI's Onboarding folder.-Keep the order list in lockstep with ``packages/ui/src/lib/page-types.ts``-``ONBOARDING_ORDER``. A slot without enough signal is skipped at generation-time, so a repo can end up with fewer than eight.+Every slot here must also appear in ``ONBOARDING_SLOT_TITLES`` in+``packages/ui/src/lib/page-types.ts``: that map gates whether a page is placed+in the Onboarding folder at all, and a slot missing from it falls through to+path-based grouping and surfaces as a stray ``onboarding/`` directory. The+reading *order* is not duplicated there — it arrives on the pages themselves as+``display_order``, assigned from this tuple at generation time.++A slot without enough signal is skipped at generation time, so a repo can end+up with fewer than five.++Retiring a slot is not just a deletion here. The pages already written into+every existing index have to be retired too, or they keep being served: see+``generation.page_redirects`` for where their ids now send a reader, and+``pipeline.persist.sweep_retired_pages`` for how the rows leave a store+that was built before the cut."""from __future__ import annotations@@ -28,12 +40,9 @@ ONBOARDING_GENERATION_VERSION = "3"# ---- Slot identifiers ----SLOT_PROJECT_OVERVIEW = "project_overview"-SLOT_GUIDED_TOUR = "guided_tour"SLOT_GETTING_STARTED = "getting_started"-SLOT_CODEBASE_MAP = "codebase_map"SLOT_KEY_CONCEPTS = "key_concepts"SLOT_HOW_IT_WORKS = "how_it_works"-SLOT_DEVELOPMENT_GUIDE = "development_guide"SLOT_ACTIVE_LANDSCAPE = "active_landscape"SLOT_GLOSSARY = "glossary"@@ -45,12 +54,9 @@ SLOT_GLOSSARY = "glossary"# meeting all of it at once.ONBOARDING_ORDER: tuple[str, ...] = (SLOT_PROJECT_OVERVIEW,- SLOT_GUIDED_TOUR,SLOT_GETTING_STARTED,- SLOT_CODEBASE_MAP,SLOT_KEY_CONCEPTS,SLOT_HOW_IT_WORKS,- SLOT_DEVELOPMENT_GUIDE,SLOT_ACTIVE_LANDSCAPE,SLOT_GLOSSARY,)@@ -66,12 +72,9 @@ PROMOTED_SLOTS: dict[str, str] = {# label in the UI when a page hasn't been hydrated yet.SLOT_TITLES: dict[str, str] = {SLOT_PROJECT_OVERVIEW: "Project Overview",- SLOT_GUIDED_TOUR: "Guided Tour",SLOT_GETTING_STARTED: "Getting Started",- SLOT_CODEBASE_MAP: "Codebase Map",SLOT_KEY_CONCEPTS: "Key Concepts",SLOT_HOW_IT_WORKS: "How It Works",- SLOT_DEVELOPMENT_GUIDE: "Development Guide",SLOT_ACTIVE_LANDSCAPE: "Active Landscape",SLOT_GLOSSARY: "Glossary",}diff --git a/packages/core/src/repowise/core/generation/onboarding/subkinds/__init__.py b/packages/core/src/repowise/core/generation/onboarding/subkinds/__init__.pyindex b51f43978..a5e1af366 100644--- a/packages/core/src/repowise/core/generation/onboarding/subkinds/__init__.py+++ b/packages/core/src/repowise/core/generation/onboarding/subkinds/__init__.py@@ -11,11 +11,8 @@ re-orders to ``ONBOARDING_ORDER`` for iteration.# Side-effect imports — each module calls register() at import time.from . import (active_landscape, # noqa: F401- codebase_map, # noqa: F401- development_guide, # noqa: F401getting_started, # noqa: F401glossary, # noqa: F401- guided_tour, # noqa: F401how_it_works, # noqa: F401key_concepts, # noqa: F401)diff --git a/packages/core/src/repowise/core/generation/onboarding/subkinds/codebase_map.py b/packages/core/src/repowise/core/generation/onboarding/subkinds/codebase_map.pydeleted file mode 100644index 9e740254b..000000000--- a/packages/core/src/repowise/core/generation/onboarding/subkinds/codebase_map.py+++ /dev/null@@ -1,145 +0,0 @@-"""Onboarding subkind: Codebase Map.--The wayfinding page — where things physically live. Different from the-Architecture Guide (which is conceptual) because this is spatial: it-walks the file tree top-down and tells the reader "if you're looking-for X, go to Y."--Gate: always generates. Every repo has a directory structure.-"""--from __future__ import annotations--from collections import Counter, defaultdict-from dataclasses import dataclass, field-from pathlib import PurePosixPath--from ..registry import SubkindSpec, register-from ..signals import OnboardingSignals-from ..slots import SLOT_CODEBASE_MAP, SLOT_TITLES--# Tunables — kept inline because they're specific to this subkind only.-_MIN_FILES_PER_DIR = 3-_TOP_FILES_PER_DIR = 5-_MAX_DIRS = 18-_MAX_COMMUNITY_LABELS_PER_DIR = 3---@dataclass-class DirectorySummary:- """One top-level directory's snapshot in the Codebase Map."""-- path: str- file_count: int- dominant_language: str- entry_points: list[str] = field(default_factory=list)- top_files: list[str] = field(default_factory=list)- community_labels: list[str] = field(default_factory=list)---@dataclass-class CodebaseMapContext:- repo_name: str- total_files: int- total_loc: int- directories: list[DirectorySummary] = field(default_factory=list)- # Repo-wide entry points hoisted to a dedicated section.- entry_points: list[str] = field(default_factory=list)- kg_layers: list[dict] = field(default_factory=list)- # Layers ordered top→bottom by dependency direction (the grouping spine).- layer_order: list[str] = field(default_factory=list)---def _top_level_dir(path: str) -> str:- """Return the first path segment, or "(root)" for top-level files."""- parts = PurePosixPath(path).parts- return parts[0] if len(parts) > 1 else "(root)"---def _build(signals: OnboardingSignals) -> CodebaseMapContext | None:- """Codebase Map always builds — there's no gate."""- # Group parsed files by top-level directory.- by_dir: dict[str, list] = defaultdict(list)- for pf in signals.parsed_files:- by_dir[_top_level_dir(pf.file_info.path)].append(pf)-- # Resolve community labels once, then map path → label.- label_by_cid: dict[int, str] = {}- try:- info = signals.graph_builder.community_info() or {}- for cid, ci in info.items() if hasattr(info, "items") else ():- label = getattr(ci, "label", "") or ""- if label:- label_by_cid[int(cid)] = label- except Exception:- # community_info is best-effort enrichment; the page renders fine- # without it.- pass-- directories: list[DirectorySummary] = []- for dir_name, files in by_dir.items():- if len(files) < _MIN_FILES_PER_DIR and dir_name != "(root)":- continue-- # Dominant language: most-common language by file count.- lang_counts: Counter[str] = Counter(f.file_info.language for f in files)- dominant_language = lang_counts.most_common(1)[0][0] if lang_counts else "unknown"-- # Entry points within the directory (cap at 3 — overflow goes in the- # full top_files list).- entry_points = sorted(- f.file_info.path for f in files if f.file_info.is_entry_point- )[:3]-- # Top files by PageRank within the directory (skip generated/clones).- ranked = sorted(- ((signals.pagerank.get(f.file_info.path, 0.0), f.file_info.path) for f in files),- reverse=True,- )- top_files = [path for _, path in ranked[:_TOP_FILES_PER_DIR]]-- # Distinct community labels touching files in this dir.- cids_here = {- signals.community.get(f.file_info.path)- for f in files- if signals.community.get(f.file_info.path) is not None- }- labels = sorted(- {label_by_cid[cid] for cid in cids_here if cid in label_by_cid}- )[:_MAX_COMMUNITY_LABELS_PER_DIR]-- directories.append(- DirectorySummary(- path=dir_name,- file_count=len(files),- dominant_language=dominant_language,- entry_points=entry_points,- top_files=top_files,- community_labels=labels,- )- )-- # Largest directories first — the reader sees the load-bearing dirs- # before utility ones.- directories.sort(key=lambda d: d.file_count, reverse=True)- directories = directories[:_MAX_DIRS]-- return CodebaseMapContext(- repo_name=signals.repo_name,- total_files=getattr(signals.repo_structure, "total_files", len(signals.parsed_files)),- total_loc=getattr(signals.repo_structure, "total_loc", 0),- directories=directories,- entry_points=list(getattr(signals.repo_structure, "entry_points", []))[:10],- kg_layers=list(signals.kg_layers) if signals.kg_layers else [],- layer_order=list(signals.layer_order),- )---register(- SubkindSpec(- slot=SLOT_CODEBASE_MAP,- title=SLOT_TITLES[SLOT_CODEBASE_MAP],- template="codebase_map.j2",- build_context=_build,- )-)diff --git a/packages/core/src/repowise/core/generation/onboarding/subkinds/development_guide.py b/packages/core/src/repowise/core/generation/onboarding/subkinds/development_guide.pydeleted file mode 100644index e883c9b3c..000000000--- a/packages/core/src/repowise/core/generation/onboarding/subkinds/development_guide.py+++ /dev/null@@ -1,220 +0,0 @@-"""Onboarding subkind: Development Guide.--How to do common things in this codebase — add a feature, write a test,-follow naming conventions — derived from structural repetition that's-already visible in the file tree.--Gate: at least 2 detectable repeated patterns (e.g., a strong "test-mirror" plus a recurring filename suffix, or two distinct filename-suffix groups). Without that signal, the guide would be inventing-conventions rather than reporting them.-"""--from __future__ import annotations--import re-from collections import defaultdict-from dataclasses import dataclass, field-from pathlib import PurePosixPath--from ..registry import SubkindSpec, register-from ..signals import OnboardingSignals-from ..slots import SLOT_DEVELOPMENT_GUIDE, SLOT_TITLES--_GATE_MIN_SIGNALS = 2-_MIN_SUFFIX_GROUP = 3-_TOP_SUFFIX_GROUPS = 6-_MIN_TEST_MIRROR_RATIO = 0.5---@dataclass-class SuffixPattern:- """A repeating filename suffix — e.g. `_handler.py` x 7."""-- suffix: str- examples: list[str] = field(default_factory=list)- file_count: int = 0---@dataclass-class TestMirror:- test_root: str- matched_files: int- source_files: int---@dataclass-class DevelopmentGuideContext:- repo_name: str- suffix_patterns: list[SuffixPattern] = field(default_factory=list)- test_mirror: TestMirror | None = None- parallel_dirs: list[str] = field(default_factory=list)- entry_points: list[str] = field(default_factory=list)---def _split_basename(name: str) -> list[str]:- """Split a basename into trailing tokens for suffix grouping.-- Handles snake_case and camelCase, stripping the file extension.- Example: `UserHandlerService.cs` → ['user', 'handler', 'service']- `api_route_handler.py` → ['api', 'route', 'handler']- """- stem = PurePosixPath(name).stem- # CamelCase → space, then lower + split on underscore/hyphen/space.- spaced = re.sub(r"(?<!^)(?=[A-Z])", " ", stem).lower()- tokens = re.split(r"[\s_\-]+", spaced)- return [t for t in tokens if t]---def _find_suffix_patterns(signals: OnboardingSignals) -> list[SuffixPattern]:- by_suffix: dict[str, list[str]] = defaultdict(list)- for pf in signals.parsed_files:- path = pf.file_info.path- # Skip test files — patterns inside tests/ are the mirror signal,- # not the suffix signal.- if pf.file_info.is_test:- continue- tokens = _split_basename(PurePosixPath(path).name)- if len(tokens) < 2:- continue- suffix = tokens[-1]- # Filter out generic single-letter / stop-word suffixes.- if len(suffix) <= 2 or suffix in {"py", "ts", "js", "cs", "go", "rs"}:- continue- by_suffix[suffix].append(path)-- groups: list[SuffixPattern] = []- for suffix, paths in by_suffix.items():- if len(paths) < _MIN_SUFFIX_GROUP:- continue- groups.append(- SuffixPattern(- suffix=suffix,- file_count=len(paths),- examples=sorted(paths)[:3],- )- )- groups.sort(key=lambda g: g.file_count, reverse=True)- return groups[:_TOP_SUFFIX_GROUPS]---def _test_tree_roots(signals: OnboardingSignals) -> list[str]:- """Top-level directories that are test trees, in this repo's own spelling.-- "Which directory is the test root" is a different question from "is this- path a test", so it is derived rather than read off a hardcoded list: group- the ingested files by first path segment and keep the segments where every- ingested file underneath is test material. That all-or-nothing rule is what- separates a real root from a directory that merely contains one — `tests/`- qualifies, `src/` in a `src/test/java` layout does not, and a repo naming- its tree `spec/` or `Foo.Tests/` is found without the list knowing about it.- """- total: dict[str, int] = defaultdict(int)- tests: dict[str, int] = defaultdict(int)- for pf in signals.parsed_files:- parts = PurePosixPath(pf.file_info.path).parts- if len(parts) < 2: # a repo-root file is not a tree- continue- total[parts[0]] += 1- if pf.file_info.is_test:- tests[parts[0]] += 1- return sorted(f"{seg}/" for seg, count in tests.items() if count == total[seg])---def _find_test_mirror(signals: OnboardingSignals) -> TestMirror | None:- """Detect a "tests mirror source layout" convention.-- For every file under a test root, strip the root and try to locate a- non-test file that shares the remaining path stem. A mirror is reported- when ≥ 50% of test files match.- """- source_paths: set[str] = {- pf.file_info.path for pf in signals.parsed_files if not pf.file_info.is_test- }-- best: TestMirror | None = None- for root in _test_tree_roots(signals):- test_files = [pf.file_info.path for pf in signals.parsed_files if pf.file_info.path.startswith(root)]- if len(test_files) < _MIN_SUFFIX_GROUP:- continue- # Strip leading "test_" / "_test" / "spec_" from the basename and- # look for the resulting stem anywhere in the source tree.- matched = 0- for tf in test_files:- stem = PurePosixPath(tf).stem- stem_normalised = re.sub(r"^test_|^spec_|_test$|_spec$", "", stem, flags=re.IGNORECASE)- if not stem_normalised:- continue- if any(stem_normalised in PurePosixPath(p).stem for p in source_paths):- matched += 1- if test_files and matched / len(test_files) >= _MIN_TEST_MIRROR_RATIO:- candidate = TestMirror(- test_root=root.rstrip("/"),- matched_files=matched,- source_files=len(test_files),- )- if best is None or candidate.matched_files > best.matched_files:- best = candidate- return best---def _find_parallel_dirs(signals: OnboardingSignals) -> list[str]:- """Find sibling directories that look structurally parallel.-- A parallel layout shows up when multiple siblings under the same parent- each contain the same set of basenames (e.g. `services/auth/{api.py,- service.py, models.py}` repeated under `services/billing/…`).- """- by_parent: dict[str, dict[str, set[str]]] = defaultdict(lambda: defaultdict(set))- for pf in signals.parsed_files:- parts = PurePosixPath(pf.file_info.path).parts- if len(parts) < 3:- continue- grandparent = parts[-3]- parent = parts[-2]- by_parent[grandparent][parent].add(parts[-1])-- parallel: list[str] = []- for grandparent, siblings in by_parent.items():- if len(siblings) < 3:- continue- # Look for a shared core of basenames across siblings.- all_names: list[set[str]] = list(siblings.values())- if not all_names:- continue- shared = set.intersection(*all_names)- if len(shared) >= 2:- parallel.append(grandparent)- return sorted(parallel)[:5]---def _build(signals: OnboardingSignals) -> DevelopmentGuideContext | None:- suffix_patterns = _find_suffix_patterns(signals)- test_mirror = _find_test_mirror(signals)- parallel_dirs = _find_parallel_dirs(signals)-- signal_count = (- (1 if suffix_patterns else 0)- + (1 if test_mirror else 0)- + (1 if parallel_dirs else 0)- )- if signal_count < _GATE_MIN_SIGNALS:- return None-- return DevelopmentGuideContext(- repo_name=signals.repo_name,- suffix_patterns=suffix_patterns,- test_mirror=test_mirror,- parallel_dirs=parallel_dirs,- entry_points=list(getattr(signals.repo_structure, "entry_points", []))[:5],- )---register(- SubkindSpec(- slot=SLOT_DEVELOPMENT_GUIDE,- title=SLOT_TITLES[SLOT_DEVELOPMENT_GUIDE],- template="development_guide.j2",- build_context=_build,- )-)diff --git a/packages/core/src/repowise/core/generation/onboarding/subkinds/guided_tour.py b/packages/core/src/repowise/core/generation/onboarding/subkinds/guided_tour.pydeleted file mode 100644index 9ffe827f6..000000000--- a/packages/core/src/repowise/core/generation/onboarding/subkinds/guided_tour.py+++ /dev/null@@ -1,82 +0,0 @@-"""Onboarding subkind: Guided Tour.--A single pedagogical page that narrates the topology-driven tour — an ordered-walk that starts at the entry points and follows the import graph inward,-closing on how the system is built and deployed. The *ordering* is computed-deterministically upstream (``generation.tour``) and arrives here as-``signals.tour_stops``; this subkind hands those ordered stops (each already-pointing at a real wiki page, with its one-line summary) to the LLM, which-writes the connective narration that ties one step to the next.--Gate: skips when no tour could be built (e.g. a repo with no documented-files), so the slot simply doesn't appear.-"""--from __future__ import annotations--from dataclasses import dataclass, field--from ..registry import SubkindSpec, register-from ..signals import OnboardingSignals-from ..slots import SLOT_GUIDED_TOUR, SLOT_TITLES--# A tour with only the overview stop isn't worth a page on its own.-_MIN_STOPS = 2---@dataclass-class TourStopContext:- """One stop as the template sees it — ordered page reference + summary."""-- order: int- target_path: str- page_type: str- title: str- kind: str- reason: str- summary: str---@dataclass-class GuidedTourContext:- repo_name: str- stops: list[TourStopContext] = field(default_factory=list)- layer_order: list[str] = field(default_factory=list)---def _build(signals: OnboardingSignals) -> GuidedTourContext | None:- if len(signals.tour_stops) < _MIN_STOPS:- return None-- stops: list[TourStopContext] = []- for s in signals.tour_stops:- target = s.get("target_path", "")- # The overview's summary is keyed by repo_name; file/infra pages by path.- summary = (signals.completed_page_summaries.get(target) or "").strip()[:240]- stops.append(- TourStopContext(- order=int(s.get("order", len(stops) + 1)),- target_path=target,- page_type=s.get("page_type", "file_page"),- title=s.get("title", target),- kind=s.get("kind", "code"),- reason=s.get("reason", ""),- summary=summary,- )- )-- return GuidedTourContext(- repo_name=signals.repo_name,- stops=stops,- layer_order=list(signals.layer_order),- )---register(- SubkindSpec(- slot=SLOT_GUIDED_TOUR,- title=SLOT_TITLES[SLOT_GUIDED_TOUR],- template="guided_tour.j2",- build_context=_build,- )-)diff --git a/packages/core/src/repowise/core/generation/page_redirects.py b/packages/core/src/repowise/core/generation/page_redirects.pyindex ccbbfc3aa..045f40c48 100644--- a/packages/core/src/repowise/core/generation/page_redirects.py+++ b/packages/core/src/repowise/core/generation/page_redirects.py@@ -6,21 +6,31 @@ something. This module owns that mapping and nothing else: it turns a retiredpage id into the id of the page that took over its material.Page ids are ``{page_type}:{target_path}`` (see ``models.compute_page_id``).-Retirements come in three shapes and the tables mirror that:+Retirements come in four shapes and the tables mirror that. Two axes: whether+the rule is keyed by page *type* or by exact *id*, and whether the successor+can be named up front or has to be resolved against the store.* **A whole page type folds into another, keeping its path.** Its target pathis usually the repository name, which differs per repo, so the rule cannot bewritten as a literal id. :data:`SUPERSEDED_TYPES` rewrites the type andcarries the path across unchanged.-* **One page with a fixed target path retires.** The onboarding slots are- ``onboarding/{slot}`` for every repo, so these can be written as exact ids in- :data:`SUPERSEDED_IDS`.-* **A page folds into the repository's single page of some other type.** Here- the retired id carries nothing that identifies the successor — a layer page is- keyed by its layer slug, and the overview by the repository name — so the- successor cannot be named without reading the store.+* **One page with a fixed target path retires into another named page.** The+ onboarding slots are ``onboarding/{slot}`` for every repo, so these can be+ written as exact ids in :data:`SUPERSEDED_IDS`.+* **A page type folds into the repository's single page of some other type.**+ Here the retired id carries nothing that identifies the successor — a layer+ page is keyed by its layer slug, and the overview by the repository name — so+ the successor cannot be named without reading the store.:data:`SUPERSEDED_TO_REPO_WIDE` names the successor *type* and the servinglayer resolves it.+* **One page with a fixed target path folds into a repo-wide page.** Both of+ the above at once, and the shape the retired onboarding slots need: the+ retired id is exact (``onboarding:onboarding/codebase_map`` in every repo)+ but the successor is the overview, whose id carries the repository name.+ Keying these by type is not available — the surviving onboarding pages share+ the type, so a type rule would redirect the whole collection — and+ :data:`SUPERSEDED_IDS` cannot name a per-repo successor.+ :data:`SUPERSEDED_IDS_TO_REPO_WIDE` closes that gap.Retirements chain: a page folded into a second page that later folds into athird must land on the third, not the second, or the redirect leads somewhere@@ -66,6 +76,31 @@ SUPERSEDED_TO_REPO_WIDE: dict[str, str] = {"layer_page": "repo_overview",}+# Retired page id → the page type of the *one* repo-wide page that took over.+#+# The id-keyed twin of the table above, for a page whose id is fixed across+# repositories but whose successor is not. ``repo_wide_successor_type`` checks+# this before the type table, so a single retired id can fold into the overview+# while every other page of its type keeps being served.+SUPERSEDED_IDS_TO_REPO_WIDE: dict[str, str] = {+ # Three orientation pages retired together. The Guided Tour's *data* did+ # not go anywhere — the ordered stops are still computed and still served+ # by ``get_overview`` and Present mode from the overview's own metadata —+ # so the page's material is genuinely on the overview. The Codebase Map+ # described the repository at the overview's altitude in the overview's+ # words. The Development Guide reported filename shapes as if they were+ # procedures, and had no successor worth naming.+ "onboarding:onboarding/guided_tour": "repo_overview",+ "onboarding:onboarding/codebase_map": "repo_overview",+ "onboarding:onboarding/development_guide": "repo_overview",+}++# Every retired id, whichever table names it. The sweep and the config-key+# validator both need "was this an onboarding slot once?" and neither should+# keep its own list: a slot that is redirected but not swept is the exact state+# ``sweep_retired_pages`` exists to clear.+RETIRED_IDS: frozenset[str] = frozenset(SUPERSEDED_IDS) | frozenset(SUPERSEDED_IDS_TO_REPO_WIDE)+# A chain longer than this is a table authoring mistake rather than a real# history — the orientation set has never held more than a handful of pages.# Bounded so a table that somehow evades cycle detection cannot spin forever.@@ -172,8 +207,17 @@ def repo_wide_successor_type(page_id: str) -> str | None:repository, which ``page_id`` does not carry. The caller resolves itagainst the store it is already reading.+ An exact-id rule is more specific than a type-level one and wins, matching+ :func:`_successor`. That ordering is what lets three onboarding slots+ retire into the overview while every other page of type ``onboarding``+ keeps being served as itself.+Raises:SupersededTargetError: ``page_id`` is not ``{page_type}:{target_path}``."""+ exact = SUPERSEDED_IDS_TO_REPO_WIDE.get(page_id)+ if exact is not None:+ return exact+page_type, _ = _split(page_id)return SUPERSEDED_TO_REPO_WIDE.get(page_type)diff --git a/packages/core/src/repowise/core/generation/templates/onboarding/codebase_map.j2 b/packages/core/src/repowise/core/generation/templates/onboarding/codebase_map.j2deleted file mode 100644index a5f8c1c67..000000000--- a/packages/core/src/repowise/core/generation/templates/onboarding/codebase_map.j2+++ /dev/null@@ -1,73 +0,0 @@-You are writing the "Codebase Map" page for the repository `{{ ctx.repo_name }}`.--This is the wayfinding page — where things physically live. The reader has-already read the Architecture Guide (which is conceptual); this page is-spatial. The right tone is: "if you're looking for X, go to Y."--## Repo facts (do not invent beyond these)-- **Total files**: {{ ctx.total_files }}-- **Total lines of code**: {{ ctx.total_loc }}-- **Top-level directories surveyed**: {{ ctx.directories | length }}--{% if ctx.entry_points %}-## Repo-wide entry points-{% for ep in ctx.entry_points %}-- `{{ ep }}`-{% endfor %}-{% endif %}--{% if ctx.layer_order %}-## Architectural layers (top → bottom by dependency direction)-The codebase stacks into these layers; higher layers depend on lower ones.-Use this ordering to frame the tour through the directories below.-{% for layer in ctx.layer_order %}-{{ loop.index }}. {{ layer }}-{% endfor %}-{% endif %}--{% if ctx.kg_layers %}-## Architectural Layers (from Knowledge Graph)-{% for layer in ctx.kg_layers %}-- **{{ layer.name }}** — {{ layer.description | default("") }}{% if layer.nodeIds %} ({{ layer.nodeIds | length }} files){% endif %}--{% endfor %}-{% endif %}--## Top-level directories-{% for d in ctx.directories %}-### `{{ d.path }}/` ({{ d.file_count }} files, mostly {{ d.dominant_language }})-{% if d.community_labels %}-- Architectural clusters present: {{ d.community_labels | join(", ") }}-{% endif %}-{% if d.entry_points %}-- Entry points: {% for ep in d.entry_points %}`{{ ep }}`{% if not loop.last %}, {% endif %}{% endfor %}-{% endif %}-{% if d.top_files %}-- Key files (by PageRank):-{% for f in d.top_files %}- - `{{ f }}`-{% endfor %}-{% endif %}--{% endfor %}--## What to write-Produce a Codebase Map markdown page. Required sections, in this order:--1. **## Overview** — one paragraph: the shape of the file tree at a glance,- how many top-level directories matter, and which one a new contributor- should explore first. Ground every claim in the facts above.-2. **## Top-level directories** — one short subsection per directory listed- above (heading: `### \`<path>/\``). Each subsection should answer two- questions in 2–4 sentences: (a) what kind of code lives here, (b) the- first file or two to read. Reference the listed entry points and key- files. Do not invent files that aren't in the data.-3. **## If you're looking for…** — a bulleted lookup list of 5–8 entries- that map common questions to directories. Examples to model on (adapt- to what's actually here): "the HTTP layer → `server/`", "tests → mirror- the layout under `tests/`", "the public API surface → `<top file>`".-4. **## What's not here** — one short paragraph naming up to three- directories that exist in the tree but are *not* the primary place a- contributor should start (build infrastructure, vendor folders, etc.).--Output markdown only. No preamble, no apologies, no closing summary.diff --git a/packages/core/src/repowise/core/generation/templates/onboarding/development_guide.j2 b/packages/core/src/repowise/core/generation/templates/onboarding/development_guide.j2deleted file mode 100644index 050eef64c..000000000--- a/packages/core/src/repowise/core/generation/templates/onboarding/development_guide.j2+++ /dev/null@@ -1,63 +0,0 @@-You are writing the "Development Guide" page for `{{ ctx.repo_name }}` —-how to do common things in this codebase, derived from conventions that-already exist in the file tree. Convention-based, not aspirational: only-report rules the data actually supports.--## Detected conventions (use only these — do not invent new ones)--{% if ctx.suffix_patterns %}-### Recurring filename suffixes-{% for p in ctx.suffix_patterns %}-- **`*_{{ p.suffix }}`** — {{ p.file_count }} files. Examples:-{% for ex in p.examples %}- - `{{ ex }}`-{% endfor %}-{% endfor %}-{% endif %}--{% if ctx.test_mirror %}-### Test mirror layout-- **`{{ ctx.test_mirror.test_root }}/` mirrors the source tree** — {{ ctx.test_mirror.matched_files }} of {{ ctx.test_mirror.source_files }} test files match a source stem.-{% endif %}--{% if ctx.parallel_dirs %}-### Parallel sibling directories-The following parent directories contain ≥3 sibling subdirectories that-share a common file layout (a strong "every X is built like Y" signal):-{% for d in ctx.parallel_dirs %}-- `{{ d }}/`-{% endfor %}-{% endif %}--{% if ctx.entry_points %}-## Entry points (anchor "where to start" advice in these)-{% for ep in ctx.entry_points %}-- `{{ ep }}`-{% endfor %}-{% endif %}--## What to write-Produce a Development Guide markdown page. Required structure:--1. **## Overview** — one paragraph naming the strongest 2–3 conventions- the reader should internalise before making changes. Quote concrete- suffixes / directory names from the data above.-2. **## Adding a new <thing>** — pick the dominant suffix pattern above- and write a 3–5 step playbook for adding another file of that kind.- Example: if `*_handler` is dominant, the section is "Adding a new- handler" with steps grounded in the example file paths above. If no- suffix pattern dominates, skip this section and replace it with- **"## Adding a new module"** based on the parallel-dirs signal.-3. **## Writing tests** — only include this section if the test mirror- was detected above. State the rule explicitly: tests for- `path/to/foo.py` live at `<test_root>/.../test_foo.py` (or the- project's actual convention as evidenced by the data).-4. **## House style** — at most three bullets covering observations the- data supports (naming, parallel-dir uniformity, etc.). If you can't- support a bullet with the data above, omit it.--Hard rules:-- Never invent a linter rule, a commit-message format, or a code style- the data above does not support.-- Quote real file paths in every example.-- Output markdown only. No preamble, no apologies, no closing summary.diff --git a/packages/core/src/repowise/core/generation/templates/onboarding/guided_tour.j2 b/packages/core/src/repowise/core/generation/templates/onboarding/guided_tour.j2deleted file mode 100644index 7f1a0146e..000000000--- a/packages/core/src/repowise/core/generation/templates/onboarding/guided_tour.j2+++ /dev/null@@ -1,60 +0,0 @@-You are writing the "Guided Tour" page for `{{ ctx.repo_name }}` — a single,-ordered walk that takes a new contributor from the entry points inward, one-stop at a time, and closes on how the system is built and deployed.--The stops below are ALREADY ORDERED by graph topology (entry points first,-then the files they import, depth by depth, with infrastructure last). Each-stop names a real wiki page and its one-line summary. Your job is the-*connective tissue*: for each stop write 2–4 sentences that say what the-reader is looking at, why it matters at this point in the walk, and — crucially-— how it relates to the stops BEFORE it. The tour must read like a tour, not a-glossary: explicitly back-reference earlier steps ("the parser introduced in-Step 2 hands its output to…").--{% if ctx.layer_order %}-## Layer spine (top → bottom by dependency direction)-The system stacks as: {{ ctx.layer_order | join(" → ") }}. Use this to orient-the reader as the walk descends from entry points toward foundations.-{% endif %}--## The ordered stops (narrate these IN THIS ORDER — do not reorder)-{% for s in ctx.stops %}-### Step {{ s.order }}: {{ s.title }} ({{ s.kind }})-- Page: `{{ s.target_path }}` ({{ s.page_type }})-- Why this stop: {{ s.reason }}-{% if s.summary %}- What it does: {{ s.summary }}{% endif %}--{% endfor %}--## What to write-Produce a markdown page with this structure:--1. **## How to take this tour** — one short paragraph: this is an ordered walk- from the entry points inward; each step builds on the last.-2. **## The tour** — one `### Step N: <title>` subsection per stop above, in- order. For each step:- - Open with one sentence stating the file/page's role (lead with the role:- "orchestrator", "entry point", "parser", "adapter", "deploy manifest", …).- - Then 1–3 sentences of connective narration that reference at least one- earlier step by number where it makes sense.- - End the sentence that names the page with the path in backticks (e.g.- `{{ ctx.stops[0].target_path }}`) so the reader can click through.-3. **## Where to go next** — 2–3 bullets pointing past the tour (the layer- pages, the module pages, or the search), each with a half-sentence reason.--Style — make every step concrete, like these:-- Bad: "This is the Dockerfile."- Good: "The Dockerfile defines how the application is packaged into a container- image — a multi-stage build that compiles the sources from Step 3 and- copies only the output into a slim runtime image."-- Bad: "These are the database models."- Good: "The data models define the core entities; the `User` model here is the- one the request handler in Step 2 loads on every authenticated call."--Hard rules:-- Narrate the stops in the given order; never invent stops, paths, or files- that are not listed above.-- If a stop's summary is missing, describe its role from its title and kind- rather than inventing internals.-- Output markdown only. No preamble, no apologies, no closing summary section- beyond "Where to go next".diff --git a/packages/core/src/repowise/core/generation/templates/stub/onboarding/codebase_map.j2 b/packages/core/src/repowise/core/generation/templates/stub/onboarding/codebase_map.j2deleted file mode 100644index 446bfae21..000000000--- a/packages/core/src/repowise/core/generation/templates/stub/onboarding/codebase_map.j2+++ /dev/null@@ -1,56 +0,0 @@-{#- Deterministic (no-LLM) codebase map. Directory tables render well from- structure alone, so this page is near-parity with its LLM counterpart.--#}-# Codebase Map--`{{ ctx.repo_name }}` holds {{ ctx.total_files }} files and {{ ctx.total_loc }} lines across {{ ctx.directories | length }} significant director{{ "ies" if ctx.directories | length != 1 else "y" }}.--{% if ctx.layer_order %}-## Architectural layers--Top to bottom, the order work flows through.-{% for l in ctx.layer_order %}-{{ loop.index }}. {{ l }}-{% endfor %}-{% endif %}--{% if ctx.entry_points %}-## Entry points-{#- Capped: a monorepo where every UI folder carries an index.ts produces- dozens, and the point of this section is to name a place to start. -#}-{% for ep in ctx.entry_points[:15] %}-- `{{ ep }}`-{% endfor %}-{%- if ctx.entry_points | length > 15 %}-- ...and {{ ctx.entry_points | length - 15 }} more.-{% endif %}-{% endif %}--## Directories--| Directory | Files | Language | Clusters |-| --- | --- | --- | --- |-{% for d in ctx.directories -%}-| `{{ d.path }}` | {{ d.file_count }} | {{ d.dominant_language }} | {{ (d.community_labels | join(", ")) | oneline(60) if d.community_labels else "none" }} |-{% endfor %}--{% for d in ctx.directories %}-{% if d.top_files or d.entry_points %}-### `{{ d.path }}`--{{ d.file_count }} {{ d.dominant_language }} file{{ "s" if d.file_count != 1 else "" }}.-{% if d.entry_points %}-Entry points:-{% for ep in d.entry_points %}-- `{{ ep }}`-{% endfor %}-{% endif %}-{% if d.top_files %}-Most central files:-{% for f in d.top_files %}-- `{{ f }}`-{% endfor %}-{% endif %}-{% endif %}-{% endfor %}-{% include "stub/_footer.j2" %}diff --git a/packages/core/src/repowise/core/generation/templates/stub/onboarding/development_guide.j2 b/packages/core/src/repowise/core/generation/templates/stub/onboarding/development_guide.j2deleted file mode 100644index 6c9783189..000000000--- a/packages/core/src/repowise/core/generation/templates/stub/onboarding/development_guide.j2+++ /dev/null@@ -1,42 +0,0 @@-{#- Deterministic (no-LLM) development guide. The conventions here are mined- from file naming and directory shape, so they are observations rather- than rules. Worded that way on purpose.--#}-# Development Guide--Conventions observed in `{{ ctx.repo_name }}` by looking at how files are named and arranged. These are patterns the codebase already follows, not rules anyone wrote down.--{% if ctx.suffix_patterns %}-## Naming patterns--| Suffix | Files | Examples |-| --- | --- | --- |-{% for p in ctx.suffix_patterns -%}-| `{{ p.suffix }}` | {{ p.file_count }} | {% for e in p.examples[:3] %}`{{ e }}`{% if not loop.last %}, {% endif %}{% endfor %} |-{% endfor %}--A new file that fits one of these categories should follow the matching suffix.-{% endif %}--{% if ctx.test_mirror %}-## Where tests live--Tests sit under `{{ ctx.test_mirror.test_root }}`, mirroring the source tree: {{ ctx.test_mirror.matched_files }} of {{ ctx.test_mirror.source_files }} source files have a matching test path. A new source file's test belongs at the mirrored path under `{{ ctx.test_mirror.test_root }}`.-{% endif %}--{% if ctx.parallel_dirs %}-## Directories that move together--These sit at the same level and tend to be structured alike, so a change in one usually has a counterpart in the others.-{% for d in ctx.parallel_dirs %}-- `{{ d }}`-{% endfor %}-{% endif %}--{% if ctx.entry_points %}-## Entry points to run-{% for ep in ctx.entry_points %}-- `{{ ep }}`-{% endfor %}-{% endif %}-{% include "stub/_footer.j2" %}diff --git a/packages/core/src/repowise/core/generation/templates/stub/onboarding/guided_tour.j2 b/packages/core/src/repowise/core/generation/templates/stub/onboarding/guided_tour.j2deleted file mode 100644index 0ecad572c..000000000--- a/packages/core/src/repowise/core/generation/templates/stub/onboarding/guided_tour.j2+++ /dev/null@@ -1,30 +0,0 @@-{#- Deterministic (no-LLM) guided tour.-- Stop order, kind and the per-stop `reason` strings are all produced by- generation/tour.py, so this page is close to its LLM counterpart. What a- model adds is the connective narration between stops ("the parser from- step 2 hands its output to..."), which structure cannot supply.--#}-# Guided Tour--A reading order through `{{ ctx.repo_name }}`, {{ ctx.stops | length }} stops long. Each stop is picked by how much of the codebase depends on it and how early it sits in the import graph, so following them in order means you rarely meet a name before it has been introduced.--{% if ctx.layer_order %}-**Layer order:** {% for l in ctx.layer_order %}{{ l }}{% if not loop.last %} → {% endif %}{% endfor %}-{% endif %}--{% for stop in ctx.stops %}-## {{ stop.order }}. {{ stop.title }}--`{{ stop.target_path }}` *({{ stop.kind }})*--{{ stop.reason | oneline(300) }}-{% if stop.summary %}-{{ stop.summary }}-{% endif %}-{% endfor %}--## Where to go next--Read the layer pages for the architectural spine, then the module pages for the areas you will work in.-{% include "stub/_footer.j2" %}diff --git a/packages/core/src/repowise/core/pipeline/incremental.py b/packages/core/src/repowise/core/pipeline/incremental.pyindex 665be854a..91a30ef46 100644--- a/packages/core/src/repowise/core/pipeline/incremental.py+++ b/packages/core/src/repowise/core/pipeline/incremental.py@@ -945,6 +945,8 @@ async def persist_incremental_index(# Filled by the tombstone step; read after the session closes, so it has to# survive a step that was skipped.tombstoned_page_ids: list[str] = []+ # Same contract, for rows of a page that has been retired outright.+ swept_page_ids: list[str] = []try:await init_db(engine)sf = create_session_factory(engine)@@ -961,6 +963,18 @@ async def persist_incremental_index(except Exception as exc:_skip("Stale row prune", exc)+ # Delete rows of pages retired since this index was built. This+ # path never regenerates a repo-wide page, so nothing else here+ # would ever visit one to notice it should be gone, and for a user+ # whose updates all come from the post-commit hook this is the only+ # place a retirement can land.+ try:+ from repowise.core.pipeline.persist import sweep_retired_pages++ swept_page_ids = await sweep_retired_pages(session, repo_id)+ except Exception as exc:+ _skip("Retired page sweep", exc)+# Tombstone pages for deleted/renamed files FIRST — a fresh page# for a file that no longer exists misleads every retrieval# consumer until the next full regeneration.@@ -1123,14 +1137,30 @@ async def persist_incremental_index(# A tombstone can never be an answer — hydration drops it — but# retrieval fetches a fixed number of rows before that check runs, so# every tombstone left in the index costs a real candidate its slot.- if tombstoned_page_ids:+ #+ # A swept page's FTS row is worse than a tombstone: search hydrates+ # title and snippet from the FTS copy itself, so an orphan answers in+ # full while the page it names 404s.+ if tombstoned_page_ids or swept_page_ids:try:from repowise.core.persistence.search import FullTextSearchfts = FullTextSearch(engine)await fts.ensure_index()- await fts.delete_many(tombstoned_page_ids)+ if tombstoned_page_ids:+ await fts.delete_many(tombstoned_page_ids)+ if swept_page_ids:+ await fts.delete_many(swept_page_ids)except Exception as exc:_skip("Tombstone full-text removal", exc)++ # Ceiling: the swept pages' *vector* embeddings survive this path.+ # There is no store here to delete them from, and building one would+ # pull the lancedb import onto the post-commit hook, which+ # ``deterministic.py`` avoids on purpose — and with the default mock+ # embedder this path never wrote a page embedding in the first place.+ # LanceDB hydrates a hit from its own columns, so a residual embedding+ # can still surface in semantic search until the next docs-mode update+ # (which does delete it) or a reindex.finally:await engine.dispose()diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.pyindex 9dfe4bdf6..39c219bdc 100644--- a/packages/core/src/repowise/core/pipeline/persist.py+++ b/packages/core/src/repowise/core/pipeline/persist.py@@ -639,19 +639,19 @@ async def _prune_stale_file_rows(_SWEPT_GENERATED_PAGE_TYPES = STRUCTURALLY_KEYED_PAGE_TYPES-async def sweep_retired_page_types(session: Any, repo_id: str) -> list[str]:- """Delete every row of a page type that no longer exists.+async def sweep_retired_pages(session: Any, repo_id: str) -> list[str]:+ """Delete every row of a page that no longer exists, by type or by id.Distinct from the two sweeps below, and simpler than either: those ask what*this* run produced, because a page of a live type may legitimately be- absent from a scoped run. A retired type has no legitimate rows at all —+ absent from a scoped run. A retired page has no legitimate rows at all —nothing emits one and no failure mode can make anything emit one — so thequestion never arises and this is safe on every path, full or scoped.The retirement tables are the source of truth rather than a list repeated- here. A type is retired exactly when a reader following its id gets sent+ here. A page is retired exactly when a reader following its id gets sentsomewhere else, and that is what those tables say; keeping a second list- would let a type be redirected without being swept, which is the state this+ would let a page be redirected without being swept, which is the state thisfunction was written to clear.That state is the reason this exists. The architecture diagram merged into@@ -663,26 +663,44 @@ async def sweep_retired_page_types(session: Any, repo_id: str) -> list[str]:second-ranked retrieval hit for "how does the ingestion pipeline work",competing with the overview it had been merged into.- Returns the swept page ids so the caller can drop them from FTS after the- session closes (the FTS store must not be touched in-session).+ Retirement by *id* is the second half of the same argument, and the reason+ this is no longer named for types. Three orientation slots retired out of+ the onboarding collection while five stayed, so their rows cannot be+ reached by page type: ``onboarding`` still has legitimate rows and always+ will. Sweeping the exact ids is the only way those leave a store, and the+ safety argument is unchanged — a retired id names a page nothing emits.++ Returns the swept page ids so the caller can drop them from the vector+ store and from FTS. A row deleted here but left in either of those is worse+ than one never swept: search still answers from the FTS copy, with the full+ title and snippet of a page the reader can no longer open."""- from sqlalchemy import delete, select+ from sqlalchemy import delete, or_, selectfrom repowise.core.generation.page_redirects import (+ RETIRED_IDS,SUPERSEDED_TO_REPO_WIDE,SUPERSEDED_TYPES,)from repowise.core.persistence.models import Page, PageVersion- retired = sorted(set(SUPERSEDED_TYPES) | set(SUPERSEDED_TO_REPO_WIDE))- if not retired:+ retired_types = sorted(set(SUPERSEDED_TYPES) | set(SUPERSEDED_TO_REPO_WIDE))+ retired_ids = sorted(RETIRED_IDS)+ if not retired_types and not retired_ids:return []+ # Either rule can match, and a page matched by both is one row either way.+ match_clauses = []+ if retired_types:+ match_clauses.append(Page.page_type.in_(retired_types))+ if retired_ids:+ match_clauses.append(Page.id.in_(retired_ids))+stale = ((await session.execute(select(Page.id).where(- Page.repository_id == repo_id, Page.page_type.in_(retired)+ Page.repository_id == repo_id, or_(*match_clauses))))@@ -697,10 +715,11 @@ async def sweep_retired_page_types(session: Any, repo_id: str) -> list[str]:)if stale:logger.info(- "retired_page_types_swept",+ "retired_pages_swept",repo_id=repo_id,count=len(stale),- types=retired,+ types=retired_types,+ ids=retired_ids,)return list(stale)@@ -1357,7 +1376,7 @@ async def persist_pipeline_result()# Rows of a page type that no longer exists at all. Independent of what# this run produced, so it runs on every path rather than only here.- swept_page_ids += await sweep_retired_page_types(session, repo_id)+ swept_page_ids += await sweep_retired_pages(session, repo_id)# Placement depends on the whole page set, so it is computed here rather# than during generation, after the sweep has retired anything stale.diff --git a/packages/core/src/repowise/core/pipeline/scoped_generation.py b/packages/core/src/repowise/core/pipeline/scoped_generation.pyindex 1f1921ef4..7faf53121 100644--- a/packages/core/src/repowise/core/pipeline/scoped_generation.py+++ b/packages/core/src/repowise/core/pipeline/scoped_generation.py@@ -208,7 +208,7 @@ async def execute_scoped_generation(from repowise.core.pipeline import run_generationfrom repowise.core.pipeline.persist import (mark_page_ids_stale,- sweep_retired_page_types,+ sweep_retired_pages,sweep_superseded_generated_pages,)@@ -254,7 +254,7 @@ async def execute_scoped_generation(# emit a retired type, so absence is never evidence of a narrow scope.# Here rather than only on the full path because an index that is only# ever updated incrementally is exactly the one still serving them.- swept_page_ids += await sweep_retired_page_types(session, repo_id)+ swept_page_ids += await sweep_retired_pages(session, 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.diff --git a/packages/server/src/repowise/server/mcp_server/_page_paths.py b/packages/server/src/repowise/server/mcp_server/_page_paths.pyindex eab8d2594..4c1a06882 100644--- a/packages/server/src/repowise/server/mcp_server/_page_paths.py+++ b/packages/server/src/repowise/server/mcp_server/_page_paths.py@@ -8,7 +8,7 @@ repository overview it is the repository's name.Every one of those is a legitimate thing to *rank*, and none of them is alegitimate thing to hand back in a field named ``path`` or ``file``. An agent-told to read ``onboarding/guided_tour`` or ``pkg/cmd/release`` gets an error,+told to read ``onboarding/how_it_works`` or ``pkg/cmd/release`` gets an error,and nothing in the response says the string was never a path. This module isthe one place that distinction is written down, so the tools cannot drift onit.diff --git a/packages/ui/__tests__/docs/docs-tree.test.tsx b/packages/ui/__tests__/docs/docs-tree.test.tsxindex 16899a959..4648bf6f7 100644--- a/packages/ui/__tests__/docs/docs-tree.test.tsx+++ b/packages/ui/__tests__/docs/docs-tree.test.tsx@@ -839,4 +839,44 @@ describe("DocsTree", () => {// Both files are in the single bottom folder.expect(screen.getByText("Auto-documented files (2)")).toBeInTheDocument();});++ // Three orientation slots were retired, and their rows survive in every+ // index built before the sweep that removes them. `ONBOARDING_SLOT_TITLES`+ // still lists all three on purpose, and this is the reason: in *folder*+ // view a dedicated onboarding page whose slot is not in that map does not+ // disappear, it falls through to path-based grouping and surfaces as a stray+ // top-level `onboarding/` directory beside the Onboarding folder. That reads+ // as a bug rather than a retirement.+ //+ // The default domain view is unaffected either way — it places pages by the+ // stamped parent_page_id and labels them from page.title — so folder view is+ // what this has to assert on.+ it("keeps a retired onboarding slot in the Onboarding folder rather than a stray directory", () => {+ const retired = makePage({+ id: "onboarding:onboarding/codebase_map",+ page_type: "onboarding",+ title: "Codebase Map",+ target_path: "onboarding/codebase_map",+ metadata: { subkind: "codebase_map" },+ parent_page_id: ROOT.id,+ display_order: 3,+ });+ render(+ <DocsTree+ pages={[ROOT, ONBOARDING, retired]}+ selectedPageId={null}+ onSelectPage={() => {}}+ />,+ );+ fireEvent.click(screen.getByLabelText("Switch to folder view"));++ // Both slots are in the one Onboarding folder, the retired one labelled+ // from the map, which is exactly what keeping its entry buys.+ const onboardingRow = rowLabels().find((l) => l.includes("Onboarding")) ?? "";+ expect(onboardingRow).not.toBe("");+ expect(screen.getByText("Codebase Map")).toBeInTheDocument();+ expect(screen.getByText("Getting Started")).toBeInTheDocument();+ // The failure mode if the entry were dropped: a bare `onboarding` row.+ expect(rowLabels().some((l) => l.trim() === "onboarding")).toBe(false);+ });});diff --git a/packages/ui/__tests__/present/build-present-model.test.ts b/packages/ui/__tests__/present/build-present-model.test.tsindex dc8c5da23..6387274fc 100644--- a/packages/ui/__tests__/present/build-present-model.test.ts+++ b/packages/ui/__tests__/present/build-present-model.test.ts@@ -184,4 +184,24 @@ describe("buildPresentModel", () => {const model = buildPresentModel([bareOverview, layerCore]);expect(model.walkthrough.length).toBeGreaterThan(0);});++ // The assumption the Guided Tour page's retirement rests on. The page is+ // gone; the ordered stops it used to narrate are still computed and still+ // written to the overview's metadata, and every consumer outside that page+ // read the metadata rather than the page. If that were ever untrue, this is+ // where it would show: a deck built from an index that has no onboarding+ // page at all must still walk the tour.+ it("builds a full deck and walkthrough with no onboarding page in the index", () => {+ const pages = [overview, arch, layerApi, layerCore, mainFile];+ expect(pages.some((p) => p.page_type === "onboarding")).toBe(false);++ const model = buildPresentModel(pages);++ expect(model.deck.some((s) => s.kind === "title")).toBe(true);+ expect(model.deck.some((s) => s.kind === "diagram")).toBe(true);+ expect(model.deck.length).toBeGreaterThan(3);+ expect(model.walkthrough).toHaveLength(2);+ expect(model.walkthrough.map((w) => w.title)).toEqual(["main.py", "core.py"]);+ expect(model.totalMinutes).toBeGreaterThan(0);+ });});diff --git a/packages/ui/src/lib/page-types.ts b/packages/ui/src/lib/page-types.tsindex dd3df7d08..4fe0797cf 100644--- a/packages/ui/src/lib/page-types.ts+++ b/packages/ui/src/lib/page-types.ts@@ -95,7 +95,7 @@ export function isStubPage(//// One slot — project_overview — is *promoted*: its// content lives in the existing repo_overview page, tagged via-// `metadata.onboarding_slot`. The other eight are dedicated+// `metadata.onboarding_slot`. The other five are dedicated// `page_type === "onboarding"` pages with `metadata.subkind` discriminating// them.//@@ -111,14 +111,33 @@ export function isStubPage(export const ONBOARDING_SLOT_TITLES = {project_overview: "Project Overview",- guided_tour: "Guided Tour",getting_started: "Getting Started",- codebase_map: "Codebase Map",key_concepts: "Key Concepts",how_it_works: "How It Works",- development_guide: "Development Guide",active_landscape: "Active Landscape",glossary: "Glossary",++ // ---- Retired slots, kept only to label rows an old index still holds ----+ //+ // These three stopped being generated (see `slots.py`), and+ // `sweep_retired_pages` deletes their rows on the next docs update of any+ // kind. An index built before that release still holds them until the user+ // runs one, and `serve` does not.+ //+ // Only the *folder* view is affected — the default domain view places pages+ // by the stamped `parent_page_id` and labels them from `page.title`, so it+ // never consults this map. But `buildOnboardingFolder` does, and dropping a+ // slot from here does not hide such a row: `getOnboardingSlot` returns null+ // and `buildTree` lets the page fall through to path-based grouping, which+ // surfaces it as a stray top-level `onboarding/` directory beside the+ // Onboarding folder. That reads as a bug rather than a retirement, so they+ // stay listed and an un-swept row keeps the label it has always had.+ //+ // Ceiling: delete these three lines once no supported index predates the+ // sweep.+ guided_tour: "Guided Tour",+ codebase_map: "Codebase Map",+ development_guide: "Development Guide",} as const;export type OnboardingSlot = keyof typeof ONBOARDING_SLOT_TITLES;diff --git a/tests/unit/cli/test_update_persist_reliability.py b/tests/unit/cli/test_update_persist_reliability.pyindex ddcbe6a1f..0f0ebb7c3 100644--- a/tests/unit/cli/test_update_persist_reliability.py+++ b/tests/unit/cli/test_update_persist_reliability.py@@ -124,6 +124,127 @@ def test_full_persist_collects_degraded_steps(tmp_path: Path) -> None:assert any(entry.startswith("Graph nodes persist:") for entry in degraded)+# ---------------------------------------------------------------------------+# A retirement has to reach an index nobody re-indexes+# ---------------------------------------------------------------------------+++async def _seed_pages(repo_path: Path, repo_name: str, page_ids: list[str]) -> None:+ """Write page rows and their FTS entries the way an older release left them."""+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.core.persistence import (+ FullTextSearch,+ create_engine,+ create_session_factory,+ get_session,+ init_db,+ upsert_repository,+ )+ from repowise.core.persistence.models import Page++ engine = create_engine(get_db_url_for_repo(repo_path))+ try:+ await init_db(engine)+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ repo = await upsert_repository(session, name=repo_name, local_path=str(repo_path))+ now = datetime.now(UTC)+ for page_id in page_ids:+ page_type, target = page_id.split(":", 1)+ session.add(+ Page(+ id=page_id,+ repository_id=repo.id,+ page_type=page_type,+ title=target,+ content=f"body of {target}",+ target_path=target,+ source_hash="x" * 64,+ model_name="mock",+ provider_name="mock",+ created_at=now,+ updated_at=now,+ )+ )+ fts = FullTextSearch(engine)+ await fts.ensure_index()+ for page_id in page_ids:+ await fts.index(page_id, page_id, f"body of {page_id}")+ finally:+ await engine.dispose()+++async def _page_ids(repo_path: Path) -> set[str]:+ from repowise.cli.helpers import get_db_url_for_repo+ from repowise.core.persistence import create_engine, create_session_factory, get_session+ from repowise.core.persistence.models import Page++ engine = create_engine(get_db_url_for_repo(repo_path))+ try:+ sf = create_session_factory(engine)+ async with get_session(sf) as session:+ return set((await session.execute(select(Page.id))).scalars().all())+ finally:+ await engine.dispose()+++async def _fts_ids(repo_path: Path) -> set[str]:+ import aiosqlite++ async with aiosqlite.connect(repo_path / ".repowise" / "wiki.db") as db:+ rows = await (await db.execute("SELECT page_id FROM page_fts")).fetchall()+ return {r[0] for r in rows}+++def test_update_sweeps_pages_retired_since_the_index_was_built(tmp_path: Path) -> None:+ """The contract that makes a retirement reach an existing user.++ An update runs ``file_pages_only``, so the generation ladder returns before+ the repo-wide levels and never visits an onboarding row to notice it should+ not exist. If the sweep is not called here, a user who never re-indexes is+ served the retired pages forever — which is the state this whole retirement+ mechanism exists to prevent.+ """+ from repowise.core.generation.page_redirects import RETIRED_IDS++ (tmp_path / ".repowise").mkdir()+ retired = sorted(RETIRED_IDS)+ assert retired, "no retired ids to exercise"+ survivor = "onboarding:onboarding/key_concepts"+ asyncio.run(_seed_pages(tmp_path, "repo", [*retired, survivor]))++ asyncio.run(+ _persist_full_update_async(+ repo_path=tmp_path,+ repo_name="repo",+ generated_pages=[_page("file_page:a.py")],+ file_diffs=[],+ git_meta_map={},+ new_decision_markers=[],+ decision_vector_store=None,+ provider=None,+ partial_health_report=None,+ dead_code_report=None,+ graph_builder=None,+ knowledge_graph_result=None,+ degraded=[],+ )+ )++ remaining = asyncio.run(_page_ids(tmp_path))+ assert not remaining & set(retired)+ # The survivor shares page_type='onboarding' with all three. Losing it here+ # would mean the sweep is matching on type, and the whole orientation+ # collection would go with the retirement.+ assert survivor in remaining++ # A row deleted from `pages` but left in FTS still answers search in full,+ # hydrated from the FTS copy, pointing at a page that now 404s.+ fts_left = asyncio.run(_fts_ids(tmp_path))+ assert not fts_left & set(retired)+ assert survivor in fts_left++# ---------------------------------------------------------------------------# Lock contention: exactly one winner# ---------------------------------------------------------------------------diff --git a/tests/unit/generation/test_deterministic_templates.py b/tests/unit/generation/test_deterministic_templates.pyindex 46f46710b..8b2eb5804 100644--- a/tests/unit/generation/test_deterministic_templates.py+++ b/tests/unit/generation/test_deterministic_templates.py@@ -1,8 +1,8 @@"""Render tests for deterministic templates the sample repo cannot reach.``tests/integration/test_deterministic_generation.py`` covers the page types-the fixture repo actually produces. Four templates are unreachable there: the-layer page needs a knowledge graph, and three onboarding slots gate themselves+the fixture repo actually produces. The rest are unreachable there: the layer+page needs a knowledge graph, and the onboarding slots below gate themselvesoff on a fixture with no git history and no dependency manifest. Renderingthem here keeps a Jinja typo from shipping unnoticed."""@@ -18,14 +18,6 @@ from repowise.core.generation.onboarding.subkinds.active_landscape import (HotDir,HotFile,)-from repowise.core.generation.onboarding.subkinds.development_guide import (- DevelopmentGuideContext,- SuffixPattern,-)-from repowise.core.generation.onboarding.subkinds.development_guide import (- # Aliased so pytest does not try to collect it as a test class.- TestMirror as _TestMirror,-)from repowise.core.generation.onboarding.subkinds.getting_started import (GettingStartedContext,ReadmeSection,@@ -70,25 +62,6 @@ def test_getting_started_renders(generator):assert "`httpx`" in page.content-def test_development_guide_renders(generator):- ctx = DevelopmentGuideContext(- repo_name="demo",- suffix_patterns=[SuffixPattern(suffix="_cmd.py", examples=["a_cmd.py"], file_count=4)],- test_mirror=_TestMirror(test_root="tests", matched_files=12, source_files=20),- parallel_dirs=["packages/core", "packages/cli"],- entry_points=["src/main.py"],- )- page = generator._stub_onboarding_page(- _onboarding_spec("development_guide", "development_guide.j2"),- ctx,- "onboarding/development_guide",- )-- assert "`_cmd.py`" in page.content- assert "tests" in page.content- assert "12 of 20" in page.content--def test_active_landscape_renders(generator):ctx = ActiveLandscapeContext(repo_name="demo",diff --git a/tests/unit/generation/test_kg_claude_md_onboarding.py b/tests/unit/generation/test_kg_claude_md_onboarding.pyindex c3ab5f707..9b5f93152 100644--- a/tests/unit/generation/test_kg_claude_md_onboarding.py+++ b/tests/unit/generation/test_kg_claude_md_onboarding.py@@ -16,9 +16,6 @@ from repowise.core.generation.editor_files.data import ()from repowise.core.generation.kg_context import KnowledgeGraphContextfrom repowise.core.generation.onboarding.signals import OnboardingSignals-from repowise.core.generation.onboarding.subkinds.codebase_map import (- CodebaseMapContext,-)from repowise.core.generation.onboarding.subkinds.how_it_works import (HowItWorksContext,_build,@@ -259,52 +256,6 @@ class TestHowItWorksWithTour:assert ctx is None-# ----------------------------------------------------------------------------# CodebaseMap + KG layers tests-# ------------------------------------------------------------------------------class TestCodebaseMapWithLayers:- def test_layers_in_context(self):- ctx = CodebaseMapContext(- repo_name="test",- total_files=10,- total_loc=500,- kg_layers=[{"name": "Core", "description": "Core logic", "nodeIds": ["file:a.py"]}],- )- assert len(ctx.kg_layers) == 1-- def test_template_renders_layers(self, onboarding_env):- tmpl = onboarding_env.get_template("codebase_map.j2")- ctx = CodebaseMapContext(- repo_name="test",- total_files=10,- total_loc=500,- kg_layers=[- {- "name": "Core",- "description": "Core business logic",- "nodeIds": ["file:a.py", "file:b.py"],- },- {"name": "API", "description": "REST API layer", "nodeIds": ["file:c.py"]},- ],- )- rendered = tmpl.render(ctx=ctx)- assert "## Architectural Layers" in rendered- assert "**Core**" in rendered- assert "**API**" in rendered-- def test_template_no_layers_section(self, onboarding_env):- tmpl = onboarding_env.get_template("codebase_map.j2")- ctx = CodebaseMapContext(- repo_name="test",- total_files=10,- total_loc=500,- )- rendered = tmpl.render(ctx=ctx)- assert "Architectural Layers" not in rendered--# ---------------------------------------------------------------------------# KnowledgeGraphContext.get_tour() tests# ---------------------------------------------------------------------------diff --git a/tests/unit/generation/test_models.py b/tests/unit/generation/test_models.pyindex 5e4bd60f6..a74ab863e 100644--- a/tests/unit/generation/test_models.py+++ b/tests/unit/generation/test_models.py@@ -288,6 +288,53 @@ def test_direct_generation_config_frames_evidence_errors_with_the_field_name() -GenerationConfig(source_evidence_files={"repo_overview": "README.md"})+class TestRetiredEvidenceKeysDoNotBreakAnUpgrade:+ """A key naming a retired page is dropped, not raised on.++ The strictness elsewhere in this validator is aimed at a typo, which is+ only ever a mistake. A retired key is a config that was correct when it was+ written, and every user carrying one would hit a hard generation failure on+ their first update after the release that retired the page.+ """++ def test_a_retired_key_is_ignored_rather_than_rejected(self) -> None:+ from repowise.core.generation.page_redirects import RETIRED_IDS++ retired_keys = [+ page_id.split(":", 1)[1]+ for page_id in sorted(RETIRED_IDS)+ if page_id.startswith("onboarding:")+ ]+ assert retired_keys, "no retired onboarding keys to exercise"++ for key in retired_keys:+ config = GenerationConfig.from_repo_config(+ {"generation_context": {"files": {key: ["docs/x.md"]}}}+ )+ assert key not in config.source_evidence_files++ def test_a_retired_key_alongside_a_live_one_keeps_the_live_one(self) -> None:+ config = GenerationConfig.from_repo_config(+ {+ "generation_context": {+ "files": {+ "onboarding/codebase_map": ["docs/old.md"],+ "repo_overview": ["README.md"],+ }+ }+ }+ )++ assert config.source_evidence_files == {"repo_overview": ("README.md",)}++ def test_a_genuine_typo_still_raises(self) -> None:+ """The leniency is scoped to the retirement table, not to unknown keys."""+ with pytest.raises(ValueError, match="must name repo_overview"):+ GenerationConfig.from_repo_config(+ {"generation_context": {"files": {"onboarding/codebase_maps": ["docs/x.md"]}}}+ )++def test_direct_generation_config_normalizes_evidence_keys_like_the_config_loader() -> None:# Sharing one validator also aligns key normalization: direct construction# now strips keys before the membership check, as from_repo_config alwaysdiff --git a/tests/unit/generation/test_onboarding.py b/tests/unit/generation/test_onboarding.pyindex 0c825cddc..69dfb06ea 100644--- a/tests/unit/generation/test_onboarding.py+++ b/tests/unit/generation/test_onboarding.py@@ -28,8 +28,6 @@ from repowise.core.generation.onboarding.slots import (ONBOARDING_ORDER,PROMOTED_SLOTS,SLOT_ACTIVE_LANDSCAPE,- SLOT_CODEBASE_MAP,- SLOT_DEVELOPMENT_GUIDE,SLOT_GETTING_STARTED,SLOT_HOW_IT_WORKS,SLOT_KEY_CONCEPTS,@@ -168,10 +166,10 @@ def test_subkinds_registered_in_canonical_order() -> None:# ONBOARDING_ORDER.expected = [s for s in ONBOARDING_ORDER if s not in PROMOTED_SLOTS.values()]assert slots == expected- # Six templated subkinds, the topology-driven guided tour, and the- # glossary, which is rendered without a model at all.- assert len(slots) == 8- assert "guided_tour" in slots+ # Four templated subkinds plus the glossary, which is rendered without a+ # model at all. The promoted overview brings orientation to six pages.+ assert len(slots) == 5+ assert len(ONBOARDING_ORDER) == 6# Last, and it must stay last: a glossary is a lookup surface, not a# reading step.assert slots[-1] == "glossary"@@ -182,37 +180,13 @@ def test_onboarding_level_is_eight() -> None:def test_target_path_format() -> None:- assert target_path("codebase_map") == "onboarding/codebase_map"+ assert target_path("key_concepts") == "onboarding/key_concepts"def test_promoted_slots_map() -> None:assert PROMOTED_SLOTS == {"repo_overview": "project_overview"}-# ----------------------------------------------------------------------------# Codebase map — always generates-# ------------------------------------------------------------------------------def test_codebase_map_always_builds() -> None:- spec = onboarding.get_spec(SLOT_CODEBASE_MAP)- assert spec is not None- files = [- _file("src/auth/login.py", symbols=["Login"]),- _file("src/auth/session.py", symbols=["Session"]),- _file("src/auth/middleware.py", symbols=["AuthMiddleware"]),- _file("src/api/routes.py", symbols=["Router"]),- _file("src/api/handlers.py", symbols=["Handler"]),- _file("src/api/serializers.py", symbols=["Serializer"]),- ]- sig = _signals(files=files)- ctx = spec.build_context(sig)- assert ctx is not None- assert len(ctx.directories) >= 1- # Largest dir first- assert ctx.directories[0].file_count >= ctx.directories[-1].file_count--# ---------------------------------------------------------------------------# Active landscape — gated on git churn# ---------------------------------------------------------------------------@@ -835,12 +809,13 @@ async def test_missing_onboarding_evidence_is_visible_in_page_provenance() -> Noasync def test_evidence_for_a_gated_page_is_reported_as_not_generated() -> None:- spec = onboarding.get_spec(SLOT_DEVELOPMENT_GUIDE)+ spec = onboarding.get_spec(SLOT_KEY_CONCEPTS)assert spec is not None- signals = _signals(files=[_file("src/one.py")])+ # One symbol is below the concept gate, so the page is never generated.+ signals = _signals(files=[_file("src/one.py", symbols=["One"])])config = GenerationConfig(source_evidence_files={- "onboarding/development_guide": ("docs/development.md",),+ "onboarding/key_concepts": ("docs/concepts.md",),},)generator = PageGenerator(MockProvider(), ContextAssembler(config), config)@@ -851,45 +826,11 @@ async def test_evidence_for_a_gated_page_is_reported_as_not_generated() -> None:assert page is Noneassert any(entry.get("event") == "source_evidence.skipped"- and entry.get("skipped")- == [{"path": "docs/development.md", "reason": "page_not_generated"}]+ and entry.get("skipped") == [{"path": "docs/concepts.md", "reason": "page_not_generated"}]for entry in logs)-# ----------------------------------------------------------------------------# Development guide — gated on ≥2 structural signals-# ------------------------------------------------------------------------------def test_development_guide_skipped_for_unconventional_repo() -> None:- spec = onboarding.get_spec(SLOT_DEVELOPMENT_GUIDE)- assert spec is not None- sig = _signals(files=[_file("src/a.py"), _file("src/b.py")])- assert spec.build_context(sig) is None---def test_development_guide_fires_with_suffix_pattern_and_test_mirror() -> None:- spec = onboarding.get_spec(SLOT_DEVELOPMENT_GUIDE)- assert spec is not None- files = [- _file("src/auth_handler.py", symbols=["AuthHandler"]),- _file("src/user_handler.py", symbols=["UserHandler"]),- _file("src/billing_handler.py", symbols=["BillingHandler"]),- _file("src/order_handler.py", symbols=["OrderHandler"]),- _file("tests/test_auth_handler.py"),- _file("tests/test_user_handler.py"),- _file("tests/test_billing_handler.py"),- ]- sig = _signals(files=files)- ctx = spec.build_context(sig)- assert ctx is not None- suffixes = {p.suffix for p in ctx.suffix_patterns}- assert "handler" in suffixes- assert ctx.test_mirror is not None- assert ctx.test_mirror.test_root == "tests"--# ---------------------------------------------------------------------------# Promoted-page tagging# ---------------------------------------------------------------------------@@ -930,50 +871,6 @@ def test_tag_promoted_pages_sets_onboarding_slot() -> None:assert "onboarding_slot" not in pages[2].metadata-# ----------------------------------------------------------------------------# Guided tour — gated on having a real (multi-stop) tour-# ------------------------------------------------------------------------------def _tour_stops(n: int) -> tuple[dict, ...]:- return tuple(- {- "order": i + 1,- "target_path": f"src/file_{i}.py",- "page_type": "file_page",- "title": f"file_{i}.py",- "depth": i,- "kind": "code",- "reason": "reason",- }- for i in range(n)- )---def test_guided_tour_skipped_without_enough_stops() -> None:- spec = onboarding.get_spec("guided_tour")- assert spec is not None- sig = _signals(files=[_file("src/main.py", is_entry_point=True)], tour_stops=_tour_stops(1))- assert spec.build_context(sig) is None---def test_guided_tour_builds_with_stops_and_summaries() -> None:- spec = onboarding.get_spec("guided_tour")- assert spec is not None- sig = _signals(- files=[_file("src/main.py", is_entry_point=True)],- tour_stops=_tour_stops(3),- layer_order=("API", "Service", "Data"),- completed_page_summaries={"src/file_0.py": "Entry orchestrator."},- )- ctx = spec.build_context(sig)- assert ctx is not None- assert len(ctx.stops) == 3- assert ctx.layer_order == ["API", "Service", "Data"]- # Summary is attached to the matching stop.- assert ctx.stops[0].summary == "Entry orchestrator."--# ---------------------------------------------------------------------------# Templates render# ---------------------------------------------------------------------------@@ -1000,12 +897,6 @@ def _jinja_env() -> jinja2.Environment:@pytest.mark.parametrize("subkind_slot,ctx_factory",[- (- SLOT_CODEBASE_MAP,- lambda: onboarding.get_spec(SLOT_CODEBASE_MAP).build_context(- _signals(files=[_file(f"src/m{i}.py", symbols=[f"M{i}"]) for i in range(6)])- ),- ),(SLOT_ACTIVE_LANDSCAPE,lambda: onboarding.get_spec(SLOT_ACTIVE_LANDSCAPE).build_context(@@ -1062,33 +953,6 @@ def _jinja_env() -> jinja2.Environment:)),),- (- "guided_tour",- lambda: onboarding.get_spec("guided_tour").build_context(- _signals(- files=[_file("src/main.py", is_entry_point=True)],- tour_stops=_tour_stops(3),- layer_order=("API", "Service"),- completed_page_summaries={"src/file_0.py": "Entry orchestrator."},- )- ),- ),- (- SLOT_DEVELOPMENT_GUIDE,- lambda: onboarding.get_spec(SLOT_DEVELOPMENT_GUIDE).build_context(- _signals(- files=[- _file("src/auth_handler.py"),- _file("src/user_handler.py"),- _file("src/billing_handler.py"),- _file("src/order_handler.py"),- _file("tests/test_auth_handler.py"),- _file("tests/test_user_handler.py"),- _file("tests/test_billing_handler.py"),- ]- )- ),- ),],)def test_subkind_template_renders(subkind_slot: str, ctx_factory: Any) -> None:diff --git a/tests/unit/generation/test_page_redirects.py b/tests/unit/generation/test_page_redirects.pyindex 06096ab6c..8c2809b7f 100644--- a/tests/unit/generation/test_page_redirects.py+++ b/tests/unit/generation/test_page_redirects.py@@ -5,10 +5,13 @@ from __future__ import annotationsimport pytestfrom repowise.core.generation.page_redirects import (+ RETIRED_IDS,SUPERSEDED_IDS,+ SUPERSEDED_IDS_TO_REPO_WIDE,SUPERSEDED_TYPES,SupersededCycleError,SupersededTargetError,+ repo_wide_successor_type,resolve_superseded,)@@ -177,6 +180,20 @@ class TestShippedTables:for retired_type, successor in SUPERSEDED_TYPES.items():assert retired_type != successor+ def test_every_retired_id_resolves_somewhere(self):+ """Whichever table names it, a retired id must not dead-end.++ Walks ``RETIRED_IDS`` rather than either table on its own, so an id+ added to one of them cannot be left with no destination.+ """+ for retired_id in sorted(RETIRED_IDS):+ landed = resolve_superseded(retired_id) or repo_wide_successor_type(retired_id)+ assert landed, f"{retired_id} is retired but resolves to nothing"++ def test_the_two_id_tables_do_not_both_claim_an_id(self):+ """One id, one destination — two rules for it is a table bug."""+ assert not set(SUPERSEDED_IDS) & set(SUPERSEDED_IDS_TO_REPO_WIDE)+# ---------------------------------------------------------------------------# The architecture map moved onto the overview@@ -195,3 +212,51 @@ class TestArchitectureDiagramRetirement:def test_the_overview_itself_is_not_redirected(self):assert resolve_superseded("repo_overview:repowise") is None++# ---------------------------------------------------------------------------+# Three orientation pages retired onto the overview+# ---------------------------------------------------------------------------+++RETIRED_ORIENTATION_IDS = [+ "onboarding:onboarding/guided_tour",+ "onboarding:onboarding/codebase_map",+ "onboarding:onboarding/development_guide",+]++SURVIVING_ORIENTATION_IDS = [+ "onboarding:onboarding/getting_started",+ "onboarding:onboarding/key_concepts",+ "onboarding:onboarding/how_it_works",+ "onboarding:onboarding/active_landscape",+ "onboarding:onboarding/glossary",+]+++class TestOrientationRetirement:+ """The id-keyed repo-wide shape, which these three are the first users of.++ The successor is the overview, whose id carries the repository name, so it+ cannot be written as a literal successor id. And the retired pages share+ ``page_type='onboarding'`` with the five that survive, so the rule cannot+ be keyed on type either. Both halves are asserted here because getting+ either wrong silently takes out the whole orientation collection.+ """++ @pytest.mark.parametrize("page_id", RETIRED_ORIENTATION_IDS)+ def test_a_retired_slot_hands_off_to_the_overview(self, page_id):+ assert repo_wide_successor_type(page_id) == "repo_overview"++ @pytest.mark.parametrize("page_id", RETIRED_ORIENTATION_IDS)+ def test_a_retired_slot_has_no_literal_successor(self, page_id):+ """It resolves repo-wide instead, which the serving layer handles."""+ assert resolve_superseded(page_id) is None++ @pytest.mark.parametrize("page_id", SURVIVING_ORIENTATION_IDS)+ def test_a_surviving_slot_is_not_redirected(self, page_id):+ """The regression that a type-keyed rule would cause."""+ assert repo_wide_successor_type(page_id) is None+ assert resolve_superseded(page_id) is None++ def test_the_retired_set_is_exactly_these_three(self):+ assert sorted(RETIRED_IDS) == sorted(RETIRED_ORIENTATION_IDS)diff --git a/tests/unit/persistence/test_retired_page_types_sweep.py b/tests/unit/persistence/test_retired_pages_sweep.pysimilarity index 59%rename from tests/unit/persistence/test_retired_page_types_sweep.pyrename to tests/unit/persistence/test_retired_pages_sweep.pyindex db018f559..3c2169e06 100644--- a/tests/unit/persistence/test_retired_page_types_sweep.py+++ b/tests/unit/persistence/test_retired_pages_sweep.py@@ -1,13 +1,18 @@-"""Tests for the retired-page-type sweep.+"""Tests for the retired-page sweep.-A retired page type has no live rows: nothing emits one and no failure mode-can make anything emit one. So unlike the other two sweeps, this one does not-ask what the run produced — which is what makes it safe on a scoped run, where+A retired page has no live rows: nothing emits one and no failure mode can+make anything emit one. So unlike the other two sweeps, this one does not ask+what the run produced — which is what makes it safe on a scoped run, whereabsence is normally no evidence at all.-The retirement tables in ``page_redirects`` are the source of truth. A type+The retirement tables in ``page_redirects`` are the source of truth. A pagethat redirects but is never swept leaves an index serving a page the producthas replaced, which is the state this was written to clear.++Retirement by exact id is the half that cannot be expressed as a type. Three+orientation slots retired while five stayed, and all eight are+``page_type='onboarding'``, so a type-keyed sweep would take the survivors+with them."""from __future__ import annotations@@ -17,11 +22,12 @@ from datetime import UTC, datetimefrom sqlalchemy import selectfrom repowise.core.generation.page_redirects import (+ RETIRED_IDS,SUPERSEDED_TO_REPO_WIDE,SUPERSEDED_TYPES,)from repowise.core.persistence.models import Page, PageVersion-from repowise.core.pipeline.persist import sweep_retired_page_types+from repowise.core.pipeline.persist import sweep_retired_pagesfrom tests.unit.persistence.helpers import insert_repo@@ -51,13 +57,62 @@ async def test_every_retired_type_is_swept(async_session):async_session.add(_page_row(repo.id, page_type, f"leftover-{page_type}"))await async_session.flush()- swept = await sweep_retired_page_types(async_session, repo.id)+ swept = await sweep_retired_pages(async_session, repo.id)assert sorted(swept) == sorted(f"{t}:leftover-{t}" for t in retired)remaining = (await async_session.execute(select(Page.page_type))).scalars().all()assert not set(remaining) & set(retired)+async def test_every_retired_id_is_swept(async_session):+ """The id-keyed half, driven by the table for the same reason."""+ repo = await insert_repo(async_session)+ retired = sorted(RETIRED_IDS)+ assert retired, "no ids are retired; this half of the sweep has nothing to do"+ for page_id in retired:+ page_type, target = page_id.split(":", 1)+ async_session.add(_page_row(repo.id, page_type, target))+ await async_session.flush()++ swept = await sweep_retired_pages(async_session, repo.id)++ assert sorted(swept) == retired+ left = set((await async_session.execute(select(Page.id))).scalars().all())+ assert not left & set(retired)+++async def test_surviving_onboarding_slots_are_not_swept_with_their_retired_siblings(+ async_session,+):+ """The reason this sweep cannot be keyed on page type.++ Every onboarding page shares ``page_type='onboarding'``. If the retired+ slots were reached by type, the whole orientation collection would go with+ them — silently, on the next update, with no way to tell from the store+ that it had happened.+ """+ from repowise.core.generation.onboarding.slots import ONBOARDING_ORDER, PROMOTED_SLOTS++ repo = await insert_repo(async_session)+ survivors = [+ f"onboarding/{slot}"+ for slot in ONBOARDING_ORDER+ if slot not in set(PROMOTED_SLOTS.values())+ ]+ assert survivors, "orientation has no generated slots left to protect"+ for target in survivors:+ async_session.add(_page_row(repo.id, "onboarding", target))+ for page_id in sorted(RETIRED_IDS):+ page_type, target = page_id.split(":", 1)+ async_session.add(_page_row(repo.id, page_type, target))+ await async_session.flush()++ await sweep_retired_pages(async_session, repo.id)++ left = set((await async_session.execute(select(Page.id))).scalars().all())+ assert left == {f"onboarding:{target}" for target in survivors}++async def test_live_page_types_are_untouched(async_session):"""The sweep names types, not rows, so a live page must not be caught."""repo = await insert_repo(async_session)@@ -67,7 +122,7 @@ async def test_live_page_types_are_untouched(async_session):async_session.add(_page_row(repo.id, "repo_overview", "demo"))await async_session.flush()- await sweep_retired_page_types(async_session, repo.id)+ await sweep_retired_pages(async_session, repo.id)survivors = set((await async_session.execute(select(Page.id))).scalars().all())assert survivors == {@@ -97,7 +152,7 @@ async def test_versions_go_with_the_page(async_session):)await async_session.flush()- await sweep_retired_page_types(async_session, repo.id)+ await sweep_retired_pages(async_session, repo.id)left = (await async_session.execute(select(PageVersion.page_id))).scalars().all()assert left == []@@ -111,7 +166,7 @@ async def test_other_repositories_are_not_touched(async_session):async_session.add(_page_row(theirs.id, "architecture_diagram", "theirs"))await async_session.flush()- swept = await sweep_retired_page_types(async_session, mine.id)+ swept = await sweep_retired_pages(async_session, mine.id)assert swept == ["architecture_diagram:mine"]survivors = (await async_session.execute(select(Page.id))).scalars().all()@@ -123,4 +178,4 @@ async def test_a_clean_index_sweeps_nothing(async_session):async_session.add(_page_row(repo.id, "module_page", "src/ingest"))await async_session.flush()- assert await sweep_retired_page_types(async_session, repo.id) == []+ assert await sweep_retired_pages(async_session, repo.id) == []diff --git a/tests/unit/server/mcp/test_answer_candidates.py b/tests/unit/server/mcp/test_answer_candidates.pyindex 45ff85568..5c050a313 100644--- a/tests/unit/server/mcp/test_answer_candidates.py+++ b/tests/unit/server/mcp/test_answer_candidates.py@@ -77,7 +77,7 @@ def test_a_page_that_names_no_file_is_not_offered_as_one():"""hits = [{"page_type": "module_page", "target_path": "pkg/cmd/release"},- {"page_type": "onboarding", "target_path": "onboarding/guided_tour"},+ {"page_type": "onboarding", "target_path": "onboarding/how_it_works"},{"page_type": "scc_page", "target_path": "scc-8f21ab"},{"page_type": "file_page", "target_path": "pkg/cmd/release/list.go"},]diff --git a/tests/unit/server/mcp/test_search.py b/tests/unit/server/mcp/test_search.pyindex 7919b9fec..336dfef49 100644--- a/tests/unit/server/mcp/test_search.py+++ b/tests/unit/server/mcp/test_search.py@@ -406,7 +406,7 @@ class TestClassifyHitKind:from repowise.server.mcp_server.tool_search import _classify_hit_kindassert _classify_hit_kind("", "repo_overview") == "doc"- assert _classify_hit_kind("onboarding/guided_tour", "onboarding") == "doc"+ assert _classify_hit_kind("onboarding/how_it_works", "onboarding") == "doc"def test_file_page_paths_classify_by_role(self):from repowise.server.mcp_server.tool_search import _classify_hit_kind@@ -1005,7 +1005,7 @@ class TestSearchCandidates:await _seed_page("module_page:pkg/cmd/release", "pkg/cmd/release", "module_page")await _seed_page(- "onboarding:onboarding/guided_tour", "onboarding/guided_tour", "onboarding"+ "onboarding:onboarding/how_it_works", "onboarding/how_it_works", "onboarding")await _seed_page("file_page:pkg/cmd/release/list.go", "pkg/cmd/release/list.go")await _seed_page("file_page:pkg/cmd/release/http.go", "pkg/cmd/release/http.go")@@ -1016,10 +1016,10 @@ class TestSearchCandidates:"module_page:pkg/cmd/release", "Release", "module_page", "pkg/cmd/release", 0.90),_mk_result(- "onboarding:onboarding/guided_tour",+ "onboarding:onboarding/how_it_works","Guided Tour","onboarding",- "onboarding/guided_tour",+ "onboarding/how_it_works",0.80,),_mk_result(diff --git a/tests/unit/server/mcp/test_search_candidates.py b/tests/unit/server/mcp/test_search_candidates.pyindex 0392768dc..7aca4ad3e 100644--- a/tests/unit/server/mcp/test_search_candidates.py+++ b/tests/unit/server/mcp/test_search_candidates.py@@ -48,7 +48,7 @@ class TestFilePathOf:def test_scc_overview_and_onboarding_pages_name_no_file(self):assert file_path_of("scc_page", "scc-8f21ab") is Noneassert file_path_of("repo_overview", "cli") is None- assert file_path_of("onboarding", "onboarding/guided_tour") is None+ assert file_path_of("onboarding", "onboarding/how_it_works") is Noneassert file_path_of("layer_page", "presentation") is Nonedef test_an_empty_target_path_resolves_to_nothing(self):@@ -77,7 +77,7 @@ class TestHitFilePath:class TestFileCandidates:def test_pages_that_name_no_file_do_not_consume_a_slot(self):hits = [- _page("onboarding", "onboarding/guided_tour"),+ _page("onboarding", "onboarding/how_it_works"),_page("file_page", "a.go"),_page("module_page", "pkg/cmd"),_page("file_page", "b.go"),@@ -118,7 +118,7 @@ class TestFileCandidates:_page("file_page", "a.go"),_page("scc_page", "scc-11"),_page("repo_overview", "cli"),- _page("onboarding", "onboarding/guided_tour"),+ _page("onboarding", "onboarding/how_it_works"),_page("file_page", "b.go"),_page("file_page", "c.go"),]@@ -133,7 +133,7 @@ class TestFileCandidates:assert len(file_candidates(hits, limit=10)) == 10def test_no_files_reached_yields_no_block(self):- hits = [_page("repo_overview", "cli"), _page("onboarding", "onboarding/guided_tour")]+ hits = [_page("repo_overview", "cli"), _page("onboarding", "onboarding/how_it_works")]assert file_candidates(hits, limit=10) == []def test_empty_pool_yields_no_block(self):