Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
fix(wiki): page title, layer identity and deterministic file page defects (#1013)
Raghav Chamadiyac03f9c315d9c
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.pyindex 953bc219b..f69a12959 100644--- a/packages/core/src/repowise/core/generation/context/assembler.py+++ b/packages/core/src/repowise/core/generation/context/assembler.py@@ -35,6 +35,19 @@ from .token_budget import (log = structlog.get_logger(__name__)++def _is_foreign_edge(node: str, path: str) -> bool:+ """Whether a graph neighbour is a real dependency rather than this file itself.++ Graph node ids are either a file path or ``<file path>::<symbol>``. Both+ spellings of "this file" are dropped so a dependency list only ever names+ other files.+ """+ if node.startswith("external:"):+ return False+ return node != path and node.split("::", 1)[0] != path++# Maximum imports to include before truncating_MAX_IMPORTS = 30# Maximum top-files to include in repo overview@@ -138,9 +151,14 @@ class ContextAssembler:# Graph edgesin_edges = list(graph.predecessors(path)) if path in graph else []out_edges = list(graph.successors(path)) if path in graph else []- # Filter out external nodes- in_edges = [e for e in in_edges if not e.startswith("external:")]- out_edges = [e for e in out_edges if not e.startswith("external:")]+ # Filter out external nodes, and edges that point back into this same+ # file. The graph carries file->symbol edges, so a file's successors+ # include its own symbols ("thisfile.py::Thing"). Left in, those+ # dominate the rendered dependency list: measured over the current+ # index, 70% of all dependency lines were self-references and 121+ # pages listed nothing else. A file's dependencies are other files.+ in_edges = [e for e in in_edges if _is_foreign_edge(e, path)]+ out_edges = [e for e in out_edges if _is_foreign_edge(e, path)]# Source snippet — use structural summary for large filessource_text = source_bytes.decode("utf-8", errors="replace")diff --git a/packages/core/src/repowise/core/generation/layers.py b/packages/core/src/repowise/core/generation/layers.pyindex e6096d83f..3bc82a94e 100644--- a/packages/core/src/repowise/core/generation/layers.py+++ b/packages/core/src/repowise/core/generation/layers.py@@ -20,6 +20,7 @@ strings and edge tuples, which keeps them trivially unit-testable.from __future__ import annotations+import refrom collections import defaultdictfrom collections.abc import Iterable, Mappingfrom pathlib import PurePosixPath@@ -259,6 +260,34 @@ _CANONICAL_RANK: dict[str, int] = {_PINNED_AFTER_RUNTIME: frozenset[str] = ADJACENT_LAYERS | {DOCS_TOOLING_LAYER}+def layer_key(layer: str) -> str:+ """Normalise a layer to its stable slug, from either spelling.++ Callers hand us one of two things: a canonical heuristic name from+ :func:`infer_layer` ("UI", "Docs & Tooling") or a curated layer id+ ("layer:ui"). Both must rank identically, because the curated id *is*+ ``layer:`` plus the slug of the heuristic name. See ``kg_curation`` where the+ id is minted. Normalising at lookup lets ordering key on the stable id+ without a second rank table, and keeps older callers passing names working.+ """+ slug = re.sub(r"[^a-z0-9]+", "-", layer.lower().strip()).strip("-")+ return slug.removeprefix("layer-") or "unknown"+++_PINNED_KEYS: frozenset[str] = frozenset(layer_key(la) for la in _PINNED_AFTER_RUNTIME)+_CANONICAL_RANK_BY_KEY: dict[str, int] = {+ layer_key(name): rank for name, rank in _CANONICAL_RANK.items()+}+++def _is_pinned(layer: str) -> bool:+ return layer_key(layer) in _PINNED_KEYS+++def _canonical_rank(layer: str) -> int:+ return _CANONICAL_RANK_BY_KEY.get(layer_key(layer), len(_CANONICAL_RANK))++def infer_layer(path: str, language: str | None = None) -> str:"""Return the architectural layer name for *path*.@@ -371,7 +400,7 @@ def layer_order_basis(ld = file_layers.get(dst)if not ls or not ld or ls == ld:continue- if ls in _PINNED_AFTER_RUNTIME or ld in _PINNED_AFTER_RUNTIME:+ if _is_pinned(ls) or _is_pinned(ld):continuereturn "imports"return "canonical"@@ -408,8 +437,8 @@ def compute_layer_order(if len(layers) <= 1:return layers- runtime = [layer for layer in layers if layer not in _PINNED_AFTER_RUNTIME]- adjacent = [layer for layer in layers if layer in _PINNED_AFTER_RUNTIME]+ runtime = [layer for layer in layers if not _is_pinned(layer)]+ adjacent = [layer for layer in layers if _is_pinned(layer)]out_deg: dict[str, int] = defaultdict(int) # edges leaving the layerin_deg: dict[str, int] = defaultdict(int) # edges entering the layer@@ -420,7 +449,7 @@ def compute_layer_order(ld = file_layers.get(dst)if not ls or not ld or ls == ld:continue- if ls in _PINNED_AFTER_RUNTIME or ld in _PINNED_AFTER_RUNTIME:+ if _is_pinned(ls) or _is_pinned(ld):continueout_deg[ls] += 1in_deg[ld] += 1@@ -429,8 +458,8 @@ def compute_layer_order(# Net "imported-ness": more incoming than outgoing → foundational →# sorts later (bottom). Negate out so consumers float to the top.net = in_deg[layer] - out_deg[layer]- return (net, _CANONICAL_RANK.get(layer, len(_CANONICAL_RANK)))+ return (net, _canonical_rank(layer))ordered = sorted(runtime, key=sort_key)- ordered += sorted(adjacent, key=lambda la: _CANONICAL_RANK.get(la, len(_CANONICAL_RANK)))+ ordered += sorted(adjacent, key=_canonical_rank)return ordereddiff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.pyindex 163041cec..3172eceff 100644--- a/packages/core/src/repowise/core/generation/page_generator/core.py+++ b/packages/core/src/repowise/core/generation/page_generator/core.py@@ -40,7 +40,12 @@ from .decision_harvest import (HARVESTABLE_PAGE_TYPES,harvest_decisions,)-from .deterministic import DeterministicRenderMixin, oneline+from .deterministic import (+ DeterministicRenderMixin,+ as_markdown,+ oneline,+ signature,+)from .helpers import _extract_summary, _now_isofrom .pertype import PerTypeGenerationMixinfrom .prompts import SUPPORTED_LANGUAGES, SYSTEM_PROMPTS@@ -60,25 +65,31 @@ def _attach_file_provenance(page: GeneratedPage, ctx: FilePageContext) -> None:renders ``layer_name`` as a zoom-out chip and ``sources`` as a "builtfrom" provenance list."""+ from ...analysis.knowledge_graph import _slugify+ from ..layers import infer_layer+if ctx.kg_layer_name:page.metadata["layer_name"] = ctx.kg_layer_name- # Stable slug id of the layer page this file links to. The layer page- # is keyed by slug (``layer:<slug>``) so the join survives the LLM- # layer-name enrichment that mutates ``layer_name`` after generation.- if ctx.kg_layer_id:- page.metadata["layer_id"] = ctx.kg_layer_idif ctx.kg_layer_role:page.metadata["layer_role"] = ctx.kg_layer_roleelse:# Guarantee every file page carries a layer so the Architecture tree# can group it. When the knowledge graph has no layer, fall back to# path-based inference.- from ...analysis.knowledge_graph import _slugify- from ..layers import infer_layer+ page.metadata["layer_name"] = infer_layer(+ ctx.file_path, getattr(ctx, "language", None)+ )- inferred = infer_layer(ctx.file_path, getattr(ctx, "language", None))- page.metadata["layer_name"] = inferred- page.metadata["layer_id"] = f"layer:{_slugify(inferred)}"+ # ``layer_id`` is the join key every consumer groups on, so guarantee it+ # unconditionally. A curated layer_name without an id used to leave the+ # page unjoinable. The id is the stable slug; ``layer_name`` is display+ # text the LLM enrichment pass rewrites, and must never be a grouping key.+ # Derived with kg_curation's own slugify, so a fallback id is byte-identical+ # to the id that pass would mint for the same layer. A near-miss here points+ # a file page at a layer page that does not exist.+ page.metadata["layer_id"] = ctx.kg_layer_id or "layer:{}".format(+ _slugify(str(page.metadata["layer_name"]))+ )sources: list[dict[str, str]] = []seen: set[str] = set()@@ -192,6 +203,8 @@ class PageGenerator(PerTypeGenerationMixin, DeterministicRenderMixin):# Registered on whatever env we ended up with (including one a caller# injected), since deterministic templates depend on it.self._jinja_env.filters.setdefault("oneline", oneline)+ self._jinja_env.filters.setdefault("as_markdown", as_markdown)+ self._jinja_env.filters.setdefault("signature", signature)# ------------------------------------------------------------------# generate_all — orchestration (delegates to orchestrate.py)diff --git a/packages/core/src/repowise/core/generation/page_generator/deterministic.py b/packages/core/src/repowise/core/generation/page_generator/deterministic.pyindex 5822829a2..d1b33456a 100644--- a/packages/core/src/repowise/core/generation/page_generator/deterministic.py+++ b/packages/core/src/repowise/core/generation/page_generator/deterministic.py@@ -20,6 +20,7 @@ the UI can offer to rewrite it with a model.from __future__ import annotations+import refrom typing import Anyimport structlog@@ -54,6 +55,95 @@ def oneline(value: object, limit: int = _ONELINE_LIMIT) -> str:return text+# reStructuredText roles (:meth:`x`, :class:`~pkg.X`) and the double-backtick+# literal. Our docstrings are predominantly Sphinx flavoured, and markdown+# renders none of it: ``:meth:`foo``` shows the role name as body text and the+# double backticks come out as a stray empty code span.+# Allow-listed rather than ``:[a-z:]+:`` so ordinary prose is left alone. A+# permissive pattern eats any "word:word:" that happens to precede a backtick,+# which turns "O(n:m:`k`)" into "O(n`k`)".+_REST_ROLE_RE = re.compile(+ r":(?:py:)?(?:meth|class|func|attr|mod|ref|data|exc|obj|const|term|doc|file):`~?([^`]+)`"+)+# A directive owns its indented body, so dropping only the ``.. note::`` line+# leaves the body dangling at +4 spaces, which markdown then renders as a code+# block. Consume the body with it.+_REST_DIRECTIVE_RE = re.compile(+ r"^([ \t]*)\.\.[ \t]+[a-z-]+::.*(?:\n(?:\1[ \t]+.*|[ \t]*(?=\n|$)))*", re.MULTILINE+)+# Not preceded or followed by a third backtick, so a ``` fence is left intact.+_DOUBLE_TICK_RE = re.compile(r"(?<!`)``([^`\n]+)``(?!`)")+_FENCE_RE = re.compile(r"```.*?```", re.DOTALL)+++def as_markdown(value: object) -> str:+ """Convert a source docstring into markdown that renders as intended.++ Docstrings reach a deterministic page verbatim, so whatever dialect the+ author used lands in the rendered wiki. Sphinx roles and directives are by+ far the most common here and are also the ones markdown mangles worst, so+ those are converted; everything else is left alone rather than guessed at.+ """+ text = str(value or "")+ if not text.strip():+ return ""++ # Fenced blocks are already markdown and must survive untouched, so lift+ # them out, rewrite the prose around them, and put them back.+ fences: list[str] = []++ def _stash(match: re.Match[str]) -> str:+ fences.append(match.group(0))+ return f"\x00FENCE{len(fences) - 1}\x00"++ text = _FENCE_RE.sub(_stash, text)+ text = _REST_DIRECTIVE_RE.sub("", text)+ # ``:meth:`Store.get``` -> ``Store.get``, keeping the reference visible as+ # code rather than dropping it.+ text = _REST_ROLE_RE.sub(r"`\1`", text)+ text = _DOUBLE_TICK_RE.sub(r"`\1`", text)+ text = dedent_body(text).strip()+ for i, fence in enumerate(fences):+ text = text.replace(f"\x00FENCE{i}\x00", fence)+ return text+++def dedent_body(text: str) -> str:+ """Strip the common indent from every line after the first.++ A docstring's first line starts at the quote, later lines carry the source+ indentation. Left in, four or more leading spaces make markdown treat the+ body as a code block.+ """+ lines = text.splitlines()+ if len(lines) < 2:+ return text+ rest = [ln for ln in lines[1:] if ln.strip()]+ if not rest:+ return lines[0]+ indent = min(len(ln) - len(ln.lstrip()) for ln in rest)+ return "\n".join([lines[0]] + [ln[indent:] if ln.strip() else "" for ln in lines[1:]])+++def signature(value: object, limit: int = 120) -> str:+ """Render a symbol signature for a table cell without cutting mid-token.++ Signatures are captured across source lines, so collapsing whitespace is+ needed before anything else or the cell fills with runs of indentation.+ When one is still too long we cut back to the last argument boundary, so+ the reader sees a whole parameter list prefix rather than half an+ identifier.+ """+ text = " ".join(str(value or "").split())+ if len(text) <= limit:+ return text+ head = text[:limit]+ cut = max(head.rfind(", "), head.rfind("("))+ if cut > limit // 3:+ head = head[: cut + 1]+ return head.rstrip().rstrip(",") + " …"++class DeterministicRenderMixin:"""Template-only ``_deterministic_*`` renderers, mixed into PageGenerator.diff --git a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py b/packages/core/src/repowise/core/generation/page_generator/orchestrate.pyindex abeef61dd..37d4b919d 100644--- a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py+++ b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py@@ -145,7 +145,10 @@ class _GenerationRun:# and reused by level-8 onboarding, the repo overview, and the agent# surface. Empty until _compute_ia() runs.self.tour_stops: list[dict] = []+ # Display names, in spine order. Rendered as prose and served over MCP.self.layer_order: list[str] = []+ # The same spine as stable layer ids. This is the join key.+ self.layer_order_ids: list[str] = []# Selection allow-sets (populated by _compute_selection).self.selection: Any = None@@ -404,7 +407,7 @@ class _GenerationRun:the import graph) and reference only pages that will exist, so neitherspawns new LLM work."""- from ..layers import compute_layer_order, infer_layer+ from ..layers import compute_layer_order, infer_layer, layer_keyfrom ..tour import build_tourimport_edges = self._file_import_edges()@@ -437,13 +440,31 @@ class _GenerationRun:for p in self.parsed_filesif getattr(p, "file_info", None)}+ # Order on the curated layer *id*, never on ``layer_name``. The name is+ # a display string the layer-enrichment pass rewrites, so it drifts+ # between generations and cannot be a join key; the id is stable by+ # construction (kg_curation mints it as ``layer:`` + slug) and is what+ # ``_attach_file_provenance`` stamps on each page.+ #+ # The two are kept side by side rather than one replacing the other,+ # because they answer different questions. ``layer_order_ids`` is what+ # the tree and the file pages join on. ``layer_order`` stays a list of+ # human names, because it is also rendered as prose in the onboarding+ # pages and published over MCP, where a slug would be user-visible.file_layers: dict[str, str] = {}+ display_of: dict[str, str] = {}for path in self.sel_file_paths:kg_fc = self.kg_ctx.get_file_context(path) if self.kg_ctx.available else None- file_layers[path] = (- kg_fc.layer_name if kg_fc and kg_fc.layer_name else ""- ) or infer_layer(path, lang_by_path.get(path))- self.layer_order = compute_layer_order(file_layers, import_edges)+ if kg_fc and kg_fc.layer_id:+ layer_id = kg_fc.layer_id+ display = kg_fc.layer_name or layer_id+ else:+ display = infer_layer(path, lang_by_path.get(path))+ layer_id = f"layer:{layer_key(display)}"+ file_layers[path] = layer_id+ display_of.setdefault(layer_id, display)+ self.layer_order_ids = compute_layer_order(file_layers, import_edges)+ self.layer_order = [display_of.get(lid, lid) for lid in self.layer_order_ids]# ------------------------------------------------------------------# Level runner@@ -600,6 +621,8 @@ class _GenerationRun:page.metadata["guided_tour"] = self.tour_stopsif self.layer_order:page.metadata["layer_order"] = self.layer_order+ if self.layer_order_ids:+ page.metadata["layer_order_ids"] = self.layer_order_idsbreakreturn self._finalize(all_pages)@@ -703,12 +726,20 @@ def _compute_kg_file_scores(kg_ctx: Any) -> dict[str, float]:def _embed_item(page: GeneratedPage) -> tuple[str, str, dict]:- """Build the ``(page_id, text, metadata)`` tuple for embedding."""+ """Build the ``(page_id, text, metadata)`` tuple for embedding.++ ``title`` is load-bearing, not decoration: it feeds the coverage rerank+ haystack and the grounding corpus on the serving side. Omitting it here+ (as this did until 2026-07) left every page embedded at generation time+ with a blank title, while ``reindex`` and ``doctor --repair`` set it, so+ the store disagreed with itself depending on how a page got there.+ """summary = overview_summary(page.content)return (page.page_id,page.content,{+ "title": page.title,"page_type": page.page_type,"target_path": page.target_path,"content": page.content[:600],diff --git a/packages/core/src/repowise/core/generation/selection/selector.py b/packages/core/src/repowise/core/generation/selection/selector.pyindex cd6958ddb..80369db07 100644--- a/packages/core/src/repowise/core/generation/selection/selector.py+++ b/packages/core/src/repowise/core/generation/selection/selector.py@@ -182,6 +182,24 @@ def _passes_tail_floor(path: str, tail_dirs: tuple[str, ...] | None) -> bool:return True+def _is_test_group(files: list[Any]) -> bool:+ """Whether a module group is mostly test files.++ Test directories do not deserve a module page. The same floor already+ applies to the deterministic coverage tail, where excluding test files+ raised retrieval rather than lowering it: they add pages that match on+ vocabulary without carrying an answer. Tests keep their own file pages,+ which is what an agent actually needs when it goes looking for one.++ Majority rather than any, so a production module with a colocated test+ beside it (the Go and Jest convention) keeps its page.+ """+ if not files:+ return False+ tests = sum(1 for p in files if getattr(p.file_info, "is_test", False))+ return tests * 2 > len(files)++def _select_deterministic_tail(files: list[tuple[float, str]],selected_files: list[str],@@ -380,6 +398,8 @@ def _build_module_groups(inputs: SelectionInputs) -> list[tuple[float, ModuleGroscored: list[tuple[float, ModuleGroup]] = []for key, files in groups.items():+ if _is_test_group(files):+ continues = score_module(size=len(files),cohesion=group_cohesion.get(key) or 0.0,diff --git a/packages/core/src/repowise/core/generation/templates/deterministic/scc_page.j2 b/packages/core/src/repowise/core/generation/templates/deterministic/scc_page.j2index 51c25d138..f4b6d3db3 100644--- a/packages/core/src/repowise/core/generation/templates/deterministic/scc_page.j2+++ b/packages/core/src/repowise/core/generation/templates/deterministic/scc_page.j2@@ -48,7 +48,7 @@ Ranked by how many of the cycle's edges each file carries. The file at the top i{% for m in ctx.member_symbols[:20] %}### `{{ m.file_path }}`{% for s in m.symbols[:15] %}-- `{{ s.name }}`{% if s.signature %}: `{{ s.signature | oneline(120) }}`{% endif %}+- `{{ s.name }}`{% if s.signature %}: `{{ s.signature | signature(120) }}`{% endif %}{% endfor %}{% endfor %}{% if ctx.member_symbols | length > 20 %}diff --git a/packages/core/src/repowise/core/generation/templates/deterministic/symbol_spotlight.j2 b/packages/core/src/repowise/core/generation/templates/deterministic/symbol_spotlight.j2index cb940b0d3..9f1c4490d 100644--- a/packages/core/src/repowise/core/generation/templates/deterministic/symbol_spotlight.j2+++ b/packages/core/src/repowise/core/generation/templates/deterministic/symbol_spotlight.j2@@ -17,7 +17,7 @@## Overview-{% if ctx.docstring %}{{ ctx.docstring | trim }}+{% if ctx.docstring %}{{ ctx.docstring | as_markdown }}{% else %}`{{ ctx.symbol_name }}` is {{ "an" if ctx.kind and ctx.kind[0] in "aeiou" else "a" }} {{ ctx.kind or "symbol" }} defined in `{{ ctx.file_path }}`. It carries no docstring.{% endif %}{% if ctx.decorators %}diff --git a/packages/core/src/repowise/core/generation/templates/file_page_tier2.j2 b/packages/core/src/repowise/core/generation/templates/file_page_tier2.j2index ca8923cfa..4a6ff2b3a 100644--- a/packages/core/src/repowise/core/generation/templates/file_page_tier2.j2+++ b/packages/core/src/repowise/core/generation/templates/file_page_tier2.j2@@ -1,48 +1,50 @@{#- Deterministic (no-LLM) tier-2 file page.Rendered straight from the assembled FilePageContext for the long tail- of selected files on large repos. No model call — the content is a+ of selected files on large repos. No model call, the content is astructured, factual stub built entirely from parsed AST + graph signals,and is embedded for search like any other page.++ Written for retrieval as much as for reading: the page names its own+ symbols, its neighbours' file paths and its layer in full, because those+ are the identifiers a question embeds near. Nobody reads a file page end+ to end, so where readability and retrieval disagree, retrieval wins.-#}+{%- set public_syms = ctx.symbols | selectattr("visibility", "equalto", "public") | list -%}# {{ ctx.file_path }}## Overview-{% if ctx.docstring %}{{ ctx.docstring | trim }}-{% else %}`{{ ctx.file_path }}` is a {{ ctx.language }} {% if ctx.is_entry_point %}entry-point {% endif %}{% if ctx.is_test %}test {% endif %}source file in this repository.{% endif %}+{% if ctx.docstring %}{{ ctx.docstring | as_markdown }}{% else %}`{{ ctx.file_path }}` is a {{ ctx.language }} {% if ctx.is_entry_point %}entry-point {% endif %}{% if ctx.is_test %}test {% endif %}source file{% if ctx.kg_layer_name %} in the {{ ctx.kg_layer_name }} layer{% endif %}{% if ctx.community_label %}, part of the {{ ctx.community_label }} module cluster{% endif %}.{% endif %}-{% set public_syms = ctx.symbols | selectattr("visibility", "equalto", "public") | list %}-{% if public_syms %}It exposes {{ public_syms | length }} public symbol{{ "s" if public_syms | length != 1 else "" }}{% if ctx.dependencies %} and depends on {{ ctx.dependencies | length }} internal module{{ "s" if ctx.dependencies | length != 1 else "" }}{% endif %}.{% endif %}+{% if public_syms %}It exposes {{ public_syms | length }} public symbol{{ "s" if public_syms | length != 1 else "" }}{% if ctx.dependencies %} and depends on {{ ctx.dependencies | length }} other file{{ "s" if ctx.dependencies | length != 1 else "" }}{% endif %}.{% endif %}## Public API-{% if public_syms %}-| Symbol | Kind | Signature |+{% if public_syms %}| Symbol | Kind | Signature || --- | --- | --- |-{% for s in public_syms -%}-| `{{ s.name }}` | {{ s.kind }} | {{ (s.signature or "") | replace("|", "\\|") | replace("\n", " ") | truncate(120, true, "…") }} |-{% endfor %}-{% else %}-_No public symbols were extracted from this file._+{% for s in public_syms %}| `{{ s.name }}` | {{ s.kind }} | {{ (s.signature or "") | signature | replace("|", "\\|") }} |+{% endfor %}{% else %}_No public symbols were extracted from this file._{% endif %}+## Depends on-## Dependencies--{% if ctx.dependencies %}-{% for dep in ctx.dependencies -%}-- `{{ dep }}`-{% endfor %}-{% else %}-_No internal dependencies resolved._+{% if ctx.dependencies %}{% for dep in ctx.dependencies[:25] %}- `{{ dep }}`+{% endfor %}{% if ctx.dependencies | length > 25 %}+_and {{ ctx.dependencies | length - 25 }} more._+{% endif %}{% else %}_No internal dependencies resolved._{% endif %}+## Used by-## Usage Notes+{% if ctx.dependents %}Imported by {{ ctx.dependents | length }} file{{ "s" if ctx.dependents | length != 1 else "" }} in this repository.-{% if ctx.dependents %}Imported by {{ ctx.dependents | length }} file{{ "s" if ctx.dependents | length != 1 else "" }} in this repository.{% else %}No internal callers were resolved for this file.{% endif %}-{% if ctx.community_label %} Part of the **{{ ctx.community_label }}** module cluster.{% endif %}-{% if ctx.kg_layer_name %}-**Layer:** {{ ctx.kg_layer_name }} | **Role:** {{ ctx.kg_layer_role }}+{% for dep in ctx.dependents[:25] %}- `{{ dep }}`+{% endfor %}{% if ctx.dependents | length > 25 %}+_and {{ ctx.dependents | length - 25 }} more._+{% endif %}{% else %}_No internal callers were resolved for this file._{% endif %}+{% if ctx.community_label or ctx.kg_layer_name %}## Usage Notes-<!-- Generated deterministically (tier-2, no LLM). -->+{% if ctx.community_label %}Part of the **{{ ctx.community_label }}** module cluster.+{% endif %}{% if ctx.kg_layer_name %}**Layer:** {{ ctx.kg_layer_name }}{% if ctx.kg_layer_role %} | **Role:** {{ ctx.kg_layer_role }}{% endif %}+{% endif %}+{% endif %}<!-- Generated deterministically (tier-2, no LLM). -->diff --git a/packages/ui/__tests__/present/build-present-model.test.ts b/packages/ui/__tests__/present/build-present-model.test.tsindex 32eda3acb..dc8c5da23 100644--- a/packages/ui/__tests__/present/build-present-model.test.ts+++ b/packages/ui/__tests__/present/build-present-model.test.ts@@ -83,7 +83,7 @@ describe("buildPresentModel", () => {target_path: "repo",content: "# Acme\n\nA build tool.\n\n## Details\nmore",metadata: {- layer_order: ["API", "Core"],+ layer_order: ["layer:api", "layer:core"],guided_tour: [{ order: 1, title: "main.py", target_path: "src/main.py", reason: "entry point" },{ order: 2, title: "core.py", target_path: "src/core.py", reason: "the engine" },@@ -100,15 +100,19 @@ describe("buildPresentModel", () => {id: "lc",page_type: "layer_page",title: "Core layer",+ target_path: "layer:core",content: "# Core\n\nThe core does the work and holds the pipeline together nicely.",- metadata: { layer_name: "Core" },+ // Display name deliberately unlike the id: the enrichment pass rewrites+ // layer_name, so ordering must not depend on it.+ metadata: { layer_name: "Engine and Pipeline Core" },});const layerApi = makePage({id: "la",page_type: "layer_page",title: "API layer",+ target_path: "layer:api",content: "# API\n\nThe API exposes endpoints to callers over HTTP with care.",- metadata: { layer_name: "API" },+ metadata: { layer_name: "Typed RPC Interfaces" },});const mainFile = makePage({ id: "mf", target_path: "src/main.py", title: "main.py", content: "# main\n\nStarts the program and wires everything up on boot." });@@ -142,6 +146,7 @@ describe("buildPresentModel", () => {id: "ld",page_type: "layer_page",title: "Data layer",+ target_path: "layer:data",content:"# Data\n\nThe data layer persists and indexes everything the pipeline produces, and it is the durable backbone every other layer leans on.\n\n## Architecture\n\n```mermaid\nflowchart TD\nX-->Y\n```",metadata: { layer_name: "Data" },diff --git a/packages/ui/src/docs/docs-reader.tsx b/packages/ui/src/docs/docs-reader.tsxindex 9e78c2fdb..59072f4a4 100644--- a/packages/ui/src/docs/docs-reader.tsx+++ b/packages/ui/src/docs/docs-reader.tsx@@ -227,6 +227,10 @@ function DocsReaderBody({return out;}, [wikiLinks, page.metadata, pages, page.id]);+ // layer_name is display text only. Joining to the layer page goes through+ // layer_id, whose value is the stable "layer:<slug>" the layer page is keyed+ // by. Reconstructing an id from the name never matched once the enrichment+ // pass had renamed a layer.const layerName =typeof page.metadata?.layer_name === "string" ? page.metadata.layer_name : "";const layerId =@@ -234,24 +238,9 @@ function DocsReaderBody({const layerPage = useMemo(() =>layerId- ? pages.find(- (p) => p.page_type === "layer_page" && p.target_path === layerId,- ) ??- (layerName- ? pages.find(- (p) =>- p.page_type === "layer_page" &&- p.target_path === `layer:${layerName}`,- )- : undefined)- : layerName- ? pages.find(- (p) =>- p.page_type === "layer_page" &&- p.target_path === `layer:${layerName}`,- )- : undefined,- [pages, layerId, layerName],+ ? pages.find((p) => p.page_type === "layer_page" && p.target_path === layerId)+ : undefined,+ [pages, layerId],);const sources = useMemo(() => {diff --git a/packages/ui/src/docs/docs-tree.tsx b/packages/ui/src/docs/docs-tree.tsxindex a63aa4c77..cf1fcdc6e 100644--- a/packages/ui/src/docs/docs-tree.tsx+++ b/packages/ui/src/docs/docs-tree.tsx@@ -373,19 +373,27 @@ export const DOMAIN_SECTION_KEYS = Object.values(SECTION_KEYS);// overview page at generation time. Used to order the Architecture section and// the Modules section so the tree reads as a dependency hierarchy rather than// alphabetically. Returns a rank lookup (lower = closer to the top).-function layerRankLookup(pages: DocPage[]): (layer: string) => number {+//+// Keyed on layer_id, not layer_name. layer_name is display text the LLM+// enrichment pass rewrites, so it drifts between generations. Measured+// 2026-07-23, 11 curated layers against 62 distinct layer_name values, and+// only 82 of 1108 file pages resolved to a rank. layer_id is a stable slug.+function layerRankLookup(pages: DocPage[]): (layerId: string) => number {const overview = pages.find((p) => p.page_type === "repo_overview");- const raw = overview?.metadata?.["layer_order"];+ // layer_order_ids is the join key. layer_order holds display names and is+ // only a fallback for a store generated before the ids were persisted, where+ // ranking stays as good as it ever was rather than silently going flat.+ const raw = overview?.metadata?.["layer_order_ids"] ?? overview?.metadata?.["layer_order"];const order = Array.isArray(raw) ? (raw.filter((x) => typeof x === "string") as string[]) : [];- const index = new Map(order.map((name, i) => [name, i]));- return (layer: string) => index.get(layer) ?? Number.MAX_SAFE_INTEGER;+ const index = new Map(order.map((id, i) => [id, i]));+ return (layerId: string) => index.get(layerId) ?? Number.MAX_SAFE_INTEGER;}-// The layer a module belongs to = the most common layer_name across its files.+// The layer a module belongs to = the most common layer_id across its files.function dominantLayer(files: DocPage[]): string {const counts = new Map<string, number>();for (const f of files) {- const layer = f.metadata?.["layer_name"];+ const layer = f.metadata?.["layer_id"];if (typeof layer === "string" && layer) {counts.set(layer, (counts.get(layer) ?? 0) + 1);}@@ -513,8 +521,11 @@ function buildDomainTree(pages: DocPage[]): TreeNode[] {const layerLeaves = archPages.filter((p) => p.page_type === "layer_page").sort((a, b) => {- const ra = rankOf(a.title.replace(/^Layer:\s*/, ""));- const rb = rankOf(b.title.replace(/^Layer:\s*/, ""));+ // target_path is the stable "layer:<slug>" id the page is keyed by.+ // Scraping the name off the title cannot rank, because the title+ // carries the display name and the spine is keyed on the id.+ const ra = rankOf(a.target_path);+ const rb = rankOf(b.target_path);return ra - rb || a.title.localeCompare(b.title);}).map(toLeaf);diff --git a/packages/ui/src/present/build-present-model.ts b/packages/ui/src/present/build-present-model.tsindex ec2749e0f..83fbaa246 100644--- a/packages/ui/src/present/build-present-model.ts+++ b/packages/ui/src/present/build-present-model.ts@@ -45,15 +45,10 @@ function readTour(overview: DocPage | undefined): TourStop[] {}function readLayerOrder(overview: DocPage | undefined): string[] {- const raw = overview?.metadata?.["layer_order"];+ const raw = overview?.metadata?.["layer_order_ids"] ?? overview?.metadata?.["layer_order"];return Array.isArray(raw) ? raw.filter((x): x is string => typeof x === "string") : [];}-function metaString(page: DocPage, key: string): string | undefined {- const v = page.metadata?.[key];- return typeof v === "string" ? v : undefined;-}-/*** A readable repo name from the overview page title. Titles look like* "Repository Overview: repowise" — prefer the part after the colon, then@@ -150,7 +145,10 @@ export function buildPresentModel(};const layerPages = pages.filter((p) => p.page_type === "layer_page")- .sort((a, b) => rankOf(metaString(a, "layer_name")) - rankOf(metaString(b, "layer_name")))+ // Rank on the layer page's target_path, which is the stable ``layer:<slug>``+ // id. layer_name is display text the LLM rewrites between generations, so+ // ranking on it silently drops every layer to MAX_SAFE_INTEGER.+ .sort((a, b) => rankOf(a.target_path) - rankOf(b.target_path)).slice(0, MAX_LAYER_SLIDES);for (const p of layerPages) {// Layer pages generated with the deterministic architecture diagram embeddiff --git a/tests/unit/generation/test_context_assembler.py b/tests/unit/generation/test_context_assembler.pyindex 99648dda5..8339a4be6 100644--- a/tests/unit/generation/test_context_assembler.py+++ b/tests/unit/generation/test_context_assembler.py@@ -369,3 +369,34 @@ def test_assemble_api_contract_language_matches(sample_config, sample_parsed_filassembler = ContextAssembler(sample_config)ctx = assembler.assemble_api_contract(sample_parsed_file, b"content")assert ctx.language == sample_parsed_file.file_info.language+++# ---------------------------------------------------------------------------+# Dependency edges name other files, never this one+# ---------------------------------------------------------------------------+++def test_foreign_edge_rejects_this_files_own_symbols():+ """The graph carries file->symbol edges, so a file is its own successor.++ Left in, those symbol nodes dominated the rendered dependency list: they+ were 70% of every dependency line on the file pages, and on some pages+ they were the entire list.+ """+ from repowise.core.generation.context.assembler import _is_foreign_edge++ path = "pkg/mod.py"+ assert not _is_foreign_edge("pkg/mod.py", path)+ assert not _is_foreign_edge("pkg/mod.py::Thing", path)+ assert not _is_foreign_edge("pkg/mod.py::Thing::method", path)+ assert not _is_foreign_edge("external:requests", path)+++def test_foreign_edge_keeps_real_neighbours():+ from repowise.core.generation.context.assembler import _is_foreign_edge++ path = "pkg/mod.py"+ assert _is_foreign_edge("pkg/other.py", path)+ assert _is_foreign_edge("pkg/other.py::Thing", path)+ # A path that merely shares a prefix is a different file.+ assert _is_foreign_edge("pkg/mod_extra.py", path)diff --git a/tests/unit/generation/test_deterministic_templates.py b/tests/unit/generation/test_deterministic_templates.pyindex 0603a8572..86d1cdbf5 100644--- a/tests/unit/generation/test_deterministic_templates.py+++ b/tests/unit/generation/test_deterministic_templates.py@@ -261,3 +261,116 @@ def test_summary_skips_the_stats_line():assert _extract_summary(content, skip_metadata=True).startswith("Walks the repository")# Off by default: a model that opens with **Purpose:** means it as prose.assert _extract_summary(content).startswith("**Files:**")+++# ---------------------------------------------------------------------------+# Docstring and signature rendering+# ---------------------------------------------------------------------------+++def test_as_markdown_converts_sphinx_roles_to_code_spans():+ from repowise.core.generation.page_generator.deterministic import as_markdown++ out = as_markdown("See :meth:`Store.get` and :class:`~pkg.Thing`.")+ assert out == "See `Store.get` and `pkg.Thing`."+++def test_as_markdown_converts_double_backtick_literals():+ from repowise.core.generation.page_generator.deterministic import as_markdown++ assert as_markdown("Pass ``None`` to skip.") == "Pass `None` to skip."+++def test_as_markdown_drops_rest_directives():+ from repowise.core.generation.page_generator.deterministic import as_markdown++ out = as_markdown("Body text.\n\n.. note:: internal only\n")+ assert ".. note::" not in out+ assert "Body text." in out+++def test_as_markdown_dedents_so_the_body_is_not_a_code_block():+ """Four leading spaces would make markdown render the body as code."""+ from repowise.core.generation.page_generator.deterministic import as_markdown++ out = as_markdown("Summary line.\n\n Indented continuation.\n")+ assert "\n Indented" not in out+ assert "Indented continuation." in out+++def test_as_markdown_leaves_plain_text_alone():+ from repowise.core.generation.page_generator.deterministic import as_markdown++ assert as_markdown("Just a sentence.") == "Just a sentence."+ assert as_markdown(None) == ""+++def test_signature_collapses_source_whitespace():+ """Signatures span source lines, so raw text carries runs of indentation."""+ from repowise.core.generation.page_generator.deterministic import signature++ raw = "def go(\n a: int,\n b: str,\n ) -> None"+ assert signature(raw) == "def go( a: int, b: str, ) -> None"+++def test_signature_truncates_at_an_argument_boundary_not_mid_token():+ from repowise.core.generation.page_generator.deterministic import signature++ raw = "def go(" + ", ".join(f"argument_number_{i}: int = 0" for i in range(20)) + ") -> None"+ out = signature(raw, limit=80)+ assert out.endswith(" …")+ # The visible tail must be a whole parameter, never half an identifier.+ assert not out.rstrip(" …").rstrip(",").endswith("argument_number")+ assert "argument_number_0: int = 0" in out+++def test_signature_leaves_short_signatures_untouched():+ from repowise.core.generation.page_generator.deterministic import signature++ assert signature("def go(x: int) -> None") == "def go(x: int) -> None"+++def test_as_markdown_leaves_fenced_code_blocks_intact():+ """The double-backtick rule must not chew the fence delimiters."""+ from repowise.core.generation.page_generator.deterministic import as_markdown++ src = "Run it.\n\nExample:\n\n```python\nx = 1\n```\n"+ assert "```python\nx = 1\n```" in as_markdown(src)+++def test_as_markdown_leaves_triple_backtick_spans_intact():+ from repowise.core.generation.page_generator.deterministic import as_markdown++ assert as_markdown("Use ```code``` here.") == "Use ```code``` here."+++def test_as_markdown_does_not_eat_ordinary_colon_text():+ """A permissive role pattern deletes any word:word: before a backtick."""+ from repowise.core.generation.page_generator.deterministic import as_markdown++ assert as_markdown("Time complexity: O(n:m:`k`)") == "Time complexity: O(n:m:`k`)"+ assert as_markdown("See http://x.io/a:b:`c`") == "See http://x.io/a:b:`c`"+++def test_as_markdown_removes_a_directive_body_not_just_its_head():+ """A dangling indented body renders as a code block, the thing we avoid."""+ from repowise.core.generation.page_generator.deterministic import as_markdown++ out = as_markdown(+ "Summary line.\n\n Longer prose.\n\n .. note::\n\n Internal only.\n\n More prose.\n"+ )+ assert "Internal only." not in out+ assert "Longer prose." in out and "More prose." in out+++def test_as_markdown_is_idempotent():+ from repowise.core.generation.page_generator.deterministic import as_markdown++ for src in (+ "See :meth:`Store.get`.",+ "Pass ``None``.",+ "Fence:\n\n```py\nx=1\n```\n",+ "Body.\n\n.. note:: hi\n",+ ):+ once = as_markdown(src)+ assert as_markdown(once) == oncediff --git a/tests/unit/generation/test_embed_metadata.py b/tests/unit/generation/test_embed_metadata.pynew file mode 100644index 000000000..990e8abe4--- /dev/null+++ b/tests/unit/generation/test_embed_metadata.py@@ -0,0 +1,60 @@+"""The metadata handed to the vector store at generation time.++``title`` is in the coverage-rerank haystack and the grounding corpus on the+serving side, so a blank one is a silent ranking tax rather than a cosmetic+bug. It was blank for every page embedded during generation until 2026-07,+while ``reindex`` and ``doctor --repair`` set it correctly, meaning the same+page scored differently depending on which code path last wrote it.+"""++from __future__ import annotations++import pytest++from repowise.core.generation.models import GeneratedPage+from repowise.core.generation.page_generator.orchestrate import _embed_item+from repowise.core.persistence.vector_store.in_memory import InMemoryVectorStore+from repowise.core.providers.embedding.base import MockEmbedder+++def _page(**overrides) -> GeneratedPage:+ fields = {+ "page_id": "file_page:pkg/mod.py",+ "page_type": "file_page",+ "title": "mod.py (ingestion)",+ "content": "# mod.py\n\n## Overview\n\nParses a module into symbols.\n",+ "source_hash": "abc123",+ "model_name": "template",+ "provider_name": "template",+ "input_tokens": 0,+ "output_tokens": 0,+ "cached_tokens": 0,+ "generation_level": 1,+ "target_path": "pkg/mod.py",+ "created_at": "2026-07-23T00:00:00Z",+ "updated_at": "2026-07-23T00:00:00Z",+ }+ fields.update(overrides)+ return GeneratedPage(**fields) # type: ignore[arg-type]+++def test_embed_metadata_carries_the_page_title():+ _pid, _text, meta = _embed_item(_page())+ assert meta["title"] == "mod.py (ingestion)"+++def test_embed_metadata_title_is_never_silently_blank():+ """A page always has a title; the metadata must not drop it."""+ _pid, _text, meta = _embed_item(_page(title="Retrieval Pipeline"))+ assert meta.get("title"), "blank title in embed metadata is the 2026-07 bug"+++async def test_title_survives_into_the_vector_store():+ """End-to-end through the store the generation path actually writes to."""+ store = InMemoryVectorStore(MockEmbedder())+ await store.embed_batch([_embed_item(_page())])++ results = await store.search("parses a module", limit=1)+ assert results+ assert results[0].title == "mod.py (ingestion)"diff --git a/tests/unit/generation/test_kg_aware_file_pages.py b/tests/unit/generation/test_kg_aware_file_pages.pyindex 902558acf..fdacb279d 100644--- a/tests/unit/generation/test_kg_aware_file_pages.py+++ b/tests/unit/generation/test_kg_aware_file_pages.py@@ -249,8 +249,20 @@ class TestFilePageTemplate:from jinja2 import Environment, FileSystemLoaderfrom pathlib import Path+ from repowise.core.generation.page_generator.deterministic import (+ as_markdown,+ oneline,+ signature,+ )+template_dir = Path(__file__).resolve().parents[3] / "packages" / "core" / "src" / "repowise" / "core" / "generation" / "templates"- return Environment(loader=FileSystemLoader(str(template_dir)))+ env = Environment(loader=FileSystemLoader(str(template_dir)))+ # Mirror the production environment, which registers these in+ # PageGenerator.__init__. Without them the templates fail to compile.+ env.filters["oneline"] = oneline+ env.filters["as_markdown"] = as_markdown+ env.filters["signature"] = signature+ return envdef test_tier1_template_renders_kg_layer(self, jinja_env):tmpl = jinja_env.get_template("file_page.j2")diff --git a/tests/unit/generation/test_layers.py b/tests/unit/generation/test_layers.pyindex c039c340a..24dd49414 100644--- a/tests/unit/generation/test_layers.py+++ b/tests/unit/generation/test_layers.py@@ -7,6 +7,7 @@ from repowise.core.generation.layers import (DOCS_TOOLING_LAYER,compute_layer_order,infer_layer,+ layer_key,)# ---------------------------------------------------------------------------@@ -277,6 +278,45 @@ def test_compute_layer_order_stable_without_edges():assert order == ["API", "Data", "Utility"]+def test_compute_layer_order_ranks_layer_ids_like_layer_names():+ """The spine is keyed on the stable ``layer:<slug>`` id, not the display name.++ ``layer_name`` is rewritten by the layer-enrichment pass, so it drifts+ between generations and cannot be a join key. Ordering must produce the+ same stack whichever spelling it is handed.+ """+ by_name = compute_layer_order(+ {"api/h.py": "API", "services/s.py": "Service", "models/m.py": "Data"},+ [("api/h.py", "services/s.py"), ("services/s.py", "models/m.py")],+ )+ by_id = compute_layer_order(+ {+ "api/h.py": "layer:api",+ "services/s.py": "layer:service",+ "models/m.py": "layer:data",+ },+ [("api/h.py", "services/s.py"), ("services/s.py", "models/m.py")],+ )+ assert by_id == [f"layer:{name.lower()}" for name in by_name]+++def test_compute_layer_order_pins_tests_when_given_layer_ids():+ """The pinning rule keys on the slug, so it survives the id spelling."""+ file_layers = {+ "api/h.py": "layer:api",+ "services/s.py": "layer:service",+ "tests/test_h.py": "layer:test",+ }+ edges = [("api/h.py", "services/s.py"), ("tests/test_h.py", "api/h.py")]+ order = compute_layer_order(file_layers, edges)+ assert order[-1] == "layer:test"+++def test_layer_key_normalises_both_spellings():+ assert layer_key("UI") == layer_key("layer:ui") == "ui"+ assert layer_key("Docs & Tooling") == layer_key("layer:docs-tooling") == "docs-tooling"++def test_compute_layer_order_single_layer():assert compute_layer_order({"a.py": "API"}, []) == ["API"]assert compute_layer_order({}, []) == []diff --git a/tests/unit/generation/test_page_selection.py b/tests/unit/generation/test_page_selection.pyindex cfb165de0..15e2efea3 100644--- a/tests/unit/generation/test_page_selection.py+++ b/tests/unit/generation/test_page_selection.py@@ -81,3 +81,40 @@ def test_windows_target_paths_normalize() -> None:records = [PageRecord("file_page:src/a.py", "file_page", "src\\a.py", is_template=True)]result = resolve_page_selection(records, PageSelectionIntent(path_globs=("src",)))assert result.page_ids == {"file_page:src/a.py"}+++# ---------------------------------------------------------------------------+# Test directories do not get a module page+# ---------------------------------------------------------------------------+++def _pf(path, is_test):+ from types import SimpleNamespace++ return SimpleNamespace(file_info=SimpleNamespace(path=path, is_test=is_test))+++def test_a_test_directory_is_not_a_module():+ from repowise.core.generation.selection.selector import _is_test_group++ assert _is_test_group([_pf("tests/test_a.py", True), _pf("tests/test_b.py", True)])+++def test_a_production_module_with_a_colocated_test_keeps_its_page():+ """Go and Jest put the test beside the source; that is still a module."""+ from repowise.core.generation.selection.selector import _is_test_group++ files = [_pf("pkg/a.go", False), _pf("pkg/b.go", False), _pf("pkg/a_test.go", True)]+ assert not _is_test_group(files)+++def test_an_even_split_is_not_a_test_group():+ from repowise.core.generation.selection.selector import _is_test_group++ assert not _is_test_group([_pf("pkg/a.py", False), _pf("pkg/a_test.py", True)])+++def test_empty_group_is_not_a_test_group():+ from repowise.core.generation.selection.selector import _is_test_group++ assert not _is_test_group([])diff --git a/tests/unit/generation/test_provenance.py b/tests/unit/generation/test_provenance.pyindex b956f9134..dbe0f8adc 100644--- a/tests/unit/generation/test_provenance.py+++ b/tests/unit/generation/test_provenance.py@@ -56,6 +56,29 @@ def test_layer_metadata_attached():assert page.metadata["layer_role"] == "entry_point"+def test_curated_layer_without_an_id_still_gets_one():+ """A curated layer_name with no id used to leave the page unjoinable.++ Consumers group on layer_id, so a page carrying only the display name+ dropped out of the architecture ordering entirely.+ """+ page = _page()+ _attach_file_provenance(page, _ctx(kg_layer_name="Shared UI Components"))+ assert page.metadata["layer_id"] == "layer:shared-ui-components"+++def test_every_file_page_carries_a_layer_id():+ for ctx in (+ _ctx(),+ _ctx(kg_layer_name="Domain", kg_layer_id="layer:domain"),+ _ctx(kg_layer_name="Ingestion and Reasoning"),+ _ctx(file_path="src/api/users.py"),+ ):+ page = _page()+ _attach_file_provenance(page, ctx)+ assert page.metadata.get("layer_id", "").startswith("layer:")++def test_no_kg_layer_falls_back_to_inferred_layer():# Every file page must carry a layer_name so the Architecture tree can# group it; with no KG layer it is inferred from the path, and the@@ -95,3 +118,15 @@ def test_dependencies_capped_at_ten():page = _page()_attach_file_provenance(page, _ctx(dependencies=[f"d{i}.py" for i in range(20)]))assert len(page.metadata["sources"]) == 10+++def test_fallback_layer_id_matches_the_id_curation_would_mint():+ """A near-miss id points a file page at a layer page that does not exist."""+ from repowise.core.analysis.knowledge_graph import _slugify+ from repowise.core.generation.layers import DEFAULT_LAYER, DOCS_TOOLING_LAYER++ for name in ("UI", "CLI", "API", "Service", "Data", "Types", "Config",+ "Utility", "Test", "Middleware", DEFAULT_LAYER, DOCS_TOOLING_LAYER):+ page = _page()+ _attach_file_provenance(page, _ctx(kg_layer_name=name))+ assert page.metadata["layer_id"] == f"layer:{_slugify(name)}"