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(generation): subject chapters, so a subsystem has a page a reader can land on (#1282)

Raghav Chamadiyabb23fb537bba
diff --git a/packages/core/src/repowise/core/generation/concept_tree/naming.py b/packages/core/src/repowise/core/generation/concept_tree/naming.py
index 731303dfb..9b80eba7b 100644
--- a/packages/core/src/repowise/core/generation/concept_tree/naming.py
+++ b/packages/core/src/repowise/core/generation/concept_tree/naming.py
@@ -25,6 +25,8 @@ from __future__ import annotations
import json
import re
+from collections import Counter
+from collections.abc import Container, Sequence
from dataclasses import dataclass
from typing import Any
@@ -130,7 +132,166 @@ def deterministic_title(group: ConceptGroup, layer_label: str = "") -> str:
return title
-def disambiguate_titles(titled: list[tuple[str, str]]) -> list[str]:
+# A chapter's subject is the directory it heads. ``core`` is the one stop
+# segment that survives here: as one of two segments it adds nothing ("Core
+# Ingestion" says no more than "Ingestion"), but as the whole subject it is
+# exactly what a reader means by the core package. The rest are containers with
+# no subject of their own, and no path ever ends at one on purpose.
+_CHAPTER_CONTAINERS = (_STOP_SEGMENTS - {"core"}) | {"dist", "build"}
+
+# A route parameter: ``[id]``, ``[...slug]``, ``{id}``, ``(group)``, ``:id``.
+# It names a variable rather than a subject, so a chapter at
+# ``app/repos/[id]`` is about repos.
+_DYNAMIC_SEGMENT = re.compile(r"^([\[{(].*[]})]|:.+)$")
+
+
+def _chapter_subject(target_path: str) -> str:
+ """The deepest segment of *target_path* that names something."""
+ segments = [s for s in target_path.split("/") if s]
+ if not segments:
+ return ""
+ for segment in reversed(segments):
+ if segment.lower() in _CHAPTER_CONTAINERS or _DYNAMIC_SEGMENT.match(segment):
+ continue
+ return segment
+ # Every segment is a container. The last one is still where the reader is.
+ return segments[-1]
+
+
+def _house_casing(segment: str, child_titles: Sequence[str]) -> str:
+ """How the project writes *segment* in its own page titles, or ``""``.
+
+ The children were named before their chapter needs a name, so they are the
+ one place that says whether this repository writes ``ui`` as "UI" or "Ui".
+ Taken from them rather than from an acronym list, which would be a rule
+ tuned to the repositories whose acronyms happened to be on it.
+ """
+ counts: Counter[str] = Counter()
+ for title in child_titles:
+ for word in re.split(r"[^A-Za-z0-9]+", title):
+ # An all-lowercase occurrence says nothing this function was asked
+ # about — a title carrying the word mid-sentence, or one quoting a
+ # path — and taking it would open a page title in lower case.
+ if word.lower() == segment.lower() and not word.islower():
+ counts[word] += 1
+ if not counts:
+ return ""
+ top = max(counts.values())
+ # Ties break on the string so an unchanged repository names it the same way
+ # every run.
+ return sorted(word for word, n in counts.items() if n == top)[0]
+
+
+def chapter_title(target_path: str, child_titles: Sequence[str] = ()) -> str:
+ """Name the chapter heading *target_path*, given the titles beneath it.
+
+ A chapter is not a leaf and must not be named like one. The namer, shown a
+ chapter's directory, names the loose files at that directory's root and
+ then that name stands over everything below: "Blast Radius UI" heading
+ eighteen UI modules, "Core Service Utilities" heading six core subsystems.
+ That is worse than no chapter at all, because the name now claims to head
+ things it does not describe. Measured, not assumed — a hint telling the
+ model which groups were chapters and what they contained changed two names
+ of nine and neither of those two.
+
+ What a chapter reliably *is* is the place: the directory, and the reader's
+ own word for it. So it gets that word and the word "Overview", and the only
+ thing the children are asked for is how this project spells it. Costs no
+ call, cannot drift between runs, and reproduces the four chapter names on
+ this repository's own index that read best today.
+ """
+ segment = _chapter_subject(target_path)
+ if not segment:
+ # A chapter at the repository root. It has no segment to name it by and
+ # the overview page already covers the repository, so say where it is
+ # rather than inventing a subject.
+ return "Repository Overview"
+ return f"{_house_casing(segment, child_titles) or _humanise(segment)} Overview"
+
+
+def nearest_chapter(target_path: str, chapters: Container[str]) -> str | None:
+ """The closest ancestor directory of *target_path* holding a chapter.
+
+ Strictly an ancestor, so a chapter never heads itself. Nearest rather than
+ topmost because chapters nest. The tree walks the same rule when it parents
+ a page, and a title drawn from a different set of children than the tree
+ shows beneath it is a title about the wrong pages.
+ """
+ cursor = target_path
+ while "/" in cursor:
+ cursor = cursor.rsplit("/", 1)[0]
+ if cursor in chapters:
+ return cursor
+ return None
+
+
+def chapter_titles(leaves: dict[str, str], chapters: Sequence[str]) -> dict[str, str]:
+ """Title every directory in *chapters* from the leaves it heads.
+
+ *leaves* maps a leaf page's directory to its title — every page that owns
+ files, including a directory that is both a chapter and a leaf. Titles are
+ made unique against each other and against the leaves, which do not move: a
+ leaf may carry a model-written name and a chapter yielding to it is the
+ cheaper of the two collisions to resolve.
+ """
+ keys = set(chapters)
+ kids: dict[str, list[str]] = {c: [] for c in keys}
+ for target_path, title in leaves.items():
+ parent = nearest_chapter(target_path, keys)
+ if parent is not None:
+ kids[parent].append(title)
+ ordered = sorted(keys)
+ named = disambiguate_titles(
+ [(chapter_title(c, kids[c]), c) for c in ordered],
+ reserved={t for path, t in leaves.items() if path not in keys},
+ )
+ return dict(zip(ordered, named, strict=True))
+
+
+def scc_where(members: list[str], *, max_parts: int = 2) -> str:
+ """Where a dependency cycle lives, from its members' directories.
+
+ A cycle page was titled by the hash of its member list — ``Circular
+ Dependency: scc-0fa5536d91fc``. Nothing a reader could search for names a
+ hash, which is why every one of them on this repository's index had no
+ inbound link at all: the title said only that the page existed.
+
+ Naming it after the place it happens in is the cheapest fix that keeps the
+ page and its id. Structural and repo-agnostic: the directories the members
+ share, or the two most-represented ones when they share nothing, which is
+ the honest description of a cycle that spans subsystems.
+
+ Returns an empty string when there is nothing to say, so the caller keeps
+ the id rather than rendering a title that claims less than the id does.
+ """
+ dirs = [m.rsplit("/", 1)[0] for m in members if "/" in m]
+ if not dirs:
+ return ""
+
+ common = dirs[0].split("/")
+ for d in dirs[1:]:
+ parts = d.split("/")
+ common = [a for a, b in zip(common, parts, strict=False) if a == b]
+ if not common:
+ break
+ if common:
+ # Everything is under one directory, so name that directory. The last
+ # two segments for the same reason concept titles use them: the tail
+ # carries the meaning and the head is usually a container.
+ meaningful = [s for s in common if s.lower() not in _STOP_SEGMENTS] or common
+ return " ".join(_humanise(s) for s in meaningful[-2:])
+
+ # No shared root: the cycle crosses subsystems, which is the interesting
+ # thing about it. Name the biggest two, in size order, ties on path so the
+ # title does not move between runs on an unchanged repository.
+ counts = Counter(d.split("/")[0] for d in dirs)
+ top = sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:max_parts]
+ return " and ".join(_humanise(seg) for seg, _n in top)
+
+
+def disambiguate_titles(
+ titled: list[tuple[str, str]], *, reserved: set[str] | None = None
+) -> list[str]:
"""Make a set of ``(title, target_path)`` pairs' titles unique.
Path-derived names collide easily: two packages that each hold a ``ui``
@@ -143,25 +304,36 @@ def disambiguate_titles(titled: list[tuple[str, str]]) -> list[str]:
already used, and falls back to its full target path if even that
repeats. Input order does not matter: the pairs are resolved in path
order, so the same set always produces the same names.
+
+ *reserved* names are already taken by pages not in *titled*, so a caller
+ naming a second population against a settled one yields to it rather than
+ renaming it. Passing the settled titles in *titled* instead would let this
+ rename them — and a caller that then keeps only its own slice silently
+ discards those renames, leaving the collision it asked to resolve.
+
+ Case is not a difference. "UI Overview" over "Ui Overview" is two rows a
+ reader reads as one thing written twice, which is the whole condition this
+ function exists to remove, and it is the reading the planner's own
+ disambiguation has always taken.
"""
order = sorted(range(len(titled)), key=lambda i: titled[i][1])
out = list(titled)
- used: set[str] = set()
+ used: set[str] = {t.lower() for t in (reserved or ())}
for i in order:
title, target = titled[i]
- if title not in used:
- used.add(title)
+ if title.lower() not in used:
+ used.add(title.lower())
out[i] = (title, target)
continue
segments = [s for s in target.split("/") if s]
candidate = title
for extra in reversed(segments[:-2] or segments[:-1]):
candidate = f"{_humanise(extra)} {title}"
- if candidate not in used:
+ if candidate.lower() not in used:
break
- if candidate in used:
+ if candidate.lower() in used:
candidate = f"{title} ({target})"
- used.add(candidate)
+ used.add(candidate.lower())
out[i] = (candidate, target)
return [t for t, _ in out]
diff --git a/packages/core/src/repowise/core/generation/page_generator/levels.py b/packages/core/src/repowise/core/generation/page_generator/levels.py
index 17051c561..c3b642864 100644
--- a/packages/core/src/repowise/core/generation/page_generator/levels.py
+++ b/packages/core/src/repowise/core/generation/page_generator/levels.py
@@ -187,15 +187,45 @@ async def build_level2_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
return coros
+def _scc_titles(scc_groups: list[Any]) -> dict[str, str]:
+ """``scc id -> title``, unique across the run's cycles.
+
+ Names are computed here rather than per page because uniqueness is a
+ property of the set: several cycles through one subsystem all describe
+ themselves the same way — three of this repository's seventeen are
+ "Ingestion Resolvers" — and two identical rows in the tree are
+ indistinguishable to a reader.
+
+ Resolved over the whole set even when the run emits a subset, so a scoped
+ run gives a cycle the same name a full one does.
+ """
+ from ..concept_tree.naming import disambiguate_titles, scc_where
+
+ pairs: list[tuple[str, str]] = []
+ for scc_id, scc_files in scc_groups:
+ where = scc_where(sorted(scc_files))
+ pairs.append((f"Circular Dependency: {where}" if where else "Circular Dependency", scc_id))
+ # Ties break on the cycle's own id, which is a hash of its members, so the
+ # discriminator is stable for an unchanged cycle.
+ titles = disambiguate_titles(pairs)
+ return {
+ scc_id: (title if title != "Circular Dependency" else f"Circular Dependency: {scc_id}")
+ for title, (_t, scc_id) in zip(titles, pairs, strict=True)
+ }
+
+
def build_level3_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
"""Level 3 (scc_page), allow-set filtered."""
gen = run.gen
coros: list[tuple[str, Any]] = []
+ titles = _scc_titles(list(run.sel_scc_groups))
for scc_id, scc_files in run.sel_scc_groups:
fc_list = [run.file_page_contexts[f] for f in scc_files if f in run.file_page_contexts]
pid = compute_page_id("scc_page", scc_id)
if run._emit(pid):
- coros.append((pid, gen.generate_scc_page(scc_id, scc_files, fc_list)))
+ coros.append(
+ (pid, gen.generate_scc_page(scc_id, scc_files, fc_list, title=titles.get(scc_id)))
+ )
return coros
@@ -224,7 +254,11 @@ def build_level4_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
gen = run.gen
coros: list[tuple[str, Any]] = []
for mg in run.sel_module_groups:
- fcs = [run.file_page_contexts[fp] for fp in mg.file_paths if fp in run.file_page_contexts]
+ # Read from the wider set: a chapter's prose is about its whole
+ # subsystem, while ``file_paths`` is the narrower, disjoint claim on who
+ # documents what. They are the same list for every leaf.
+ material = getattr(mg, "context_paths", ()) or mg.file_paths
+ fcs = [run.file_page_contexts[fp] for fp in material if fp in run.file_page_contexts]
if not fcs:
# A concept group whose files all failed to build a context. The
# partition is total, so this is a hole in the tree rather than a
@@ -233,7 +267,7 @@ def build_level4_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
log.warning(
"module_page.skipped_no_file_contexts",
target_path=mg.key,
- members=len(mg.file_paths),
+ members=len(material),
)
continue
page_id = compute_page_id("module_page", mg.key)
@@ -268,7 +302,10 @@ def build_level4_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
if getattr(mg, "is_rollup", False)
else None
),
- owns_files=not getattr(mg, "is_rollup", False),
+ # Ownership is what ``file_paths`` says, not what the page's
+ # shape implies: a chapter that is also a leaf directory
+ # heads its children *and* documents its own loose files.
+ owns_files=bool(mg.file_paths),
),
)
)
diff --git a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
index 0bc44299c..a46be740c 100644
--- a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
+++ b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
@@ -408,6 +408,12 @@ class _GenerationRun:
scope=scope_of.get(mg.structural_key, mg.scope),
)
)
+ # A chapter is named from the leaves under it, and those leaves have
+ # just been renamed, so the names it was given at selection are stale.
+ # Same rule, same function; the model never names a chapter directly.
+ from ..selection.selector import retitle_chapters
+
+ groups_out = retitle_chapters(groups_out)
# Generation order is left alone: it is summed PageRank, so the most
# central subsystem is written first and lands in the store earliest.
# Where the reader meets each page is ``order``, applied by the tree.
diff --git a/packages/core/src/repowise/core/generation/page_generator/pertype.py b/packages/core/src/repowise/core/generation/page_generator/pertype.py
index 42fb40618..1bbfe05cb 100644
--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py
+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py
@@ -249,11 +249,13 @@ class PerTypeGenerationMixin:
# group. Placement resolves file ownership from this list, so the
# dropped files would be parented somewhere else entirely, and the two
# records of what the page covers would disagree.
- # A rollup page sits above its child concept pages and owns no files of
- # its own: its members already belong to the leaves below it, so
- # claiming them here would parent those files twice and scramble the
- # tree. It keeps an empty member list, which is exactly what
- # ``assign_page_tree`` reads as "owns nothing".
+ # A chapter with no group of its own owns no files: everything beneath
+ # it already belongs to the leaves below, so claiming them here would
+ # parent those files twice and scramble the tree. It keeps an empty
+ # member list, which is exactly what ``assign_page_tree`` reads as
+ # "owns nothing". A chapter that *is* also a leaf directory owns its own
+ # loose files and passes ``owns_files``, which is why this is keyed on
+ # ownership rather than on ``is_rollup``.
if owns_files:
covered = sorted(members) if members else sorted(fc.file_path for fc in file_contexts)
else:
@@ -269,6 +271,16 @@ class PerTypeGenerationMixin:
wiki renumbers it and mints no new pages.
"""
page.metadata["file_paths"] = covered
+ if is_rollup:
+ # What makes this page a chapter rather than a leaf, recorded
+ # so the tree can nest its children under it. Derivable from
+ # the page set — a directory with two or more module pages
+ # immediately below it — but deriving it there would be a
+ # second place computing the rule that decided the page, and
+ # the two would have to agree forever. Absent on a page written
+ # before this shipped, which reads as "leaf" and leaves those
+ # wikis flat rather than guessing.
+ page.metadata["is_chapter"] = True
if section:
page.metadata["concept_section"] = section
page.metadata["concept_order"] = order
@@ -327,10 +339,24 @@ class PerTypeGenerationMixin:
scc_id: str,
scc_files: list[str],
file_contexts: list[FilePageContext],
+ title: str | None = None,
) -> GeneratedPage:
+ from ..concept_tree.naming import scc_where
+
ctx = self._assembler.assemble_scc_page(scc_id, scc_files, file_contexts)
members = sorted(scc_files)
- page = self._structural_scc_page(ctx, scc_id, f"Circular Dependency: {scc_id}")
+ # Titled by where the cycle is, not by the hash of its member list. The
+ # id keeps the hash, so nothing is redirected and no link breaks; only
+ # the words a reader and a search see change.
+ #
+ # The caller names the whole set at once, because uniqueness is a
+ # property of the set. This fallback is for a caller that has one
+ # cycle and no set — the name is still better than the hash, and the
+ # collision it cannot see is one two identical names would have had.
+ if not title:
+ where = scc_where(members)
+ title = f"Circular Dependency: {where}" if where else f"Circular Dependency: {scc_id}"
+ page = self._structural_scc_page(ctx, scc_id, title)
page.metadata["file_paths"] = members
return page
diff --git a/packages/core/src/repowise/core/generation/page_generator/structural.py b/packages/core/src/repowise/core/generation/page_generator/structural.py
index 51b2369c2..380c30c63 100644
--- a/packages/core/src/repowise/core/generation/page_generator/structural.py
+++ b/packages/core/src/repowise/core/generation/page_generator/structural.py
@@ -484,6 +484,10 @@ class StructuralRenderMixin:
title=title,
template="scc_page.j2",
ctx=ctx,
+ # The heading says where the cycle is. The page id stays the hash
+ # and the page still prints it, so a log line or a link naming one
+ # still resolves.
+ page_title=title,
# Ranked by how many cross-edges each file carries: the highest
# is the cheapest place to break the cycle. Computed here rather
# than in Jinja because the template language makes grouping
diff --git a/packages/core/src/repowise/core/generation/page_tree.py b/packages/core/src/repowise/core/generation/page_tree.py
index 83844f7b4..9ad8f09d1 100644
--- a/packages/core/src/repowise/core/generation/page_tree.py
+++ b/packages/core/src/repowise/core/generation/page_tree.py
@@ -339,6 +339,33 @@ def assign_page_tree(
if page.parent_page_id and page.parent_page_id.startswith("module_page:"):
claimed.setdefault(page.parent_page_id, []).append(page.target_path)
+ # A chapter heads the module pages under its directory, so those pages hang
+ # off it instead of off their layer. Without this the chapter renders as a
+ # sibling of the pages it links down to, and the tree is a flat listing with
+ # one row that happens to say "Overview" — which is the reader dead-end the
+ # chapter exists to close.
+ chapter_at: dict[str, str] = {
+ page.target_path: page.page_id
+ for page in module_pages
+ if page.metadata.get("is_chapter") and page.target_path
+ }
+
+ def nearest_chapter(target_path: str) -> str | None:
+ """The closest ancestor directory with a chapter page, if any.
+
+ Strictly an ancestor, so a chapter never parents itself and the walk
+ cannot cycle. Nearest rather than topmost because chapters nest: a
+ module under ``core/analysis/health`` belongs to Health, which belongs
+ to Analysis, which belongs to Core.
+ """
+ cursor = target_path
+ while "/" in cursor:
+ cursor = cursor.rsplit("/", 1)[0]
+ found = chapter_at.get(cursor)
+ if found:
+ return found
+ return None
+
for page in module_pages:
members = page.metadata.get("file_paths") or page.metadata.get("files") or []
members = [m for m in members if isinstance(m, str)]
@@ -362,8 +389,10 @@ def assign_page_tree(
borrowed.extend(m for m in child_members if isinstance(m, str))
members = borrowed
module_layer = _dominant_layer(members, layer_of_file)
+ # Stamped either way: the reader-facing tree groups by this, and a page
+ # that has found a chapter still belongs to a layer.
stamp_layer(page, module_layer)
- page.parent_page_id = layer_parent(module_layer)
+ page.parent_page_id = nearest_chapter(page.target_path) or layer_parent(module_layer)
# A spotlight belongs to the file it documents: "path/to/file.py::Symbol".
# The file's own page may not exist: selection can spotlight a symbol in a
diff --git a/packages/core/src/repowise/core/generation/related_pages.py b/packages/core/src/repowise/core/generation/related_pages.py
index 697c0e365..515cd1ce4 100644
--- a/packages/core/src/repowise/core/generation/related_pages.py
+++ b/packages/core/src/repowise/core/generation/related_pages.py
@@ -14,6 +14,7 @@ prose never names its collaborators is still connected to them.
from __future__ import annotations
import json
+from collections import Counter
from typing import Any
import structlog
@@ -67,6 +68,114 @@ def _module_siblings(
return siblings
+def _module_of_path(pages: list[Any]) -> dict[str, str]:
+ """``file path -> the module page id that documents it``.
+
+ Read from the pages' own recorded membership rather than from the run's
+ module groups, because the groups exist only during a full generation and
+ this has to work on the persistence-layer backfill too — which is how
+ every update flavor heals.
+
+ Ties break on the lowest page id, the same rule ``assign_page_tree`` uses
+ to decide file ownership. Two records of who documents a file that
+ disagreed would put a page's neighbours somewhere its children are not.
+ """
+ out: dict[str, str] = {}
+ for page in pages:
+ if getattr(page, "page_type", "") != "module_page":
+ continue
+ for member in page.metadata.get("file_paths") or []:
+ if not isinstance(member, str):
+ continue
+ current = out.get(member)
+ if current is None or page.page_id < current:
+ out[member] = page.page_id
+ return out
+
+
+def _module_adjacency(
+ module_of: dict[str, str],
+ import_edges: list[tuple[str, str]] | None,
+ git_meta_map: dict[str, dict] | None,
+) -> dict[str, dict[str, Counter]]:
+ """Per-module neighbour counts, keyed ``module id -> reason -> Counter``.
+
+ A module's neighbours are its members' neighbours, lifted to whichever
+ module documents them and counted. The count is the evidence: two
+ subsystems joined by forty import edges are more related than two joined
+ by one, and nothing else here carries a weight that means anything at
+ module scale.
+
+ Edges inside a module are dropped — a module is not related to itself, and
+ on a large group the self-edges would otherwise swamp every real one.
+ """
+ out: dict[str, dict[str, Counter]] = {}
+
+ def bump(mod: str, reason: str, other: str) -> None:
+ if not other or other == mod:
+ return
+ out.setdefault(mod, {}).setdefault(reason, Counter())[other] += 1
+
+ for src, dst in import_edges or []:
+ src_mod, dst_mod = module_of.get(src), module_of.get(dst)
+ if not src_mod or not dst_mod:
+ continue
+ bump(src_mod, "imports", dst_mod)
+ bump(dst_mod, "imported-by", src_mod)
+
+ for path, meta in (git_meta_map or {}).items():
+ mod = module_of.get(path)
+ if not mod:
+ continue
+ for partner, _count in _co_change_partners(meta):
+ bump(mod, "co-changes-with", module_of.get(partner, ""))
+
+ return out
+
+
+def _inherit_subtree_neighbours(
+ pages: list[Any], adjacency: dict[str, dict[str, Counter]]
+) -> None:
+ """Give a chapter that owns no files the neighbours of its subtree.
+
+ A chapter heading a subsystem whose files all belong to the pages beneath
+ it has no members, so it has no edges of its own and would be the one page
+ in the wiki with nothing across — which is the opposite of its job. Its
+ neighbours are its subsystem's: the union of its descendants' edges, minus
+ everything that lands back inside the subtree, because an edge to a page
+ it already links down to is not news.
+
+ Mutates *adjacency* in place. Only chapters with no members of their own
+ are filled; one that documents loose files has real edges already.
+ """
+ targets = {
+ page.page_id: page.target_path
+ for page in pages
+ if getattr(page, "page_type", "") == "module_page" and page.target_path
+ }
+ empty = [
+ page
+ for page in pages
+ if getattr(page, "page_type", "") == "module_page"
+ and not (page.metadata.get("file_paths") or [])
+ and page.target_path
+ ]
+ for page in empty:
+ prefix = page.target_path + "/"
+ inside = {
+ pid for pid, tp in targets.items() if tp == page.target_path or tp.startswith(prefix)
+ }
+ merged: dict[str, Counter] = {}
+ for pid in inside:
+ for reason, counts in adjacency.get(pid, {}).items():
+ bucket = merged.setdefault(reason, Counter())
+ for target, n in counts.items():
+ if target not in inside:
+ bucket[target] += n
+ if merged:
+ adjacency[page.page_id] = merged
+
+
def attach_related_pages(
pages: list[GeneratedPage],
*,
@@ -76,11 +185,17 @@ def attach_related_pages(
pagerank: dict[str, float] | None = None,
prior_page_ids: Any = None,
) -> None:
- """Populate ``metadata['related_pages']`` on file-backed pages.
+ """Populate ``metadata['related_pages']`` on file-backed and module pages.
Mutates each :class:`GeneratedPage` in place. Idempotent — recomputed
from scratch on every run.
+ A module page's neighbours are its members' neighbours lifted to module
+ scale and counted. Module pages were excluded while the pass was gated on
+ ``FILE_BACKED_PAGE_TYPES``, which left the pages that most need to name
+ their collaborators as the only ones that never did: a reader on a
+ subsystem page could reach its files and its parent, and nothing across.
+
``prior_page_ids`` widens resolution beyond this run's page set: on an
incremental update only the affected pages are regenerated, so without
the persisted ids every neighbor outside the diff would fail to resolve
@@ -109,10 +224,21 @@ def attach_related_pages(
siblings = _module_siblings(module_groups)
+ # Module neighbours, computed once over the whole page set rather than per
+ # page. Skipped entirely when no module page is present, which is the
+ # common case on a scoped file-page run.
+ module_of = _module_of_path(pages)
+ module_adj = (
+ _module_adjacency(module_of, import_edges, git_meta_map) if module_of else {}
+ )
+ if module_adj:
+ _inherit_subtree_neighbours(pages, module_adj)
+
attached_pages = 0
total_entries = 0
for page in pages:
- if page.page_type not in _FILE_BACKED or not page.target_path:
+ is_module = page.page_type == "module_page"
+ if (page.page_type not in _FILE_BACKED and not is_module) or not page.target_path:
continue
path = page.target_path
@@ -121,20 +247,36 @@ def attach_related_pages(
link.get("target_page_id") for link in page.metadata.get("wiki_links") or []
}
- candidates: dict[str, list[tuple[str, float]]] = {
- # Order within a reason: strongest evidence first. Import edges
- # carry no weight of their own, so central targets go first.
- "imports": sorted(
- ((p, pr.get(p, 0.0)) for p in imports_of.get(path, ())),
- key=lambda t: -t[1],
- ),
- "imported-by": sorted(
- ((p, pr.get(p, 0.0)) for p in imported_by.get(path, ())),
- key=lambda t: -t[1],
- ),
- "co-changes-with": _co_change_partners((git_meta_map or {}).get(path)),
- "same-module": [(p, 0.0) for p in siblings.get(path, ())],
- }
+ if is_module:
+ by_reason = module_adj.get(page.page_id, {})
+ candidates = {
+ # Already page ids, so resolution is a no-op below. Weight is
+ # the number of edges crossing the boundary.
+ reason: [
+ (target, float(n))
+ for target, n in by_reason.get(reason, Counter()).most_common()
+ ]
+ # ``same-module`` is meaningless for a module: it *is* the
+ # module. Left out rather than emitted empty, so the reason
+ # priority below skips straight past it.
+ for reason in ("imports", "imported-by", "co-changes-with")
+ }
+ candidates["same-module"] = []
+ else:
+ candidates = {
+ # Order within a reason: strongest evidence first. Import edges
+ # carry no weight of their own, so central targets go first.
+ "imports": sorted(
+ ((p, pr.get(p, 0.0)) for p in imports_of.get(path, ())),
+ key=lambda t: -t[1],
+ ),
+ "imported-by": sorted(
+ ((p, pr.get(p, 0.0)) for p in imported_by.get(path, ())),
+ key=lambda t: -t[1],
+ ),
+ "co-changes-with": _co_change_partners((git_meta_map or {}).get(path)),
+ "same-module": [(p, 0.0) for p in siblings.get(path, ())],
+ }
seen: set[str] = {page.page_id} | prose_targets
related: list[dict] = []
@@ -143,7 +285,7 @@ def attach_related_pages(
for target_path, weight in candidates[reason]:
if kept >= _PER_REASON_CAP or len(related) >= _TOTAL_CAP:
break
- target_id = index.resolve(target_path)
+ target_id = target_path if is_module else index.resolve(target_path)
if target_id is None or target_id in seen:
continue
seen.add(target_id)
diff --git a/packages/core/src/repowise/core/generation/selection/selector.py b/packages/core/src/repowise/core/generation/selection/selector.py
index dedb06ea0..057c779aa 100644
--- a/packages/core/src/repowise/core/generation/selection/selector.py
+++ b/packages/core/src/repowise/core/generation/selection/selector.py
@@ -9,7 +9,7 @@ emitted.
from __future__ import annotations
from collections import Counter
-from dataclasses import dataclass, field
+from dataclasses import dataclass, field, replace
from pathlib import Path
from typing import Any
@@ -20,6 +20,8 @@ from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTR
from ..concept_tree.grouping import ConceptGroup, group_files
from ..concept_tree.naming import (
_humanise,
+ chapter_title,
+ chapter_titles,
deterministic_scope,
deterministic_title,
disambiguate_titles,
@@ -85,10 +87,24 @@ class ModuleGroup:
#: outline planner. Threaded to the renderer so the opener can situate the
#: page against its siblings. Empty on the deterministic path until named.
scope: str = ""
- #: A rollup page overviews a subsystem directory whose detail lives on the
- #: child concept pages below it. It carries its members only for context and
- #: owns none of them, so the leaves keep their files.
+ #: A rollup page heads the subsystem directory whose detail lives on the
+ #: child concept pages below it. It still owns whatever ``file_paths``
+ #: holds — a directory that has children *and* loose files of its own is
+ #: one page that does both, because both would otherwise be
+ #: ``module_page:{that directory}`` and only one page can have an id.
is_rollup: bool = False
+ #: Files the renderer may read to describe the page, beyond the ones it
+ #: owns. A rollup sets this to its whole subsystem so the prose can be
+ #: about the subsystem while ``file_paths`` stays the disjoint ownership
+ #: claim. Empty means "the same files it owns", which is every leaf.
+ #:
+ #: The split exists because three consumers read ``file_paths`` as an
+ #: ownership claim and assume the partition is disjoint — the tree's
+ #: ``module_of_file``, the incremental cascade's ``module_page_of``, and
+ #: ``related_pages``' sibling map. Widening ``file_paths`` for context
+ #: silently broke all three: a rollup out-claimed its own leaves for every
+ #: file in the subtree.
+ context_paths: tuple[str, ...] = ()
@dataclass
@@ -485,11 +501,17 @@ def _build_module_groups(inputs: SelectionInputs) -> ConceptCandidates:
for g in groups
]
)
+ # Which directories head a subsystem. Computed before the groups are built
+ # so a directory that is both a chapter and a leaf becomes one page rather
+ # than colliding with itself on ``module_page:{dir}``.
+ chapters = _chapter_members(groups, files)
+
scored: list[tuple[float, ModuleGroup]] = []
for group, title in zip(groups, titles, strict=True):
langs = Counter(lang_of.get(m, "") for m in group.members)
langs.pop("", None)
score = sum(inputs.pagerank.get(m, 0.0) for m in group.members)
+ subsystem = chapters.get(group.target_path)
scored.append(
(
score,
@@ -508,11 +530,21 @@ def _build_module_groups(inputs: SelectionInputs) -> ConceptCandidates:
# Filled here so the deterministic path carries a scope
# sentence; the naming call overwrites it with a written one
# when a provider is present.
- scope=deterministic_scope(group),
+ scope=(
+ _chapter_scope(group.target_path, owns=True)
+ if subsystem
+ else deterministic_scope(group)
+ ),
+ is_rollup=subsystem is not None,
+ context_paths=tuple(subsystem or ()),
),
)
)
- scored.extend(_build_rollup_groups(groups, files, lang_of, inputs.pagerank))
+ scored.extend(_build_rollup_groups(chapters, groups, files, lang_of, inputs.pagerank))
+ # Last, because a chapter is named from the leaves beneath it and they all
+ # have to exist first.
+ retitled = retitle_chapters([mg for _, mg in scored])
+ scored = [(score, mg) for (score, _), mg in zip(scored, retitled, strict=True)]
scored.sort(key=lambda x: (-x[0], x[1].key))
return ConceptCandidates(scored=scored, groups=groups, layer_labels=layer_labels)
@@ -525,96 +557,156 @@ def _build_module_groups(inputs: SelectionInputs) -> ConceptCandidates:
_ROLLUP_MAX_MEMBER_FRACTION = 0.5
-def _build_rollup_groups(
- groups: list[ConceptGroup],
- files: list[str],
- lang_of: dict[str, str],
- pagerank: dict[str, float],
-) -> list[tuple[float, ModuleGroup]]:
- """Emit one overview page per parent directory that owns several concept pages.
+def _chapter_scope(parent: str, *, owns: bool) -> str:
+ """The scope sentence for a chapter, on the deterministic path."""
+ segment = parent.rsplit("/", 1)[-1] if "/" in parent else parent
+ lead = (
+ f"Heads the {_humanise(segment)} subsystem and links to the concept pages "
+ "documenting its parts"
+ )
+ if owns:
+ return (
+ f"{lead}; the files directly under this directory are documented here and "
+ "the rest of the detail lives on those child pages."
+ )
+ return f"{lead}; the detail lives on those child pages, not here."
+
+
+def _chapter_members(groups: list[ConceptGroup], files: list[str]) -> dict[str, list[str]]:
+ """Directories that head a subsystem → every production file beneath them.
The partition splits a large subsystem into path-local leaves, so a
directory such as ``.../ingestion`` gets no page of its own — only its
children do. A reader asking "what is the ingestion subsystem" then lands on
a file, not the subsystem, and a directory-level retrieval query has nothing
to match against, because directory-level retrieval matches a page to a
- directory by exact ``target_path`` equality. This adds a page whose
- ``target_path`` is exactly that parent directory: an overview that names its
- child pages and links down to them from its body.
+ directory by exact ``target_path`` equality. A chapter is a page whose
+ ``target_path`` is exactly that parent directory: it names its child pages
+ and links down to them from its body.
The rule is purely structural and repo-agnostic: a parent is eligible when at
- least two leaf concept pages are its *immediate* children and no leaf already
- claims that directory. With leaves at mixed depths several ancestor levels can
- each qualify, so two guards keep the set sane: a parent covering more than
- ``_ROLLUP_MAX_MEMBER_FRACTION`` of the repository is left to the repository
- overview, and colliding titles are disambiguated the same way leaf titles are.
-
- A rollup carries its subsystem's files only so the renderer has real material
- to summarise; it owns none of them (``is_rollup`` → empty ``file_paths``), so
- the leaves below keep their files and nothing is documented twice. In the nav
- tree it currently sits alongside its children under their shared layer rather
- than nesting them; the body still links down via ``child_pages``. True tree
- nesting is a deferred nicety, not a correctness requirement.
+ least two leaf concept pages are its *immediate* children. With leaves at
+ mixed depths several ancestor levels can each qualify, which is intended —
+ chapters nest — but one guard keeps the set sane: a parent covering more than
+ ``_ROLLUP_MAX_MEMBER_FRACTION`` of the repository is not a subsystem
+ overview, it is the repository overview under another name, and that page
+ already exists.
+
+ Eligibility deliberately does **not** exclude a parent that is itself a leaf
+ group. Both pages would be ``module_page:{parent}`` and only one page can
+ have an id, so excluding it was the only way to avoid a collision — but it
+ excluded exactly the directories a reader most wants a chapter for. On this
+ repository it suppressed nine of thirteen, including one heading eighteen
+ child pages. Such a parent becomes a single page that both owns its own
+ loose files and heads its children; see ``ModuleGroup.context_paths`` for how
+ ownership stays disjoint while the prose still covers the subsystem.
All paths here are POSIX-normalised upstream (the grouper lowercases
separators), so the ``/`` splits below are safe.
"""
total = len(files)
- leaf_targets = {g.target_path for g in groups}
- direct_children: dict[str, list[ConceptGroup]] = {}
+ child_count: Counter[str] = Counter()
for g in groups:
tp = g.target_path
- if "/" not in tp:
- continue
- parent = tp.rsplit("/", 1)[0]
- direct_children.setdefault(parent, []).append(g)
-
- # First pass: which parents qualify, and over what members. Titles are
- # computed in a second pass so they can be disambiguated as a set.
- candidates: list[tuple[str, list[str]]] = []
- for parent, children in sorted(direct_children.items()):
- if len(children) < 2 or parent in leaf_targets:
+ if "/" in tp:
+ child_count[tp.rsplit("/", 1)[0]] += 1
+
+ out: dict[str, list[str]] = {}
+ for parent, kids in sorted(child_count.items()):
+ if kids < 2:
continue
members = sorted(f for f in files if f.startswith(parent + "/"))
if not members or (total and len(members) > _ROLLUP_MAX_MEMBER_FRACTION * total):
continue
- candidates.append((parent, members))
+ out[parent] = members
+ return out
+
+
+def retitle_chapters(groups: list[ModuleGroup]) -> list[ModuleGroup]:
+ """Name every chapter after the subsystem it heads, not after its own files.
+
+ Called twice on a keyed run: once here, over the deterministic titles, and
+ once after the namer answers, because the leaf titles it is derived from
+ have changed by then. The rule is the same both times and lives in one
+ place, so the two cannot disagree. See
+ :func:`~..concept_tree.naming.chapter_title` for why a chapter is named
+ from its place rather than by the model.
- # Disambiguate overview titles against each other exactly as leaf titles are,
- # so two same-named subsystems in different packages ("Components Overview"
- # under packages/web and packages/vscode) do not render as identical rows.
- def _base_title(parent: str) -> str:
- segment = parent.rsplit("/", 1)[-1] if "/" in parent else parent
- return f"{_humanise(segment)} Overview".strip()
+ A leaf is a group that owns files; a chapter that owns none is a pure
+ rollup. A directory that is both keeps one page and takes the chapter name,
+ because the name a reader sees stands over the whole subtree whatever else
+ that page also documents.
- titles = disambiguate_titles([(_base_title(p), p) for p, _ in candidates])
+ The scope sentence comes back with the title, for the same reason. A model
+ shown a chapter's directory writes about the loose files at its root, so a
+ chapter that took its scope from that call would open by promising the
+ reader a page about those files and then be a page about the subsystem.
+ """
+ chapters = [mg.key for mg in groups if mg.is_rollup]
+ if not chapters:
+ return groups
+ titles = chapter_titles({mg.key: mg.display for mg in groups if mg.file_paths}, chapters)
+ return [
+ replace(
+ mg,
+ display=titles[mg.key],
+ scope=_chapter_scope(mg.key, owns=bool(mg.file_paths)),
+ )
+ if mg.is_rollup and mg.key in titles
+ else mg
+ for mg in groups
+ ]
+
+
+def _build_rollup_groups(
+ chapters: dict[str, list[str]],
+ groups: list[ConceptGroup],
+ files: list[str],
+ lang_of: dict[str, str],
+ pagerank: dict[str, float],
+) -> list[tuple[float, ModuleGroup]]:
+ """Chapter pages for the directories that are *not* already a leaf group.
+
+ A chapter whose directory is also a leaf is built by the caller, in the same
+ loop as every other leaf, so it keeps that group's structural key and its
+ section, both of which are keyed on the identity the namer already gave it.
+ Only the directories with no group of their own need a page synthesised
+ here, and those own no files.
+
+ The title set here is provisional: :func:`retitle_chapters` runs over every
+ chapter once the leaves exist and settles both kinds together, including
+ making them unique.
+ """
+ pending = sorted(set(chapters) - {g.target_path for g in groups})
+ if not pending:
+ return []
rollups: list[tuple[float, ModuleGroup]] = []
- for (parent, members), title in zip(candidates, titles, strict=True):
+ for parent in pending:
+ title = chapter_title(parent)
+ members = chapters[parent]
langs = Counter(lang_of.get(m, "") for m in members)
langs.pop("", None)
- segment = parent.rsplit("/", 1)[-1] if "/" in parent else parent
- score = sum(pagerank.get(m, 0.0) for m in members)
rollups.append(
(
- score,
+ sum(pagerank.get(m, 0.0) for m in members),
ModuleGroup(
key=parent,
display=title,
language=langs.most_common(1)[0][0] if langs else "unknown",
- file_paths=tuple(members),
+ # Owns nothing: every file beneath it belongs to one of the
+ # leaves below. The subsystem reaches the renderer through
+ # ``context_paths`` instead.
+ file_paths=(),
label=None,
cohesion=None,
# Hashed over the full subsystem with a distinct prefix so a
- # rollup can never collide with a leaf whose members are a
+ # chapter can never collide with a leaf whose members are a
# subset of these, and so the sweep tracks it as its own row.
structural_key=member_structural_key(members, prefix="concept-rollup"),
- scope=(
- f"Overviews the {_humanise(segment)} subsystem as a whole and "
- "links to the concept pages documenting its parts; the detail "
- "lives on those child pages, not here."
- ),
+ scope=_chapter_scope(parent, owns=False),
is_rollup=True,
+ context_paths=tuple(members),
),
)
)
diff --git a/packages/core/src/repowise/core/generation/templates/scc_page.j2 b/packages/core/src/repowise/core/generation/templates/scc_page.j2
index f565e661a..3caeb1edb 100644
--- a/packages/core/src/repowise/core/generation/templates/scc_page.j2
+++ b/packages/core/src/repowise/core/generation/templates/scc_page.j2
@@ -5,10 +5,19 @@
advice on breaking the cycle; the decouple ranking below is the
structural stand-in for it.
-#}
-# Circular Dependency: {{ ctx.scc_id }}
+{#- ``default(..., true)`` so an absent *or* empty title both fall back: the
+ caller names the whole set at once and a caller that does not is still
+ entitled to a page. #}
+# {{ page_title | default("Circular Dependency: " ~ ctx.scc_id, true) }}
{{ ctx.files | length }} files import each other in a loop, directly or transitively. Nothing in this group can be loaded, tested or extracted without the rest of it.
+{#- The id is no longer in the heading, and it is what logs, links and the
+ dependency tooling call this cycle, so it is stated once rather than being
+ findable only in the URL. #}
+
+**Cycle id:** `{{ ctx.scc_id }}`
+
## Files in the cycle
{# Capped, here and in the two listings below: a test-suite cycle routed
through a shared conftest can run to 80+ files and 200+ edges, and a page
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index fbc447f28..9dfe4bdf6 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -639,6 +639,72 @@ 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.
+
+ 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 —
+ nothing emits one and no failure mode can make anything emit one — so the
+ question 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
+ somewhere 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
+ function was written to clear.
+
+ That state is the reason this exists. The architecture diagram merged into
+ the overview and layer pages became grouping rows in the tree, both with
+ redirects registered — but ``architecture_diagram`` is not structurally
+ keyed, so no sweep ever covered it, and ``layer_page`` was only swept by a
+ full run. An index that has only been updated incrementally since therefore
+ still serves both. On this repository the retired diagram was the
+ 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).
+ """
+ from sqlalchemy import delete, select
+
+ from repowise.core.generation.page_redirects import (
+ 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:
+ return []
+
+ stale = (
+ (
+ await session.execute(
+ select(Page.id).where(
+ Page.repository_id == repo_id, Page.page_type.in_(retired)
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ for i in range(0, len(stale), _PRUNE_CHUNK):
+ batch = stale[i : i + _PRUNE_CHUNK]
+ await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
+ await session.execute(
+ delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch))
+ )
+ if stale:
+ logger.info(
+ "retired_page_types_swept",
+ repo_id=repo_id,
+ count=len(stale),
+ types=retired,
+ )
+ return list(stale)
+
+
async def _sweep_stale_generated_pages(
session: Any,
repo_id: str,
@@ -1289,6 +1355,9 @@ async def persist_pipeline_result(
getattr(result, "authoritative_page_types", None),
getattr(result, "preserved_page_ids", None),
)
+ # 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)
# 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.py
index 726cca089..1f1921ef4 100644
--- a/packages/core/src/repowise/core/pipeline/scoped_generation.py
+++ b/packages/core/src/repowise/core/pipeline/scoped_generation.py
@@ -208,6 +208,7 @@ async def execute_scoped_generation(
from repowise.core.pipeline import run_generation
from repowise.core.pipeline.persist import (
mark_page_ids_stale,
+ sweep_retired_page_types,
sweep_superseded_generated_pages,
)
@@ -248,6 +249,12 @@ async def execute_scoped_generation(
swept_page_ids = await sweep_superseded_generated_pages(
session, repo_id, generated_pages
)
+ # Rows of a page type that no longer exists. Safe on a scoped run
+ # precisely because it does not ask what the run produced: nothing can
+ # 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)
# 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/tests/unit/generation/test_concept_naming_wiring.py b/tests/unit/generation/test_concept_naming_wiring.py
index 5572236a8..6a6ddd821 100644
--- a/tests/unit/generation/test_concept_naming_wiring.py
+++ b/tests/unit/generation/test_concept_naming_wiring.py
@@ -172,6 +172,62 @@ async def test_a_run_that_writes_no_concept_page_does_not_name_one(tmp_path):
assert provider.naming_calls == 0, "an incremental run paid for a naming call"
+def _write_repo_with_a_chapter(repo_path):
+ """A repository holding one directory that heads a subsystem.
+
+ ``src/ingestion`` has three subdirectories large enough to be groups of
+ their own plus a loose file, so it is both a leaf and a chapter. The other
+ packages keep it a minority of the repository, or the near-repo-wide guard
+ would skip it.
+ """
+ repo_path.mkdir(parents=True, exist_ok=True)
+ for sub in ("languages", "graph", "resolvers"):
+ (repo_path / "src" / "ingestion" / sub).mkdir(parents=True, exist_ok=True)
+ for i in range(12):
+ (repo_path / "src" / "ingestion" / sub / f"mod{i}.py").write_text(
+ f"def {sub}_{i}() -> int:\n return {i}\n", encoding="utf-8"
+ )
+ (repo_path / "src" / "ingestion" / "loose.py").write_text(
+ "def loose() -> None:\n pass\n", encoding="utf-8"
+ )
+ for pkg in ("render", "storage", "transport", "reporting"):
+ (repo_path / "src" / pkg).mkdir(parents=True, exist_ok=True)
+ for i in range(12):
+ (repo_path / "src" / pkg / f"mod{i}.py").write_text(
+ f"def {pkg}_{i}() -> int:\n return {i}\n", encoding="utf-8"
+ )
+ return repo_path
+
+
+async def test_the_namer_never_titles_a_chapter(tmp_path):
+ """A chapter takes the name of the subsystem it heads, whatever the model said.
+
+ The model, shown a chapter's directory, names the loose files at its root,
+ and that name then stands over every page below it. Measured on this
+ repository's own index: telling the model which groups were chapters and
+ what each one contained changed two names of nine, and neither of the two
+ was a chapter that read wrong.
+ """
+ repo = _write_repo_with_a_chapter(tmp_path / "repo")
+ provider = NamingProvider(
+ _naming_payload_for({f"g{i:02d}": f"Title {i}" for i in range(1, 21)})
+ )
+
+ result = await _run(repo, provider)
+
+ pages = {p.page_id: p for p in _module_pages(result)}
+ chapter = pages.get("module_page:src/ingestion")
+ assert chapter is not None, f"fixture grew no chapter: {sorted(pages)}"
+ assert chapter.metadata.get("is_chapter") is True
+ assert chapter.title == "Ingestion Overview"
+ # The leaves under it still carry what the model called them.
+ assert any(
+ p.title.startswith("Title ")
+ for pid, p in pages.items()
+ if pid.startswith("module_page:src/ingestion/")
+ ), f"the chapter's children lost their model titles: {sorted(pages)}"
+
+
# ---------------------------------------------------------------------------
# Identity does not follow the title (D2)
# ---------------------------------------------------------------------------
diff --git a/tests/unit/generation/test_concept_outline.py b/tests/unit/generation/test_concept_outline.py
index f25dafb29..5069c5c1c 100644
--- a/tests/unit/generation/test_concept_outline.py
+++ b/tests/unit/generation/test_concept_outline.py
@@ -380,3 +380,76 @@ def test_a_trailing_number_stays_with_its_word():
)
assert deterministic_title(group) == "C4 Nodes"
+class TestCycleNaming:
+ """A cycle page was titled by the hash of its members, which nothing searches for."""
+
+ def test_a_cycle_inside_one_subsystem_is_named_for_it(self):
+ from repowise.core.generation.concept_tree.naming import scc_where
+
+ assert (
+ scc_where(
+ [
+ "src/core/ingestion/resolvers/a.py",
+ "src/core/ingestion/resolvers/b.py",
+ ]
+ )
+ == "Ingestion Resolvers"
+ )
+
+ def test_a_cycle_that_crosses_subsystems_names_the_biggest_two(self):
+ """Crossing is the interesting thing about it, so the title says so."""
+ from repowise.core.generation.concept_tree.naming import scc_where
+
+ where = scc_where(
+ [
+ "tests/a.py",
+ "tests/b.py",
+ "tests/c.py",
+ "packages/x.py",
+ "packages/y.py",
+ "docs/d.py",
+ ]
+ )
+ assert where == "Tests and Packages"
+
+ def test_a_crossing_cycle_breaks_size_ties_on_the_path(self):
+ """So the title does not move between runs on an unchanged repository."""
+ from repowise.core.generation.concept_tree.naming import scc_where
+
+ assert scc_where(["zeta/a.py", "alpha/b.py"]) == "Alpha and Zeta"
+
+ def test_members_with_no_directory_yield_no_name(self):
+ """Better to keep the id than to render a title claiming less than it."""
+ from repowise.core.generation.concept_tree.naming import scc_where
+
+ assert scc_where(["main.py"]) == ""
+
+ def test_the_name_is_stable_for_an_unchanged_cycle(self):
+ from repowise.core.generation.concept_tree.naming import scc_where
+
+ members = ["b/x.py", "a/y.py", "a/z.py"]
+ assert scc_where(sorted(members)) == scc_where(sorted(reversed(members)))
+
+ def test_titles_are_unique_across_the_run(self):
+ """Several cycles through one subsystem all describe themselves the same."""
+ from repowise.core.generation.page_generator.levels import _scc_titles
+
+ titles = _scc_titles(
+ [
+ ("scc-aaa", ["src/ingest/resolvers/a.py", "src/ingest/resolvers/b.py"]),
+ ("scc-bbb", ["src/ingest/resolvers/c.py", "src/ingest/resolvers/d.py"]),
+ ("scc-ccc", ["src/store/q.py", "src/store/r.py"]),
+ ]
+ )
+
+ assert len(set(titles.values())) == 3
+ # The one that keeps the plain name is decided by path order, not by
+ # input order, so a re-run does not swap them.
+ assert titles["scc-ccc"] == "Circular Dependency: Store"
+
+ def test_a_nameless_cycle_falls_back_to_its_id(self):
+ from repowise.core.generation.page_generator.levels import _scc_titles
+
+ titles = _scc_titles([("scc-aaa", ["main.py"])])
+
+ assert titles["scc-aaa"] == "Circular Dependency: scc-aaa"
diff --git a/tests/unit/generation/test_page_tree.py b/tests/unit/generation/test_page_tree.py
index b7f89ed81..c57f9b8d3 100644
--- a/tests/unit/generation/test_page_tree.py
+++ b/tests/unit/generation/test_page_tree.py
@@ -377,3 +377,123 @@ class TestRollupPlacement:
by_id = _by_id(pages)
assert by_id["file_page:src/ingest/a.py"].parent_page_id == "module_page:src/ingest"
assert by_id["file_page:src/web/app.tsx"].parent_page_id == "module_page:src/web"
+
+ def test_an_unstamped_rollup_leaves_the_tree_flat(self):
+ """A page written before chapters shipped must not be guessed at.
+
+ ``src`` heads two module pages here and would qualify as a chapter by
+ shape, but it carries no ``is_chapter``. Deriving the rule a second
+ time in the tree is how the two records start disagreeing, so an
+ un-stamped wiki stays exactly as flat as it was.
+ """
+ pages = _wiki_with_rollup()
+ assign_page_tree(pages, LAYER_ORDER)
+ by_id = _by_id(pages)
+ assert by_id["module_page:src/ingest"].parent_page_id == "layer_page:layer:service"
+ assert by_id["module_page:src/web"].parent_page_id == "layer_page:layer:ui"
+
+
+def _wiki_with_chapters() -> list[GeneratedPage]:
+ """A nested chapter spine: core > analysis > health, plus a loose module.
+
+ ``core`` and ``analysis`` are chapters that also own loose files of their
+ own; ``health`` is a chapter with no files. ``tools`` sits under no chapter
+ at all, which is the majority case on a real repository.
+ """
+ return [
+ _page("repo_overview", "demo"),
+ _page("layer_page", "layer:service"),
+ _page("layer_page", "layer:ui"),
+ _page("module_page", "src/core", is_chapter=True, file_paths=["src/core/main.py"]),
+ _page(
+ "module_page",
+ "src/core/analysis",
+ is_chapter=True,
+ file_paths=["src/core/analysis/run.py"],
+ ),
+ _page("module_page", "src/core/analysis/health", is_chapter=True),
+ _page(
+ "module_page",
+ "src/core/analysis/health/biomarkers",
+ file_paths=["src/core/analysis/health/biomarkers/b.py"],
+ ),
+ _page(
+ "module_page",
+ "src/core/analysis/health/perf",
+ file_paths=["src/core/analysis/health/perf/p.py"],
+ ),
+ _page("module_page", "src/core/ingest", file_paths=["src/core/ingest/a.py"]),
+ _page("module_page", "tools", file_paths=["tools/t.tsx"]),
+ _page("file_page", "src/core/main.py", layer_id="layer:service"),
+ _page("file_page", "src/core/analysis/run.py", layer_id="layer:service"),
+ _page("file_page", "src/core/analysis/health/biomarkers/b.py", layer_id="layer:service"),
+ _page("file_page", "src/core/analysis/health/perf/p.py", layer_id="layer:service"),
+ _page("file_page", "src/core/ingest/a.py", layer_id="layer:service"),
+ _page("file_page", "tools/t.tsx", layer_id="layer:ui"),
+ ]
+
+
+class TestChapterNesting:
+ def test_a_module_hangs_off_its_chapter_not_its_layer(self):
+ pages = _wiki_with_chapters()
+ assign_page_tree(pages, LAYER_ORDER)
+ by_id = _by_id(pages)
+ assert (
+ by_id["module_page:src/core/ingest"].parent_page_id == "module_page:src/core"
+ )
+
+ def test_chapters_nest_nearest_first(self):
+ """The spine is a path, not a fan: each chapter sits under the next one up."""
+ pages = _wiki_with_chapters()
+ assign_page_tree(pages, LAYER_ORDER)
+ by_id = _by_id(pages)
+ assert (
+ by_id["module_page:src/core/analysis/health/biomarkers"].parent_page_id
+ == "module_page:src/core/analysis/health"
+ )
+ assert (
+ by_id["module_page:src/core/analysis/health"].parent_page_id
+ == "module_page:src/core/analysis"
+ )
+ assert (
+ by_id["module_page:src/core/analysis"].parent_page_id == "module_page:src/core"
+ )
+
+ def test_the_top_chapter_falls_back_to_its_layer(self):
+ """Nothing above it, so the old rule still has to work."""
+ pages = _wiki_with_chapters()
+ assign_page_tree(pages, LAYER_ORDER)
+ assert _by_id(pages)["module_page:src/core"].parent_page_id == "layer_page:layer:service"
+
+ def test_a_module_under_no_chapter_keeps_its_layer(self):
+ pages = _wiki_with_chapters()
+ assign_page_tree(pages, LAYER_ORDER)
+ assert _by_id(pages)["module_page:tools"].parent_page_id == "layer_page:layer:ui"
+
+ def test_a_chapter_that_owns_files_keeps_them(self):
+ """Nesting places pages; it must not move a single file's ownership."""
+ pages = _wiki_with_chapters()
+ assign_page_tree(pages, LAYER_ORDER)
+ by_id = _by_id(pages)
+ assert by_id["file_page:src/core/main.py"].parent_page_id == "module_page:src/core"
+ assert (
+ by_id["file_page:src/core/analysis/run.py"].parent_page_id
+ == "module_page:src/core/analysis"
+ )
+ assert (
+ by_id["file_page:src/core/ingest/a.py"].parent_page_id
+ == "module_page:src/core/ingest"
+ )
+
+ def test_no_page_is_its_own_ancestor(self):
+ """A cycle breaks every walk of the tree, so assert the spine terminates."""
+ pages = _wiki_with_chapters()
+ assign_page_tree(pages, LAYER_ORDER)
+ by_id = _by_id(pages)
+ for page in pages:
+ seen = {page.page_id}
+ cursor = page.parent_page_id
+ while cursor:
+ assert cursor not in seen, f"cycle through {page.page_id}"
+ seen.add(cursor)
+ cursor = by_id[cursor].parent_page_id if cursor in by_id else None
diff --git a/tests/unit/generation/test_related_pages.py b/tests/unit/generation/test_related_pages.py
index c52f94045..c4bff9ea9 100644
--- a/tests/unit/generation/test_related_pages.py
+++ b/tests/unit/generation/test_related_pages.py
@@ -144,12 +144,208 @@ def test_deleted_targets_drop_out():
assert _related(pages[0]) == []
-def test_non_file_pages_untouched():
- pages = [_make_page("module_page", "community-1")]
+def test_pages_that_are_neither_file_nor_module_are_untouched():
+ pages = [
+ _make_page("onboarding", "onboarding/getting_started"),
+ _make_page("symbol_spotlight", "a.py::Thing"),
+ ]
attach_related_pages(pages, import_edges=[])
- assert "related_pages" not in pages[0].metadata
+ assert all("related_pages" not in p.metadata for p in pages)
+
+
+def _module(target: str, members: list[str]) -> GeneratedPage:
+ page = _make_page("module_page", target)
+ page.metadata["file_paths"] = members
+ return page
+
+
+class TestModulePages:
+ """A module's neighbours are its members' neighbours, lifted and counted."""
+
+ def test_import_edges_between_members_become_module_edges(self):
+ pages = [
+ _module("src/ingest", ["src/ingest/a.py", "src/ingest/b.py"]),
+ _module("src/store", ["src/store/db.py"]),
+ _make_page("file_page", "src/ingest/a.py"),
+ _make_page("file_page", "src/store/db.py"),
+ ]
+
+ attach_related_pages(
+ pages, import_edges=[("src/ingest/a.py", "src/store/db.py")]
+ )
+
+ ingest = _related(pages[0])
+ assert [(r["target_page_id"], r["reason"]) for r in ingest] == [
+ ("module_page:src/store", "imports")
+ ]
+ # The edge is symmetric: the target learns who depends on it.
+ assert [(r["target_page_id"], r["reason"]) for r in _related(pages[1])] == [
+ ("module_page:src/ingest", "imported-by")
+ ]
+
+ def test_weight_counts_the_edges_crossing_the_boundary(self):
+ """Two subsystems joined by three edges outrank two joined by one."""
+ pages = [
+ _module("src/ingest", ["src/ingest/a.py", "src/ingest/b.py"]),
+ _module("src/store", ["src/store/db.py", "src/store/q.py"]),
+ _module("src/util", ["src/util/u.py"]),
+ ]
+
+ attach_related_pages(
+ pages,
+ import_edges=[
+ ("src/ingest/a.py", "src/store/db.py"),
+ ("src/ingest/a.py", "src/store/q.py"),
+ ("src/ingest/b.py", "src/store/db.py"),
+ ("src/ingest/b.py", "src/util/u.py"),
+ ],
+ )
+
+ ingest = _related(pages[0])
+ assert [(r["target_page_id"], r["weight"]) for r in ingest] == [
+ ("module_page:src/store", 3.0),
+ ("module_page:src/util", 1.0),
+ ]
+
+ def test_edges_inside_a_module_are_dropped(self):
+ """A module is not related to itself, and self-edges would swamp the rest."""
+ pages = [
+ _module("src/ingest", ["src/ingest/a.py", "src/ingest/b.py"]),
+ _module("src/store", ["src/store/db.py"]),
+ ]
+
+ attach_related_pages(
+ pages,
+ import_edges=[
+ ("src/ingest/a.py", "src/ingest/b.py"),
+ ("src/ingest/b.py", "src/ingest/a.py"),
+ ("src/ingest/a.py", "src/store/db.py"),
+ ],
+ )
+
+ assert [r["target_page_id"] for r in _related(pages[0])] == [
+ "module_page:src/store"
+ ]
+
+ def test_same_module_is_never_a_reason_for_a_module(self):
+ """It *is* the module; the reason is meaningless at this scale."""
+ pages = [
+ _module("src/ingest", ["src/ingest/a.py", "src/ingest/b.py"]),
+ _module("src/store", ["src/store/db.py"]),
+ ]
+
+ attach_related_pages(
+ pages,
+ import_edges=[("src/ingest/a.py", "src/store/db.py")],
+ module_groups=[_Group("src/ingest", ("src/ingest/a.py", "src/ingest/b.py"))],
+ )
+
+ assert all(r["reason"] != "same-module" for r in _related(pages[0]))
+
+ def test_co_change_partners_lift_to_their_modules(self):
+ pages = [
+ _module("src/ingest", ["src/ingest/a.py"]),
+ _module("src/store", ["src/store/db.py"]),
+ ]
+ git_meta = {
+ "src/ingest/a.py": {
+ "co_change_partners_json": json.dumps(
+ [{"file_path": "src/store/db.py", "co_change_count": 9}]
+ )
+ }
+ }
+
+ attach_related_pages(pages, import_edges=[], git_meta_map=git_meta)
+
+ assert [(r["target_page_id"], r["reason"]) for r in _related(pages[0])] == [
+ ("module_page:src/store", "co-changes-with")
+ ]
+
+ def test_a_member_owned_by_no_module_is_ignored(self):
+ """A file with no documenting page cannot lift an edge anywhere."""
+ pages = [_module("src/ingest", ["src/ingest/a.py"])]
+
+ attach_related_pages(pages, import_edges=[("src/ingest/a.py", "vendor/x.py")])
+
+ assert _related(pages[0]) == []
+
+ def test_a_chapter_with_no_files_inherits_its_subtree(self):
+ """Otherwise the page whose whole job is orientation has nothing across."""
+ pages = [
+ _module("src/ingest", []), # the chapter: all its files are its children's
+ _module("src/ingest/lang", ["src/ingest/lang/a.py"]),
+ _module("src/ingest/graph", ["src/ingest/graph/b.py"]),
+ _module("src/store", ["src/store/db.py"]),
+ ]
+
+ attach_related_pages(
+ pages,
+ import_edges=[
+ ("src/ingest/lang/a.py", "src/store/db.py"),
+ ("src/ingest/graph/b.py", "src/store/db.py"),
+ ],
+ )
+
+ assert [(r["target_page_id"], r["weight"]) for r in _related(pages[0])] == [
+ ("module_page:src/store", 2.0)
+ ]
+
+ def test_an_inherited_neighbour_inside_the_subtree_is_dropped(self):
+ """It already links down to that page; repeating it across is not news."""
+ pages = [
+ _module("src/ingest", []),
+ _module("src/ingest/lang", ["src/ingest/lang/a.py"]),
+ _module("src/ingest/graph", ["src/ingest/graph/b.py"]),
+ ]
+
+ attach_related_pages(
+ pages, import_edges=[("src/ingest/lang/a.py", "src/ingest/graph/b.py")]
+ )
+
+ assert _related(pages[0]) == []
+ # The children still see each other; only the chapter filters them out.
+ assert [r["target_page_id"] for r in _related(pages[1])] == [
+ "module_page:src/ingest/graph"
+ ]
+
+ def test_a_chapter_that_owns_files_keeps_its_own_edges(self):
+ """It has real evidence, so it is not given its subtree's second-hand set."""
+ pages = [
+ _module("src/ingest", ["src/ingest/main.py"]),
+ _module("src/ingest/lang", ["src/ingest/lang/a.py"]),
+ _module("src/store", ["src/store/db.py"]),
+ _module("src/util", ["src/util/u.py"]),
+ ]
+
+ attach_related_pages(
+ pages,
+ import_edges=[
+ ("src/ingest/main.py", "src/store/db.py"),
+ ("src/ingest/lang/a.py", "src/util/u.py"),
+ ],
+ )
+
+ assert [r["target_page_id"] for r in _related(pages[0])] == [
+ "module_page:src/store"
+ ]
+
+ def test_prose_links_still_win(self):
+ """Related fills the gaps left by prose, and never duplicates one."""
+ pages = [
+ _module("src/ingest", ["src/ingest/a.py"]),
+ _module("src/store", ["src/store/db.py"]),
+ ]
+ pages[0].metadata["wiki_links"] = [
+ {"anchor": "src/store", "target_page_id": "module_page:src/store", "kind": "file"}
+ ]
+
+ attach_related_pages(
+ pages, import_edges=[("src/ingest/a.py", "src/store/db.py")]
+ )
+
+ assert _related(pages[0]) == []
def test_prior_page_ids_widen_resolution_on_incremental_update():
diff --git a/tests/unit/generation/test_selection_concept_groups.py b/tests/unit/generation/test_selection_concept_groups.py
index 13989f4e2..c0dc1f9ca 100644
--- a/tests/unit/generation/test_selection_concept_groups.py
+++ b/tests/unit/generation/test_selection_concept_groups.py
@@ -25,8 +25,11 @@ from repowise.core.generation.concept_tree.grouping import ConceptGroup
from repowise.core.generation.models import GenerationConfig
from repowise.core.generation.selection import SelectionInputs, select_pages
from repowise.core.generation.selection.selector import (
+ ModuleGroup,
_build_module_groups,
_build_rollup_groups,
+ _chapter_members,
+ retitle_chapters,
)
from tests.unit.generation.test_selection_contract import (
FakeFileInfo,
@@ -401,8 +404,16 @@ def _leaf(members: list[str]) -> ConceptGroup:
return ConceptGroup(members=sorted(members), dirs=[tp], target_path=tp)
-def test_rollup_emitted_for_parent_of_two_leaf_pages():
- """A parent that owns >=2 leaf pages and is itself no leaf gets an overview.
+def _synthesised(leaves: list[ConceptGroup], files: list[str]):
+ """The chapters that need a page of their own, as the selector builds them."""
+ chapters = _chapter_members(leaves, files)
+ return chapters, _build_rollup_groups(
+ chapters, leaves, files, {f: "python" for f in files}, {}
+ )
+
+
+def test_chapter_emitted_for_parent_of_two_leaf_pages():
+ """A parent that heads >=2 leaf pages and is itself no leaf gets a chapter.
Its target_path is exactly that directory, because directory-level retrieval
matches a page to a directory by exact target_path equality.
@@ -412,58 +423,256 @@ def test_rollup_emitted_for_parent_of_two_leaf_pages():
_leaf(["p/ingestion/graph/c.py", "p/ingestion/graph/d.py"]),
# Two unrelated subsystems so ingestion stays a minority of the repo and
# the near-repo-wide guard does not fire; each owns a single leaf, so
- # neither earns an overview of its own.
+ # neither earns a chapter of its own.
_leaf([f"p/other/e{i}.py" for i in range(6)]),
_leaf([f"p/extra/g{i}.py" for i in range(6)]),
]
files = [m for g in leaves for m in g.members] + ["p/ingestion/loose.py"]
- lang_of = {f: "python" for f in files}
- rollups = _build_rollup_groups(leaves, files, lang_of, {})
- keys = {m.key for _, m in rollups}
+ chapters, rollups = _synthesised(leaves, files)
- # ingestion owns two leaf children; the others own one each, so no overview.
- assert keys == {"p/ingestion"}
+ # ingestion heads two leaf children; the others head one each, so no chapter.
+ assert set(chapters) == {"p/ingestion"}
+ assert {m.key for _, m in rollups} == {"p/ingestion"}
(_, roll) = rollups[0]
assert roll.is_rollup is True
assert roll.structural_key.startswith("concept-rollup")
- # It carries the subsystem's files for context, including loose ones.
- assert "p/ingestion/loose.py" in roll.file_paths
+ # No group of its own, so it owns nothing and every file stays with a leaf.
+ assert roll.file_paths == ()
+ # It still reads the subsystem's files for context, including loose ones.
+ assert "p/ingestion/loose.py" in roll.context_paths
+
+def test_a_directory_that_is_both_chapter_and_leaf_yields_one_page():
+ """The parent keeps its own group and heads its children from it.
-def test_rollup_target_never_collides_with_a_leaf():
- """A parent that is already a leaf page is not given a second overview."""
+ Both pages would be ``module_page:p/svc`` and only one page can have an id,
+ so this is the case that used to be dropped. Dropping it removed the
+ chapter a reader most wants: the directory holding both the subsystem's
+ entry points and its parts.
+ """
+ parent = _leaf(["p/svc/a.py", "p/svc/b.py"]) # target p/svc — the parent itself
leaves = [
- _leaf(["p/svc/a.py", "p/svc/b.py"]), # target p/svc — the parent itself
+ parent,
_leaf(["p/svc/api/c.py", "p/svc/api/d.py"]),
_leaf(["p/svc/db/e.py", "p/svc/db/f.py"]),
+ _leaf([f"p/other/e{i}.py" for i in range(8)]),
]
files = [m for g in leaves for m in g.members]
- rollups = _build_rollup_groups(leaves, files, {f: "python" for f in files}, {})
- # p/svc is a leaf target, so no rollup claims that page id.
+
+ chapters, rollups = _synthesised(leaves, files)
+
+ # p/svc heads a subsystem...
+ assert "p/svc" in chapters
+ # ...but no second page is synthesised for it, because its own group is the
+ # page. Exactly one thing may claim ``module_page:p/svc``.
assert "p/svc" not in {m.key for _, m in rollups}
-def test_rollup_titles_are_disambiguated():
- """Two same-named subsystems in different packages get distinct titles."""
- leaves = [
- _leaf(["a/web/components/x/1.py", "a/web/components/x/2.py"]),
- _leaf(["a/web/components/z/3.py", "a/web/components/z/4.py"]),
- _leaf(["a/ext/components/y/5.py", "a/ext/components/y/6.py"]),
- _leaf(["a/ext/components/w/7.py", "a/ext/components/w/8.py"]),
+def _module_group(key: str, *, files: tuple[str, ...], chapter: bool, display: str):
+ return ModuleGroup(
+ key=key, display=display, language="python", file_paths=files, is_rollup=chapter
+ )
+
+
+def test_chapter_titles_are_disambiguated_against_the_leaves():
+ """A chapter title never duplicates a leaf's, or another chapter's.
+
+ Two identical rows in the tree are indistinguishable to a reader, and
+ anything keying on a title has to guess between them. The leaves do not
+ move: one of them may carry a model-written name, and a chapter yielding to
+ it is the cheaper of the two collisions to resolve.
+ """
+ groups = [
+ # Two chapters whose directories share a last segment, plus a leaf
+ # already holding the name they would both take.
+ _module_group("a/web/components", files=(), chapter=True, display=""),
+ _module_group("a/ext/components", files=(), chapter=True, display=""),
+ _module_group(
+ "a/web/components/x", files=("a/web/components/x/1.py",),
+ chapter=False, display="Components Overview",
+ ),
+ _module_group(
+ "a/ext/components/y", files=("a/ext/components/y/5.py",),
+ chapter=False, display="Entity Cards",
+ ),
]
- files = [m for g in leaves for m in g.members]
- rollups = _build_rollup_groups(leaves, files, {f: "python" for f in files}, {})
- titles = [m.display for _, m in rollups]
+
+ out = retitle_chapters(groups)
+ titles = [g.display for g in out]
+
assert len(titles) == len(set(titles)), titles
+ # The leaf keeps the name it was given; the chapters take qualified ones.
+ by_key = dict(zip([g.key for g in out], titles, strict=True))
+ assert by_key["a/web/components/x"] == "Components Overview"
+
+
+def test_a_chapter_is_named_for_the_directory_it_heads():
+ """Not for its own files, and not by the model.
+
+ A namer shown a chapter's directory names the loose files at that
+ directory's root, and that name then stands over everything below it. The
+ name a reader can act on is the place.
+ """
+ groups = [
+ _module_group(
+ "p/ingestion", files=("p/ingestion/loose.py",),
+ chapter=True, display="Pipeline Bootstrap Helpers",
+ ),
+ _module_group(
+ "p/ingestion/languages", files=("p/ingestion/languages/a.py",),
+ chapter=False, display="Language Catalog",
+ ),
+ ]
+
+ out = {g.key: g.display for g in retitle_chapters(groups)}
+
+ assert out["p/ingestion"] == "Ingestion Overview"
+ # A leaf is never touched: the model names those well.
+ assert out["p/ingestion/languages"] == "Language Catalog"
+
+
+def test_a_chapter_skips_container_and_route_segments():
+ """``src`` and ``[id]`` name no subject, so the chapter climbs past them."""
+ groups = [
+ _module_group("packages/ui/src", files=(), chapter=True, display=""),
+ _module_group(
+ "packages/ui/src/zoom", files=("packages/ui/src/zoom/a.ts",),
+ chapter=False, display="Zoom Canvas",
+ ),
+ _module_group("app/repos/[id]", files=(), chapter=True, display=""),
+ _module_group(
+ "app/repos/[id]/docs", files=("app/repos/[id]/docs/p.tsx",),
+ chapter=False, display="Docs Routes",
+ ),
+ ]
+
+ out = {g.key: g.display for g in retitle_chapters(groups)}
+
+ assert out["packages/ui/src"] == "Ui Overview"
+ assert out["app/repos/[id]"] == "Repos Overview"
+
+
+def test_a_chapter_spells_its_subject_the_way_the_repository_does():
+ """The children are the only place that says whether ``ui`` is "UI" or "Ui".
+
+ Taken from them rather than from an acronym list, which would be a rule
+ tuned to the repositories whose acronyms happened to be on it.
+ """
+ groups = [
+ _module_group("packages/ui/src", files=(), chapter=True, display=""),
+ _module_group(
+ "packages/ui/src/zoom", files=("packages/ui/src/zoom/a.ts",),
+ chapter=False, display="Zoom UI Canvas",
+ ),
+ _module_group(
+ "packages/ui/src/wiki", files=("packages/ui/src/wiki/b.ts",),
+ chapter=False, display="Wiki UI Panels",
+ ),
+ ]
+
+ assert {g.key: g.display for g in retitle_chapters(groups)}["packages/ui/src"] == "UI Overview"
-def test_rollup_skips_near_repo_wide_parent():
- """A parent covering most of the repo is the repo overview, not a rollup."""
+def test_a_chapter_takes_its_casing_only_from_a_deliberate_spelling():
+ """A lowercase occurrence in a child's title is not a spelling of the word.
+
+ It is the word used mid-sentence, or a quoted path. Taking it would open a
+ page title in lower case.
+ """
+ groups = [
+ _module_group("p/core", files=(), chapter=True, display=""),
+ _module_group(
+ "p/core/a", files=("p/core/a/x.py",),
+ chapter=False, display="Helpers for core and friends",
+ ),
+ ]
+
+ assert {g.key: g.display for g in retitle_chapters(groups)}["p/core"] == "Core Overview"
+
+
+def test_a_chapter_does_not_become_a_case_variant_of_a_leaf():
+ """"UI Overview" over "Ui Overview" is one thing written twice.
+
+ The chapter borrows its casing from its children and the leaf derives its
+ own from a path, so the two arrive spelled differently and an exact-match
+ uniqueness check lets both through.
+ """
+ groups = [
+ _module_group("packages/ui/src", files=(), chapter=True, display=""),
+ _module_group(
+ "packages/ui/src/overview", files=("packages/ui/src/overview/a.ts",),
+ chapter=False, display="Ui Overview",
+ ),
+ _module_group(
+ "packages/ui/src/zoom", files=("packages/ui/src/zoom/b.ts",),
+ chapter=False, display="Zoom UI Canvas",
+ ),
+ ]
+
+ titles = [g.display for g in retitle_chapters(groups)]
+
+ assert len({t.lower() for t in titles}) == len(titles), titles
+
+
+def test_a_chapter_is_named_from_the_children_the_tree_puts_under_it():
+ """Nearest chapter, not nearest directory — chapters nest.
+
+ A title drawn from a different set of children than the tree shows beneath
+ it is a title about the wrong pages.
+ """
+ groups = [
+ _module_group("p/svc", files=(), chapter=True, display=""),
+ _module_group("p/svc/api", files=(), chapter=True, display=""),
+ # Two levels down, so its nearest chapter is api and not svc.
+ _module_group(
+ "p/svc/api/v2", files=("p/svc/api/v2/a.py",), chapter=False, display="V2 API Routes"
+ ),
+ _module_group(
+ "p/svc/db", files=("p/svc/db/b.py",), chapter=False, display="Storage Layer"
+ ),
+ ]
+
+ out = {g.key: g.display for g in retitle_chapters(groups)}
+
+ assert out["p/svc"] == "Svc Overview"
+ # "API" comes from the grandchild's title, which is what the tree nests here.
+ assert out["p/svc/api"] == "API Overview"
+
+
+def test_chapter_skips_near_repo_wide_parent():
+ """A parent covering most of the repo is the repo overview, not a chapter."""
leaves = [
_leaf(["mono/a/x.py", "mono/a/y.py"]),
_leaf(["mono/b/z.py", "mono/b/w.py"]),
]
files = [m for g in leaves for m in g.members]
- rollups = _build_rollup_groups(leaves, files, {f: "python" for f in files}, {})
+ chapters, rollups = _synthesised(leaves, files)
+ assert "mono" not in chapters
assert "mono" not in {m.key for _, m in rollups}
+
+
+def test_chapters_never_double_claim_a_file():
+ """Ownership stays a partition once chapters own files.
+
+ The tree's ``module_of_file``, the incremental cascade's ``module_page_of``
+ and ``related_pages``' sibling map all read ``file_paths`` as an exclusive
+ claim and resolve a conflict by silently picking one. A chapter that
+ out-claimed its own leaves would reparent their files onto itself.
+ """
+ leaves = [
+ _leaf(["p/svc/a.py", "p/svc/b.py"]),
+ _leaf(["p/svc/api/c.py", "p/svc/api/d.py"]),
+ _leaf(["p/svc/db/e.py", "p/svc/db/f.py"]),
+ _leaf(["p/ingestion/lang/g.py", "p/ingestion/lang/h.py"]),
+ _leaf(["p/ingestion/graph/i.py", "p/ingestion/graph/j.py"]),
+ _leaf([f"p/other/k{i}.py" for i in range(8)]),
+ ]
+ files = [m for g in leaves for m in g.members]
+ _chapters, rollups = _synthesised(leaves, files)
+
+ claims: list[str] = [m for g in leaves for m in g.members]
+ claims += [p for _, mg in rollups for p in mg.file_paths]
+
+ assert sorted(claims) == sorted(files), "every file is claimed exactly once"
+ assert len(claims) == len(set(claims))
diff --git a/tests/unit/persistence/test_retired_page_types_sweep.py b/tests/unit/persistence/test_retired_page_types_sweep.py
new file mode 100644
index 000000000..db018f559
--- /dev/null
+++ b/tests/unit/persistence/test_retired_page_types_sweep.py
@@ -0,0 +1,126 @@
+"""Tests for the retired-page-type 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
+absence is normally no evidence at all.
+
+The retirement tables in ``page_redirects`` are the source of truth. A type
+that redirects but is never swept leaves an index serving a page the product
+has replaced, which is the state this was written to clear.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+from sqlalchemy import select
+
+from repowise.core.generation.page_redirects import (
+ 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 tests.unit.persistence.helpers import insert_repo
+
+
+def _page_row(repo_id: str, page_type: str, target: str) -> Page:
+ now = datetime.now(UTC)
+ return Page(
+ id=f"{page_type}:{target}",
+ repository_id=repo_id,
+ page_type=page_type,
+ title=target,
+ content="body",
+ target_path=target,
+ source_hash="x" * 64,
+ model_name="mock",
+ provider_name="mock",
+ created_at=now,
+ updated_at=now,
+ )
+
+
+async def test_every_retired_type_is_swept(async_session):
+ """Driven by the redirect tables, so a new retirement is covered for free."""
+ repo = await insert_repo(async_session)
+ retired = sorted(set(SUPERSEDED_TYPES) | set(SUPERSEDED_TO_REPO_WIDE))
+ assert retired, "the redirect tables are empty; this sweep has nothing to do"
+ for page_type in retired:
+ 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)
+
+ 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_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)
+ async_session.add(_page_row(repo.id, "layer_page", "layer:service"))
+ async_session.add(_page_row(repo.id, "module_page", "src/ingest"))
+ async_session.add(_page_row(repo.id, "file_page", "src/ingest/a.py"))
+ async_session.add(_page_row(repo.id, "repo_overview", "demo"))
+ await async_session.flush()
+
+ await sweep_retired_page_types(async_session, repo.id)
+
+ survivors = set((await async_session.execute(select(Page.id))).scalars().all())
+ assert survivors == {
+ "module_page:src/ingest",
+ "file_page:src/ingest/a.py",
+ "repo_overview:demo",
+ }
+
+
+async def test_versions_go_with_the_page(async_session):
+ """FK enforcement requires it, and a retired id never returns to claim them."""
+ repo = await insert_repo(async_session)
+ async_session.add(_page_row(repo.id, "architecture_diagram", "demo"))
+ async_session.add(
+ PageVersion(
+ page_id="architecture_diagram:demo",
+ repository_id=repo.id,
+ version=1,
+ page_type="architecture_diagram",
+ title="old",
+ content="old body",
+ source_hash="x" * 64,
+ model_name="mock",
+ provider_name="mock",
+ archived_at=datetime.now(UTC),
+ )
+ )
+ await async_session.flush()
+
+ await sweep_retired_page_types(async_session, repo.id)
+
+ left = (await async_session.execute(select(PageVersion.page_id))).scalars().all()
+ assert left == []
+
+
+async def test_other_repositories_are_not_touched(async_session):
+ """The sweep is repo-scoped; a shared store must not lose a neighbour's rows."""
+ mine = await insert_repo(async_session)
+ theirs = await insert_repo(async_session, name="other", local_path="/tmp/other")
+ async_session.add(_page_row(mine.id, "architecture_diagram", "mine"))
+ async_session.add(_page_row(theirs.id, "architecture_diagram", "theirs"))
+ await async_session.flush()
+
+ swept = await sweep_retired_page_types(async_session, mine.id)
+
+ assert swept == ["architecture_diagram:mine"]
+ survivors = (await async_session.execute(select(Page.id))).scalars().all()
+ assert survivors == ["architecture_diagram:theirs"]
+
+
+async def test_a_clean_index_sweeps_nothing(async_session):
+ repo = await insert_repo(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) == []