Skip to content

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

feat(update): say which orientation page an index has never been offered (#1288)

Raghav Chamadiyaff2bb2019831
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
index db2851abe..151c051de 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
@@ -17,10 +17,12 @@ from repowise.cli._repo_session import open_repo_db
from repowise.cli.helpers import (
config_fingerprint,
get_head_commit,
+ load_config,
load_state,
run_async,
save_config,
save_state,
+ stamp_offered_slots,
)
from repowise.cli.state_persistence import build_kg_state, save_knowledge_graph_json
from repowise.core.docs_mode import docs_mode_state_fields
@@ -359,6 +361,14 @@ def save_full_state_and_config(
# A full init/index genuinely brings the store to the current store format
# (its pages are the concept tree), so stamp the terminal version rather
# than clamping at the reindex gate a routine persist would stop below.
+ #
+ # The same run offered every registered onboarding slot its signals, so
+ # record which ones. A slot absent from a fresh index was refused by its
+ # gate, not missed, and the missing-slot notice must not report it.
+ # Read back rather than passed in: init writes ``enable_onboarding: false``
+ # to config.yaml before it reaches here, and only when it is false, so the
+ # file is the run's own answer by the time this runs.
+ stamp_offered_slots(state, enabled=bool(load_config(repo_path).get("enable_onboarding", True)))
save_state(repo_path, state, full_index=True)
if kg is not None:
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/command.py b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
index 0bf610ed6..d9204267e 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/command.py
@@ -800,6 +800,13 @@ def run_update(
)
except Exception as exc:
log.debug("reindex_notice_skipped", error=str(exc))
+ # Up-to-date code does not mean a complete wiki either. This path is
+ # where an orientation page registered after the index was built is
+ # most likely to go unmentioned forever: it returns before the
+ # generation code, so nothing else in the run can notice.
+ from .slot_notice import surface_missing_slots
+
+ surface_missing_slots(repo_path, emitter=emitter, dry_run=dry_run)
if emitter is not None:
emitter.done(
ok=True,
@@ -922,6 +929,13 @@ def run_update(
except Exception as exc: # never block a routine update on the upgrade layer
log.debug("store_upgrade_skipped", error=str(exc))
+ # An orientation page registered after this index was built cannot arrive
+ # below, because this run's parsed_files is the changed-file slice, so name
+ # the command that does reach it. Says nothing when there is nothing to say.
+ from .slot_notice import surface_missing_slots
+
+ surface_missing_slots(repo_path, emitter=emitter, dry_run=dry_run)
+
render_header(repo_path, base_ref, head)
if emitter is not None:
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd/slot_notice.py b/packages/cli/src/repowise/cli/commands/update_cmd/slot_notice.py
new file mode 100644
index 000000000..018b68bde
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/update_cmd/slot_notice.py
@@ -0,0 +1,194 @@
+"""Telling a user that their index predates an orientation page.
+
+An onboarding slot registered after an index was built cannot arrive on the
+incremental ``repowise update`` path, and must not try: that run's
+``parsed_files`` is the changed-file slice, and the slot gates read whole-repo
+signals. A Glossary mined from a truncated vocabulary scan is worse than an
+absent one, which is why ``update_cmd.command`` sets ``file_pages_only`` and
+the repo-wide levels are skipped.
+
+``repowise update --full`` is the command that does reach them. It re-parses
+the whole repository, rehydrates the graph from SQL instead of re-resolving it,
+runs the onboarding level with every registered slot, and keeps the index.
+Measured on ``test-repos/microdot`` (2026-08-04): a slot deleted from a
+persisted index came back on the next ``update --full``, and the resulting
+orientation was identical to a fresh ``repowise init`` of the same repository.
+So the remedy this module names is ``--full``, never a re-index. Nobody should
+be told to throw away an index to gain a page.
+
+**A missing row is not the same as a missing slot.** Three of microdot's five
+registered slots are refused by their own signal gates on every run, fresh or
+full; the glossary, for one, mines no house vocabulary there at all. Reporting
+those would promise a page that no command can deliver. So the comparison is
+against :data:`~repowise.cli.helpers.ONBOARDING_SLOTS_OFFERED_KEY`, the slots
+the last whole-repo run actually evaluated, and only a slot that has never been
+evaluated here is reported. An index written before that key existed has
+no such record, and there the persisted rows are the only evidence available;
+the notice degrades to naming what has no row, and one ``--full`` resolves it
+either way by writing the record.
+
+Driven by ``iter_specs()`` rather than a second list, for the reason the
+retirement sweep reads the retirement tables: a slot added without this
+following is exactly the state the notice exists to report.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+from repowise.cli.helpers import ONBOARDING_SLOTS_OFFERED_KEY, console, load_state
+from repowise.cli.upgrade import SHOWN_NOTICES_KEY
+
+log = structlog.get_logger(__name__)
+
+#: Ledger entry recording that this missing-slot set has been surfaced. Shares
+#: the reindex recommendation's ledger, since it is the same question ("has
+#: this store been told?"), namespaced so the two entries cannot collide.
+_LEDGER_PREFIX = "onboarding_slots:"
+
+
+def _registered_slots() -> list[str]:
+ from repowise.core.generation.onboarding import iter_specs
+
+ return [spec.slot for spec in iter_specs()]
+
+
+def _slot_title(slot: str) -> str:
+ from repowise.core.generation.onboarding.slots import SLOT_TITLES
+
+ return SLOT_TITLES.get(slot, slot)
+
+
+async def _persisted_slots(repo_path: Path) -> set[str]:
+ """Onboarding slots this store holds a page for.
+
+ Only consulted for an index written before the offered-slots record
+ existed, where it is the sole evidence of what was ever built.
+
+ Scoped to this repository rather than to the whole store: the database is
+ repo-local by default but ``REPOWISE_DB_URL`` can point several repos at
+ one, and an unscoped read would let another repo's Glossary silence this
+ one's notice.
+ """
+ from sqlalchemy import select
+
+ from repowise.cli.helpers import get_db_url_for_repo
+ from repowise.core.generation.onboarding import target_path
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.models import Page, Repository
+
+ by_target = {target_path(slot): slot for slot in _registered_slots()}
+ engine = create_engine(get_db_url_for_repo(repo_path))
+ try:
+ session_factory = create_session_factory(engine)
+ async with get_session(session_factory) as session:
+ repo_id = (
+ await session.execute(
+ select(Repository.id).where(Repository.local_path == str(repo_path))
+ )
+ ).scalar_one_or_none()
+ if repo_id is None:
+ # No repository row: this store has never been written for this
+ # path, so it holds no evidence either way.
+ raise LookupError(f"no repository row for {repo_path}")
+ rows = (
+ await session.execute(
+ select(Page.target_path).where(
+ Page.repository_id == repo_id,
+ Page.page_type == "onboarding",
+ )
+ )
+ ).scalars().all()
+ finally:
+ await engine.dispose()
+ return {by_target[target] for target in rows if target in by_target}
+
+
+def missing_slots(repo_path: Path) -> list[str]:
+ """Registered onboarding slots this index has never been offered.
+
+ Returns them in ``ONBOARDING_ORDER``, which is reading order, so a notice
+ listing several names them the way the wiki would.
+ """
+ from repowise.cli.helpers import load_config, run_async
+
+ if not bool(load_config(repo_path).get("enable_onboarding", True)):
+ # The user turned the collection off. Every slot is "missing" and none
+ # of it is news.
+ return []
+
+ registered = _registered_slots()
+ state = load_state(repo_path)
+ offered = state.get(ONBOARDING_SLOTS_OFFERED_KEY)
+ if isinstance(offered, list):
+ known = {str(slot) for slot in offered}
+ else:
+ try:
+ known = run_async(_persisted_slots(repo_path))
+ except Exception as exc:
+ # No record and no readable store: nothing can be claimed honestly.
+ log.debug("onboarding_slot_notice.store_unreadable", error=str(exc))
+ return []
+ return [slot for slot in registered if slot not in known]
+
+
+def surface_missing_slots(repo_path: Path, *, emitter: Any, dry_run: bool) -> None:
+ """Name the orientation pages this index has never been offered, once.
+
+ Read-only except for the shown-notice ledger, so it is safe on the no-op
+ ("already up to date") path as well as the main one. That path is the one
+ that matters most here, because a repository with no new commits never
+ reaches the generation code at all and would otherwise never be told.
+
+ Interactive-terminal only, matching the reindex recommendation: a
+ background post-commit update must not burn the one-shot into a log nobody
+ reads. The ledger is keyed by the missing set itself, so registering a
+ further slot later says so again rather than staying quiet.
+ """
+ try:
+ missing = missing_slots(repo_path)
+ except Exception as exc: # a notice must never break an update
+ log.debug("onboarding_slot_notice.skipped", error=str(exc))
+ return
+ if not missing:
+ return
+ if not (console.is_terminal and emitter is None):
+ return
+
+ key = _LEDGER_PREFIX + ",".join(sorted(missing))
+ state = load_state(repo_path)
+ shown = state.get(SHOWN_NOTICES_KEY)
+ if isinstance(shown, list) and key in shown:
+ return
+
+ titles = ", ".join(_slot_title(slot) for slot in missing)
+ noun = "page" if len(missing) == 1 else "pages"
+ console.print(f"[yellow]Orientation {noun} not in this index:[/yellow] {titles}")
+ # "the ones this repository has the signal for", not "these": on a store
+ # with no offered-slots record the rows are the only evidence, and a slot
+ # can be absent because its gate refused the repository rather than because
+ # nothing ever offered it. Promising the page outright would be a lie on
+ # every such repo, and there is no way to tell the two apart from here.
+ console.print(
+ "[dim]A routine update only regenerates what changed, so it cannot build "
+ "these. [bold]repowise update --full[/bold] re-reads the whole repository "
+ "and writes the ones it has the signal for. It keeps the index.[/dim]"
+ )
+
+ if dry_run:
+ return
+ try:
+ from repowise.cli.helpers import save_state
+
+ state = load_state(repo_path)
+ shown = state.get(SHOWN_NOTICES_KEY)
+ shown = list(shown) if isinstance(shown, list) else []
+ if key not in shown:
+ shown.append(key)
+ state[SHOWN_NOTICES_KEY] = shown
+ save_state(repo_path, state)
+ except Exception as exc: # a ledger write must never break a command
+ log.debug("onboarding_slot_notice.record_failed", error=str(exc))
diff --git a/packages/cli/src/repowise/cli/commands/upgrade_flow.py b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
index 52b0a4136..e0bedd672 100644
--- a/packages/cli/src/repowise/cli/commands/upgrade_flow.py
+++ b/packages/cli/src/repowise/cli/commands/upgrade_flow.py
@@ -42,6 +42,7 @@ from repowise.cli.helpers import (
resolve_reasoning,
run_async,
save_state,
+ stamp_offered_slots,
)
from repowise.core.docs_mode import docs_mode_state_fields
@@ -511,6 +512,11 @@ def upgrade_to_full(
# `update --full` regenerates the whole wiki (concept tree included), so it
# brings the store to the terminal store format the same way a full init
# does. Stamp it as such rather than clamping at the reindex gate.
+ #
+ # This is also the run that answers the missing-slot notice: it evaluates
+ # every registered onboarding slot against whole-repo signals, so after it
+ # there is nothing left for the notice to report.
+ stamp_offered_slots(state, enabled=config.enable_onboarding)
save_state(repo_path, state, full_index=True)
if embedder_name and embedder_name != cfg.get("embedder"):
from repowise.cli.helpers import save_config_partial
diff --git a/packages/cli/src/repowise/cli/helpers.py b/packages/cli/src/repowise/cli/helpers.py
index db74cdc2b..0c8e9f07e 100644
--- a/packages/cli/src/repowise/cli/helpers.py
+++ b/packages/cli/src/repowise/cli/helpers.py
@@ -195,6 +195,42 @@ def load_state(repo_path: Path) -> dict[str, Any]:
return {}
+#: Slots the last whole-repo generation put in front of this repository's
+#: signals, which is not the same as the slots that produced a page. The two
+#: differ, and only the first answers "has this index ever been offered a
+#: Glossary?".
+ONBOARDING_SLOTS_OFFERED_KEY = "onboarding_slots_offered"
+
+
+def stamp_offered_slots(state: dict[str, Any], *, enabled: bool = True) -> None:
+ """Record which onboarding slots this whole-repo run evaluated.
+
+ Only a run that generates the whole repository may call this: the slot
+ gates read whole-repo signals, so a scoped run that saw one changed file
+ has not offered anything to anything.
+
+ Written because a missing onboarding row has two causes that look identical
+ in a store and want opposite responses. A slot registered after this index
+ was built has never been evaluated here, and ``update --full`` would build
+ it; a slot that *was* evaluated and whose gate refused the repository will
+ be refused again by the same signals, and telling the user to spend a model
+ run on it is a lie. Measured on ``test-repos/microdot``: of the five
+ registered slots, two produce pages and three (``getting_started``,
+ ``active_landscape``, ``glossary``) are gate-skipped on every run, full or
+ fresh. A notice driven by the rows alone would name all three, forever, and
+ none of them would ever arrive.
+
+ ``enabled`` is the run's ``enable_onboarding``. A run with onboarding off
+ offered nothing, and recording otherwise would silence the notice for a
+ user who later turns it on.
+ """
+ from repowise.core.generation.onboarding import iter_specs
+
+ state[ONBOARDING_SLOTS_OFFERED_KEY] = (
+ sorted(spec.slot for spec in iter_specs()) if enabled else []
+ )
+
+
def save_state(repo_path: Path, state: dict[str, Any], *, full_index: bool = False) -> None:
"""Write *state* to ``.repowise/state.json``.
diff --git a/packages/server/src/repowise/server/schemas/pages.py b/packages/server/src/repowise/server/schemas/pages.py
index 0c9fc4328..e3545e36c 100644
--- a/packages/server/src/repowise/server/schemas/pages.py
+++ b/packages/server/src/repowise/server/schemas/pages.py
@@ -40,6 +40,33 @@ def _layer_stamp(obj: object, metadata: dict | None) -> tuple[str | None, str |
)
+def _is_chapter(obj: object, metadata: dict | None) -> bool:
+ """Whether this page heads a chapter, read off its metadata blob.
+
+ Promoted for the same reason as the layer stamp, and read the same way: a
+ chapter *is* a ``module_page`` and only its metadata says otherwise, so a
+ reader drawing from a summary listing shows it as an ordinary module that
+ happens to have children. That is the reader dead-end a chapter exists to
+ close.
+
+ Absent on every page written before chapters shipped, which reads as "not a
+ chapter" and leaves those wikis exactly as they render today.
+ """
+ if metadata is None:
+ raw = getattr(obj, "metadata_json", None) or ""
+ if "is_chapter" not in raw:
+ return False
+ try:
+ metadata = json.loads(raw)
+ except ValueError:
+ # Same call as the layer stamp makes: a blob that will not parse
+ # says nothing, rather than guessing a shape for the page.
+ return False
+ if not isinstance(metadata, dict):
+ return False
+ return bool(metadata.get("is_chapter"))
+
+
def _summary_fields(obj: object, metadata: dict | None = None) -> dict:
"""The part of a page row that costs nothing to send.
@@ -66,6 +93,7 @@ def _summary_fields(obj: object, metadata: dict | None = None) -> dict:
content_chars=len(obj.content or ""), # type: ignore[attr-defined]
layer_id=layer_id,
layer_name=layer_name,
+ is_chapter=_is_chapter(obj, metadata),
human_notes=obj.human_notes, # type: ignore[attr-defined]
parent_page_id=obj.parent_page_id, # type: ignore[attr-defined]
display_order=obj.display_order, # type: ignore[attr-defined]
@@ -109,6 +137,10 @@ class PageSummaryResponse(BaseModel):
# layers were stamped — both of which read as "ungrouped", not as an error.
layer_id: str | None = None
layer_name: str | None = None
+ # Whether this module page heads a chapter. A chapter shares its page type
+ # with the modules beneath it, so without this a listing cannot tell them
+ # apart and the reader labels a chapter "Module".
+ is_chapter: bool = False
human_notes: str | None = None
# Position in the wiki outline. Older rows carry no placement, which reads
# as a flat wiki and is what those rows actually describe.
diff --git a/packages/types/src/docs.ts b/packages/types/src/docs.ts
index ac8aae7a6..a525e5e83 100644
--- a/packages/types/src/docs.ts
+++ b/packages/types/src/docs.ts
@@ -57,6 +57,17 @@ export interface DocPageSummary {
*/
layer_id?: string | null;
layer_name?: string | null;
+ /**
+ * Whether this module page heads a chapter: a subsystem's landing page,
+ * with the module pages of its directory nested under it.
+ *
+ * Promoted out of `metadata` for the same reason as the layer stamp: a
+ * chapter's `page_type` is `module_page`, exactly like the pages beneath it,
+ * so a listing that drops the blob cannot tell a chapter from an ordinary
+ * module that happens to have children. Absent on every page written before
+ * chapters shipped, which reads as `false`.
+ */
+ is_chapter?: boolean;
human_notes: string | null;
/**
* Position in the wiki outline, computed once at generation time so every
diff --git a/packages/ui/__tests__/lib/page-types.test.ts b/packages/ui/__tests__/lib/page-types.test.ts
index 6881bc666..168b093e2 100644
--- a/packages/ui/__tests__/lib/page-types.test.ts
+++ b/packages/ui/__tests__/lib/page-types.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect } from "vitest";
import {
+ getPageLabel,
getPageTypeLabel,
isModelWrittenType,
isStubPage,
@@ -72,3 +73,35 @@ describe("getPageTypeLabel", () => {
expect(getPageTypeLabel("not_a_page_type")).toBe("not a page type");
});
});
+
+describe("getPageLabel", () => {
+ // A chapter shares `page_type` with the module pages nested under it, so the
+ // type alone calls both "Module" and the reader cannot tell a subsystem's
+ // landing page from one of its members.
+ it("calls a chapter a chapter", () => {
+ expect(getPageLabel({ page_type: "module_page", is_chapter: true })).toBe("Chapter");
+ });
+
+ it("calls an ordinary module a module", () => {
+ expect(getPageLabel({ page_type: "module_page" })).toBe("Module");
+ expect(getPageLabel({ page_type: "module_page", is_chapter: false })).toBe("Module");
+ });
+
+ it("ignores the flag on a type that cannot be a chapter", () => {
+ // Only the concept tree mints chapters. A stray flag on anything else is
+ // bad data, and labelling it "Chapter" would propagate the error.
+ expect(getPageLabel({ page_type: "file_page", is_chapter: true })).toBe("File");
+ });
+
+ it("agrees with getPageTypeLabel for every non-chapter page", () => {
+ for (const t of [...STRUCTURAL_TYPES, "repo_overview", "onboarding"]) {
+ expect(getPageLabel({ page_type: t })).toBe(getPageTypeLabel(t));
+ }
+ });
+
+ it("renders nothing rather than 'undefined' for a page with no type", () => {
+ expect(getPageLabel(null)).toBe("");
+ expect(getPageLabel(undefined)).toBe("");
+ expect(getPageLabel({})).toBe("");
+ });
+});
diff --git a/packages/ui/src/docs/docs-reader.tsx b/packages/ui/src/docs/docs-reader.tsx
index 9dc3cdbf3..592294bb5 100644
--- a/packages/ui/src/docs/docs-reader.tsx
+++ b/packages/ui/src/docs/docs-reader.tsx
@@ -11,7 +11,7 @@ import {
import type { DocPage, DocPageSummary } from "@repowise-dev/types/docs";
import { cn } from "../lib/cn";
import { formatRelativeTime, formatTokens } from "../lib/format";
-import { getPageTypeLabel } from "../lib/page-types";
+import { getPageLabel } from "../lib/page-types";
import { computeDocNav } from "./doc-nav";
import { filterMarkdownByPersona, type ReaderPersona } from "./reader-persona";
import { WikiMarkdown } from "../wiki/wiki-markdown";
@@ -406,7 +406,7 @@ function DocsReaderBody({
be untrue. */}
<div className="flex flex-wrap items-center gap-x-2 gap-y-1.5 text-[11px] text-[var(--color-text-tertiary)] mb-5">
<span className="font-mono text-[10px] uppercase tracking-[0.12em]">
- {getPageTypeLabel(page.page_type)}
+ {getPageLabel(page)}
</span>
<span aria-hidden className="opacity-40">&middot;</span>
<span className="text-[var(--color-text-secondary)]">
diff --git a/packages/ui/src/lib/page-types.ts b/packages/ui/src/lib/page-types.ts
index 4fe0797cf..b765c5e02 100644
--- a/packages/ui/src/lib/page-types.ts
+++ b/packages/ui/src/lib/page-types.ts
@@ -43,6 +43,26 @@ export function getPageTypeLabel(pageType: string): string {
return PAGE_TYPE_CONFIG[pageType]?.label ?? pageType.replace(/_/g, " ");
}
+/**
+ * What to call a page, given the page rather than only its type.
+ *
+ * A chapter is a `module_page`, deliberately: it is a module page with a
+ * better partition rather than an eleventh page type. So its type alone
+ * labels it "Module", which is what the modules nested *under* it are called
+ * too. `is_chapter` is the only thing that separates them, so anywhere a
+ * reader is told what a page is, it has to be read.
+ *
+ * Takes a partial so a caller holding a summary row, a full page, or a search
+ * hit can all pass what they have.
+ */
+export function getPageLabel(
+ page: { page_type?: string; is_chapter?: boolean } | null | undefined,
+): string {
+ if (!page?.page_type) return "";
+ if (page.is_chapter && page.page_type === "module_page") return "Chapter";
+ return getPageTypeLabel(page.page_type);
+}
+
// ---------------------------------------------------------------------------
// Model-written pages
// ---------------------------------------------------------------------------
diff --git a/tests/unit/cli/test_update_slot_notice.py b/tests/unit/cli/test_update_slot_notice.py
new file mode 100644
index 000000000..e02c16d5d
--- /dev/null
+++ b/tests/unit/cli/test_update_slot_notice.py
@@ -0,0 +1,246 @@
+"""The missing-orientation-page notice on the ``repowise update`` path.
+
+Three things it must get right, all of them measured on ``test-repos/microdot``
+before they were written down: it names ``--full`` and never a re-index, it
+says nothing when the last whole-repo run already offered every registered
+slot (microdot's own state: three of five slots are gate-skipped there on every
+run, fresh or full), and it is driven by ``iter_specs()`` rather than a list
+repeated here.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import pytest
+
+from repowise.cli.commands.update_cmd import slot_notice
+from repowise.cli.helpers import (
+ ONBOARDING_SLOTS_OFFERED_KEY,
+ load_state,
+ save_state,
+ stamp_offered_slots,
+)
+from repowise.core.generation.onboarding import iter_specs
+
+
+class _FakeTerminal:
+ """A console that reports as a terminal and records what was printed."""
+
+ is_terminal = True
+
+ def __init__(self) -> None:
+ self.lines: list[str] = []
+
+ def print(self, *args, **_kwargs) -> None:
+ self.lines.append(" ".join(str(a) for a in args))
+
+
+def console(monkeypatch) -> _FakeTerminal:
+ fake = _FakeTerminal()
+ monkeypatch.setattr(slot_notice, "console", fake)
+ return fake
+
+
+def _registered() -> list[str]:
+ return [spec.slot for spec in iter_specs()]
+
+
+# --- what counts as missing ------------------------------------------------
+
+
+def test_no_slot_is_missing_when_the_last_full_run_offered_them_all(tmp_path: Path) -> None:
+ state: dict = {}
+ stamp_offered_slots(state)
+ save_state(tmp_path, state)
+
+ assert slot_notice.missing_slots(tmp_path) == []
+
+
+def test_a_slot_registered_since_the_last_full_run_is_missing(tmp_path: Path) -> None:
+ registered = _registered()
+ assert len(registered) > 1, "this test needs at least two registered slots"
+ newcomer = registered[-1]
+
+ # The record a whole-repo run left before ``newcomer`` was registered.
+ save_state(tmp_path, {ONBOARDING_SLOTS_OFFERED_KEY: sorted(registered[:-1])})
+
+ assert slot_notice.missing_slots(tmp_path) == [newcomer]
+
+
+def test_a_gate_skipped_slot_is_not_reported(tmp_path: Path) -> None:
+ """The microdot case: offered, refused by its own gate, so no page.
+
+ Nothing any command can do changes that, so reporting it would promise a
+ page ``--full`` will not produce.
+ """
+ state: dict = {}
+ stamp_offered_slots(state) # every registered slot was evaluated...
+ save_state(tmp_path, state) # ...and this store holds no onboarding row.
+
+ assert slot_notice.missing_slots(tmp_path) == []
+
+
+def test_missing_slots_are_returned_in_reading_order(tmp_path: Path) -> None:
+ save_state(tmp_path, {ONBOARDING_SLOTS_OFFERED_KEY: []})
+
+ assert slot_notice.missing_slots(tmp_path) == _registered()
+
+
+def test_nothing_is_missing_when_onboarding_is_disabled(tmp_path: Path) -> None:
+ (tmp_path / ".repowise").mkdir(parents=True, exist_ok=True)
+ (tmp_path / ".repowise" / "config.yaml").write_text(
+ "enable_onboarding: false\n", encoding="utf-8"
+ )
+ save_state(tmp_path, {ONBOARDING_SLOTS_OFFERED_KEY: []})
+
+ assert slot_notice.missing_slots(tmp_path) == []
+
+
+def test_the_comparison_follows_the_registry(tmp_path: Path) -> None:
+ """Driven by ``iter_specs()``, not by a second list.
+
+ A slot registered without this module following is the exact state the
+ notice exists to report, so the registry has to be what it reads.
+ """
+ save_state(tmp_path, {ONBOARDING_SLOTS_OFFERED_KEY: []})
+
+ assert slot_notice.missing_slots(tmp_path) == [spec.slot for spec in iter_specs()]
+
+
+def test_an_index_with_no_record_falls_back_to_its_rows(tmp_path: Path) -> None:
+ """Every index built before the record existed takes this path.
+
+ There is no evidence of what was offered, so the rows are all there is:
+ the notice reports what has no page and one ``--full`` resolves it either
+ way, by writing the record. An index-only store holds no onboarding page
+ at all, so every registered slot is reported.
+ """
+ import asyncio
+ import subprocess
+
+ from repowise.core.pipeline.full_index import index_repo_full
+
+ repo = tmp_path / "repo"
+ repo.mkdir(parents=True)
+ for args in (
+ ("init",),
+ ("config", "user.email", "[email protected]"),
+ ("config", "user.name", "T"),
+ ):
+ subprocess.run(["git", *args], cwd=str(repo), capture_output=True, text=True)
+ (repo / "a.py").write_text("def alpha():\n return 1\n")
+ subprocess.run(["git", "add", "."], cwd=str(repo), capture_output=True, text=True)
+ subprocess.run(["git", "commit", "-m", "initial"], cwd=str(repo), capture_output=True, text=True)
+
+ asyncio.run(index_repo_full(repo)) # real store, keyless, no onboarding pages
+
+ state = load_state(repo)
+ assert ONBOARDING_SLOTS_OFFERED_KEY not in state
+
+ assert slot_notice.missing_slots(repo) == _registered()
+
+
+# --- what the user sees ----------------------------------------------------
+
+
+def test_notice_names_full_and_never_a_reindex(tmp_path: Path, console: _FakeTerminal) -> None:
+ save_state(tmp_path, {ONBOARDING_SLOTS_OFFERED_KEY: []})
+
+ slot_notice.surface_missing_slots(tmp_path, emitter=None, dry_run=False)
+
+ printed = " ".join(console.lines)
+ assert "repowise update --full" in printed
+ assert "index" in printed # it says the index is kept
+ for forbidden in ("re-index", "reindex", "repowise init"):
+ assert forbidden not in printed.lower().replace("--full", "")
+
+
+def test_notice_names_the_missing_pages_by_title(tmp_path: Path, console: _FakeTerminal) -> None:
+ from repowise.core.generation.onboarding import SLOT_GLOSSARY, SLOT_TITLES
+
+ offered = [slot for slot in _registered() if slot != SLOT_GLOSSARY]
+ save_state(tmp_path, {ONBOARDING_SLOTS_OFFERED_KEY: sorted(offered)})
+
+ slot_notice.surface_missing_slots(tmp_path, emitter=None, dry_run=False)
+
+ printed = " ".join(console.lines)
+ assert SLOT_TITLES[SLOT_GLOSSARY] in printed
+
+
+def test_notice_is_silent_when_nothing_is_missing(tmp_path: Path, console: _FakeTerminal) -> None:
+ state: dict = {}
+ stamp_offered_slots(state)
+ save_state(tmp_path, state)
+
+ slot_notice.surface_missing_slots(tmp_path, emitter=None, dry_run=False)
+
+ assert console.lines == []
+
+
+def test_notice_shows_once_per_missing_set(tmp_path: Path, console: _FakeTerminal) -> None:
+ registered = _registered()
+ save_state(tmp_path, {ONBOARDING_SLOTS_OFFERED_KEY: sorted(registered[:-1])})
+
+ slot_notice.surface_missing_slots(tmp_path, emitter=None, dry_run=False)
+ assert console.lines
+
+ console.lines.clear()
+ slot_notice.surface_missing_slots(tmp_path, emitter=None, dry_run=False)
+ assert console.lines == [] # the ledger suppresses the second showing
+
+ # A further slot registered later is news again: the ledger is keyed by the
+ # missing set, not by "this store has been told something once".
+ save_state(tmp_path, {ONBOARDING_SLOTS_OFFERED_KEY: sorted(registered[:-2])})
+ slot_notice.surface_missing_slots(tmp_path, emitter=None, dry_run=False)
+ assert console.lines
+
+
+def test_notice_is_silent_when_not_a_terminal(tmp_path: Path, monkeypatch) -> None:
+ class _NonTerminal(_FakeTerminal):
+ is_terminal = False
+
+ fake = _NonTerminal()
+ monkeypatch.setattr(slot_notice, "console", fake)
+ save_state(tmp_path, {ONBOARDING_SLOTS_OFFERED_KEY: []})
+
+ slot_notice.surface_missing_slots(tmp_path, emitter=None, dry_run=False)
+
+ assert fake.lines == []
+ # And a suppressed showing must not burn the one-shot.
+ monkeypatch.setattr(slot_notice, "console", _FakeTerminal())
+ assert slot_notice.missing_slots(tmp_path) == _registered()
+
+
+def test_dry_run_does_not_burn_the_one_shot(tmp_path: Path, console: _FakeTerminal) -> None:
+ save_state(tmp_path, {ONBOARDING_SLOTS_OFFERED_KEY: []})
+
+ slot_notice.surface_missing_slots(tmp_path, emitter=None, dry_run=True)
+ assert console.lines
+
+ console.lines.clear()
+ slot_notice.surface_missing_slots(tmp_path, emitter=None, dry_run=False)
+ assert console.lines
+
+
+# --- the stamp -------------------------------------------------------------
+
+
+def test_stamp_records_every_registered_slot(tmp_path: Path) -> None:
+ state: dict = {}
+ stamp_offered_slots(state)
+
+ assert state[ONBOARDING_SLOTS_OFFERED_KEY] == sorted(_registered())
+
+
+def test_stamp_records_nothing_when_onboarding_was_off(tmp_path: Path) -> None:
+ """A run with the collection disabled offered nothing.
+
+ Recording otherwise would silence the notice for a user who later turns it
+ back on and whose index has never seen a single slot.
+ """
+ state: dict = {}
+ stamp_offered_slots(state, enabled=False)
+
+ assert state[ONBOARDING_SLOTS_OFFERED_KEY] == []
diff --git a/tests/unit/server/test_pages.py b/tests/unit/server/test_pages.py
index e3054fe5c..af87d4428 100644
--- a/tests/unit/server/test_pages.py
+++ b/tests/unit/server/test_pages.py
@@ -135,6 +135,80 @@ async def test_list_pages_summary_has_no_layer_stamp_when_unstamped(
assert row["layer_name"] is None
+async def test_list_pages_summary_keeps_the_chapter_flag(client: AsyncClient, app) -> None:
+ """A chapter survives the summary trim, and an ordinary module stays one.
+
+ A chapter's page type is ``module_page``, exactly like the pages nested
+ under it, so this flag is the only thing that separates them. Left inside
+ the dropped metadata blob, every reader drawing from a listing labels a
+ subsystem's landing page "Module".
+ """
+ repo = await create_test_repo(client)
+ repo_id = repo["id"]
+ async with get_session(app.state.session_factory) as session:
+ await crud.upsert_page(
+ session,
+ page_id="module_page:src/core",
+ repository_id=repo_id,
+ page_type="module_page",
+ title="Core",
+ content="body",
+ target_path="src/core",
+ source_hash="abc123",
+ model_name="mock",
+ provider_name="mock",
+ metadata={"is_chapter": True},
+ )
+ await crud.upsert_page(
+ session,
+ page_id="module_page:src/core/health",
+ repository_id=repo_id,
+ page_type="module_page",
+ title="Health",
+ content="body",
+ target_path="src/core/health",
+ source_hash="def456",
+ model_name="mock",
+ provider_name="mock",
+ )
+
+ resp = await client.get(
+ "/api/pages", params={"repo_id": repo_id, "fields": "summary"}
+ )
+ assert resp.status_code == 200
+ by_id = {row["id"]: row for row in resp.json()}
+ assert "metadata" not in by_id["module_page:src/core"]
+ assert by_id["module_page:src/core"]["is_chapter"] is True
+ assert by_id["module_page:src/core/health"]["is_chapter"] is False
+
+
+async def test_full_page_row_also_carries_the_chapter_flag(client: AsyncClient, app) -> None:
+ """The two response models share ``_summary_fields``, so this cannot drift."""
+ repo = await create_test_repo(client)
+ repo_id = repo["id"]
+ async with get_session(app.state.session_factory) as session:
+ await crud.upsert_page(
+ session,
+ page_id="module_page:src/core",
+ repository_id=repo_id,
+ page_type="module_page",
+ title="Core",
+ content="body",
+ target_path="src/core",
+ source_hash="abc123",
+ model_name="mock",
+ provider_name="mock",
+ metadata={"is_chapter": True},
+ )
+
+ resp = await client.get("/api/pages", params={"repo_id": repo_id})
+ row = resp.json()[0]
+ assert row["is_chapter"] is True
+ assert row["metadata"]["is_chapter"] is True
+
+
@pytest.mark.asyncio
async def test_list_pages_rejects_unknown_fields(client: AsyncClient, app) -> None:
repo_id, _ = await _create_page(client, app.state.session_factory)