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): the overview says what the repository does, in its own words (#1249)

Raghav Chamadiya2d4161642a93
diff --git a/packages/core/src/repowise/core/generation/concept_tree/vocabulary.py b/packages/core/src/repowise/core/generation/concept_tree/vocabulary.py
index f20f52cab..2be2e9eca 100644
--- a/packages/core/src/repowise/core/generation/concept_tree/vocabulary.py
+++ b/packages/core/src/repowise/core/generation/concept_tree/vocabulary.py
@@ -812,17 +812,17 @@ def _scan_tree(repo_root: Path) -> tuple[list[tuple[str, str]], frozenset[str]]:
_WORD_GAP = re.compile(r"[\s_\-]+")
-def _term_words(term: str) -> list[str]:
+def term_words(term: str) -> list[str]:
return [w for w in _WORD_GAP.split(term) if w]
-def _phrase_pattern(term: str) -> re.Pattern[str]:
+def phrase_pattern(term: str) -> re.Pattern[str]:
"""Match a term however the code spells the gaps between its words.
``bug magnet`` has to find ``bug magnet``, ``bug-magnet`` and
``bug_magnet``, because the docs write it one way and the code the other.
"""
- words = [re.escape(w) for w in _term_words(term)]
+ words = [re.escape(w) for w in term_words(term)]
return re.compile(r"\b" + r"[\s_\-]+".join(words) + r"\b", re.I)
@@ -885,7 +885,7 @@ def _survives_single_word_test(term: str, dir_names: frozenset[str]) -> bool:
everything and stops nothing. "dead_code" must not be what lets "Code"
through.
"""
- words = _term_words(term)
+ words = term_words(term)
if len(words) != 1:
return True
word = words[0]
@@ -950,7 +950,7 @@ def extract_house_terms(
_warn_empty(repo_root)
return []
- patterns = {c.term.lower(): _phrase_pattern(c.term) for c in candidates}
+ patterns = {c.term.lower(): phrase_pattern(c.term) for c in candidates}
# Every match of a term's pattern contains that term's first word, so a
# substring test on the lowercased prose rejects most (file, term) pairs
# before the regex engine is started. It is a necessary condition and
@@ -959,7 +959,7 @@ def extract_house_terms(
# pairs. It is worth the two lines: the corpus is every source file in the
# repository and the pattern set is up to two hundred, so the product is
# where the whole cost of mining sits.
- first_words = {c.term.lower(): _term_words(c.term)[0].lower() for c in candidates}
+ first_words = {c.term.lower(): term_words(c.term)[0].lower() for c in candidates}
code_files: dict[str, list[str]] = {c.term.lower(): [] for c in candidates}
code_definitions: dict[str, tuple[str, str]] = {}
prose_corpus, dir_names = _scan_tree(repo_root)
@@ -1018,7 +1018,7 @@ def extract_house_terms(
terms.sort(
key=lambda t: (
-t.doc_frequency,
- len(_term_words(t.term)) == 1,
+ len(term_words(t.term)) == 1,
-t.code_frequency,
t.term.lower(),
)
diff --git a/packages/core/src/repowise/core/generation/overview_tables.py b/packages/core/src/repowise/core/generation/overview_tables.py
index 8054d12e8..aeed57f19 100644
--- a/packages/core/src/repowise/core/generation/overview_tables.py
+++ b/packages/core/src/repowise/core/generation/overview_tables.py
@@ -14,12 +14,17 @@ page, stable across updates that changed no code, and assertable in a test.
from __future__ import annotations
import re
+from collections.abc import Iterable, Sequence
+from dataclasses import dataclass
import structlog
+from .concept_tree.vocabulary import HouseTerm, phrase_pattern, term_words
+
log = structlog.get_logger(__name__)
PACKAGE_TABLE_HEADING = "## Packages"
+CAPABILITY_TABLE_HEADING = "## What it does"
# The heading plus everything up to the next heading of the same or higher
# level. Anchored at a line start so a mention inside prose is not a match.
@@ -72,3 +77,252 @@ def embed_package_table(content: str, table: str | None) -> str:
return _PACKAGE_SECTION_RE.sub(lambda _m: section, content, count=1)
sep = "" if content.endswith("\n") else "\n"
return f"{content}{sep}\n{section}"
+
+
+# ---------------------------------------------------------------------------
+# Capabilities
+# ---------------------------------------------------------------------------
+#
+# The overview's opening question is "what does this thing do", and the answer
+# should be in the repository's own words rather than in the generic vocabulary
+# of static analysis. The mined house terms are those words. Ranked by document
+# frequency alone they are not front-page material: on this repository the top
+# of that list holds the repository's own name, "DONE", "Architecture" and
+# "Files changed", which would put junk in half the rows.
+#
+# So a term reaches this table only with corroboration from a second,
+# independently-derived artifact: a module page — built from the dependency
+# graph, with no knowledge of the documents — has to name it in its title or
+# its summary. That needs no stopword list and no per-repository tuning.
+
+_MAX_CAPABILITY_ROWS = 6
+#: Long enough for a sentence, short enough that a row stays one line to read.
+_MAX_CAPABILITY_DEFINITION = 160
+
+_CAPABILITY_SECTION_RE = re.compile(
+ r"^##[ \t]+What it does[ \t]*\n(?:.*?)(?=^#{1,2}[ \t]|\Z)",
+ re.MULTILINE | re.DOTALL,
+)
+
+
+@dataclass(frozen=True)
+class Capability:
+ """One row: a mined term, what the repository says it is, and where from."""
+
+ term: str
+ #: The repository's own sentence, or ``None``. Never invented — a term the
+ #: repository named without defining is still a capability, and writing a
+ #: definition for it is the one thing the vocabulary miner refuses to do.
+ definition: str | None
+ #: The document or source file the sentence was read from, falling back to
+ #: the first document that named the term. Always a real path.
+ source_path: str
+ #: How many module pages name it. Kept for the log, not rendered — it is
+ #: the strength of the corroboration, not a fact about the repository.
+ corroborating_pages: int
+
+
+def select_capabilities(
+ house_terms: Sequence[HouseTerm],
+ module_names: Iterable[str],
+ *,
+ limit: int = _MAX_CAPABILITY_ROWS,
+) -> list[Capability]:
+ """The terms worth putting on the front page, in the order they go there.
+
+ ``module_names`` are what the structural side calls the parts of the
+ system: the module groups' titles. They are the corroborating artifact — a
+ module group is cut from the dependency graph and named from the code, so
+ a term appearing in one was arrived at twice, from the documents and from
+ the structure, independently.
+
+ Titles only. Community labels and directory keys were tried and measured
+ worse: a label like "Ingestion and Analysis Engine" is broad enough to
+ corroborate almost any single common word, which put "Architecture" and
+ "Workspace" on the front page of a real render.
+
+ Groups rather than written module *pages*, deliberately. A group exists on
+ every run, so a scoped run that regenerates the overview alone selects the
+ same rows as a full one — a front-page section that shrinks depending on
+ how generation was invoked is the instability these deterministic tables
+ exist to remove. It is also the stronger claim of independence: a group's
+ name is computed, while a page's summary is model-written and resampled.
+
+ The cost is reach. Measured on django, matching titles and summaries of
+ written pages corroborates 5 terms where names alone corroborate 2. The
+ upgrade path is to read module summaries out of the store rather than out
+ of this run, which would be both stable and rich; it needs level 6 to
+ become async and the vector store to be present, so it is not done here.
+
+ **Multi-word terms come first.** Not as a filter — a single word still
+ reaches the table when there is room — but ahead of single words, because
+ a subsystem is nearly always named with two words ("blast radius", "dead
+ code", "change risk") and an ordinary English word with one. The ranking
+ in :func:`~...vocabulary.extract_house_terms` already encodes that as its
+ tiebreak; here it leads, because document frequency barely discriminates
+ at six rows (most repositories have two or three documents worth mining,
+ so nearly every term ties at one) and one junk row out of six is expensive.
+
+ Ordering is total and derived only from the inputs, so two runs over an
+ unchanged repository select the same rows in the same order.
+ """
+ corpus = [name for name in module_names if name]
+ selected: list[Capability] = []
+ for term in house_terms:
+ pattern = phrase_pattern(term.term)
+ hits = sum(1 for page in corpus if pattern.search(page))
+ if not hits:
+ continue
+ definition = term.definition
+ if definition and not _is_a_sentence(definition):
+ # Keep the row, drop the claim. The capability is real — the
+ # structure corroborated it — but the prose nearest the term is
+ # not a statement about it, and an em dash misinforms nobody.
+ log.info(
+ "overview_capability_definition_rejected",
+ term=term.term,
+ text=" ".join(definition.split())[:120],
+ )
+ definition = None
+ # Cite where the sentence came from, or -- when there is no sentence,
+ # including one just rejected -- the document that named the term.
+ # Citing the home of prose the table declined to quote would point a
+ # reader at a line that is not there.
+ source = (term.definition_source if definition else None) or (
+ term.source_paths[0] if term.source_paths else None
+ )
+ if source is None:
+ # A term with no path at all cannot be cited, and an uncitable row
+ # on the front page is the shape of claim this wiki does not make.
+ continue
+ selected.append(
+ Capability(
+ term=term.term,
+ definition=definition,
+ source_path=source,
+ corroborating_pages=hits,
+ )
+ )
+
+ selected.sort(key=lambda c: (len(term_words(c.term)) == 1, -c.corroborating_pages, c.term))
+ kept = selected[:limit]
+ log.info(
+ "overview_capabilities_selected",
+ mined=len(house_terms),
+ corroborated=len(selected),
+ kept=len(kept),
+ terms=[c.term for c in kept],
+ )
+ if house_terms and not selected:
+ # The documents name things the structure does not. That is a real
+ # answer about a repository — marketing vocabulary with no cluster
+ # behind it — but it is also what a corroboration corpus arriving
+ # empty looks like, so the two counts that separate them are logged
+ # rather than the section just not appearing.
+ log.warning(
+ "overview_capabilities_uncorroborated",
+ mined=len(house_terms),
+ module_names=len(corpus),
+ )
+ return kept
+
+
+# A mined "definition" is whatever prose sat nearest the term, and near a term
+# in a README that is often not a sentence about it. Two real examples from
+# this repository's own front page:
+#
+# CLI -> "repowise init [PATH] # index a codebase (one-time; ...)"
+# Distill -> "`repowise distill <cmd>` compresses command output *before*
+# the agent reads it:"
+#
+# The first is a line of shell with an inline comment. The second is a lead-in
+# that ends on a colon because the explanation is the code block underneath.
+# Neither says what the thing is, and an em dash is a better answer than
+# either: the reader learns the capability exists and is not misinformed about
+# what it does.
+
+#: A command line rather than a sentence: a shell comment, a prompt, an option
+#: flag, a redirect or a pipeline.
+#:
+#: The redirect and pipe test requires whitespace on both sides. Bare ``<`` and
+#: ``>`` reject real prose: "Decisions are co-located ... under the
+#: ``decision:<record_id>`` namespace" is a sentence, and the angle brackets in
+#: it are a placeholder, not a redirect.
+_LOOKS_LIKE_COMMAND = re.compile(r"(^\s*[$>]\s|\s#\s|\s--?[a-zA-Z]|\s[|<>]\s)")
+#: Ends where the real explanation begins — a colon, or an unclosed opener.
+_TRAILS_OFF = (":", ",", ";", "-", "—", "–", "(", "[")
+
+
+def _is_a_sentence(text: str) -> bool:
+ """Whether mined prose reads as a statement about the term.
+
+ Deliberately shallow. This is not grammar checking — it is the difference
+ between a sentence and a fragment of shell, and getting it wrong in the
+ strict direction costs a definition, which the table already renders as an
+ em dash. Getting it wrong the other way puts a command line on the front
+ page as though it explained something.
+ """
+ text = " ".join(text.split())
+ # Three, not four: "Blast-radius request/response models." is terse and is
+ # still the repository's own answer to what the term means. Two words is
+ # where the fragments live ("See below", "Two parts").
+ if len(text.split()) < 3:
+ return False
+ if text.rstrip().endswith(_TRAILS_OFF):
+ return False
+ if _LOOKS_LIKE_COMMAND.search(text):
+ return False
+ # A statement starts with a word, not with punctuation or a code fence.
+ return text[:1].isalpha()
+
+
+def _cell(text: str) -> str:
+ """Text safe to put in a markdown table cell.
+
+ A pipe ends the cell wherever it appears, and mined prose is the
+ repository's text rather than ours — a definition that quotes a shell
+ pipeline or a reStructuredText grid row would otherwise shift every column
+ to its right.
+ """
+ return " ".join(text.split()).replace("|", "\\|")
+
+
+def build_capability_table(capabilities: Sequence[Capability]) -> str | None:
+ """Render ``Capability | What it is | Where it is written`` as markdown.
+
+ Returns ``None`` when nothing was selected. A repository whose documents
+ name nothing its code also spells is a supported and common outcome, and a
+ header over an empty table says less than no section at all.
+ """
+ if not capabilities:
+ log.info("overview_capability_table_empty")
+ return None
+
+ lines = [
+ "| Capability | What it is | Where it is written |",
+ "|---|---|---|",
+ ]
+ for cap in capabilities:
+ definition = _cell(cap.definition) if cap.definition else "—"
+ if len(definition) > _MAX_CAPABILITY_DEFINITION:
+ definition = definition[: _MAX_CAPABILITY_DEFINITION - 1].rstrip() + "…"
+ lines.append(f"| {_cell(cap.term)} | {definition} | `{_cell(cap.source_path)}` |")
+ log.debug("overview_capability_table_built", rows=len(capabilities))
+ return "\n".join(lines)
+
+
+def embed_capability_table(content: str, table: str | None) -> str:
+ """Return *content* with *table* under ``## What it does``, idempotently.
+
+ Same contract as :func:`embed_package_table`: an existing section of that
+ name is replaced wholesale, so a reused or cached page picks up the current
+ selection instead of accumulating a second one.
+ """
+ if not table:
+ return content
+
+ section = f"{CAPABILITY_TABLE_HEADING}\n\n{table}\n\n"
+ if _CAPABILITY_SECTION_RE.search(content):
+ return _CAPABILITY_SECTION_RE.sub(lambda _m: section, content, count=1)
+ sep = "" if content.endswith("\n") else "\n"
+ return f"{content}{sep}\n{section}"
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 025815148..d362ec46c 100644
--- a/packages/core/src/repowise/core/generation/page_generator/levels.py
+++ b/packages/core/src/repowise/core/generation/page_generator/levels.py
@@ -275,7 +275,67 @@ def build_level4_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
return coros
-def build_level6_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
+async def _module_corroboration(run: _GenerationRun) -> list[str]:
+ """What the structural side calls the parts of the system.
+
+ One string per module group: its title, plus its summary. A module group
+ is cut from the dependency graph and named from the code, so a mined term
+ appearing in one was arrived at twice — from the documents and from the
+ structure — independently.
+
+ Titles alone are about ninety short strings, which is too thin a net: it
+ misses "Knowledge Graph" and "Code Health" while letting "Architecture"
+ and "Workspace" through on an incidental word. The summaries are what make
+ the corroboration mean something.
+
+ Summaries come from this run when level 4 wrote the page, and from the
+ store when it did not. Both together, because either alone is wrong: the
+ run alone empties the corpus on every scoped update and the section
+ vanishes from the front page, and the store alone is one generation stale
+ on a full run. Never raises — a store that cannot answer costs reach, not
+ a page.
+ """
+ groups = run.sel_module_groups
+ if not groups:
+ return []
+
+ summaries: dict[str, str] = {}
+ missing: list[str] = []
+ for mg in groups:
+ written = run.completed_page_summaries.get(mg.key)
+ if written:
+ summaries[mg.key] = written
+ else:
+ missing.append(mg.key)
+
+ if missing and run.vector_store is not None:
+ try:
+ batch = await run.vector_store.get_page_summaries_by_paths(missing)
+ except Exception as exc:
+ # Reach, not correctness. Said out loud because a quietly thinner
+ # corpus reads downstream as "the structure does not name this".
+ log.warning(
+ "generation.overview_corroboration_store_read_failed",
+ repo_name=run.repo_name,
+ wanted=len(missing),
+ error=str(exc),
+ )
+ else:
+ for path, payload in batch.items():
+ summary = (payload or {}).get("summary")
+ if summary:
+ summaries[path] = summary
+
+ log.info(
+ "generation.overview_corroboration_corpus",
+ groups=len(groups),
+ from_this_run=sum(1 for mg in groups if run.completed_page_summaries.get(mg.key)),
+ with_summary=len(summaries),
+ )
+ return [f"{mg.display}\n{summaries.get(mg.key, '')}" for mg in groups]
+
+
+async def build_level6_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
"""Level 6 (repo_overview).
The overview carries the architecture map. That map used to sit on a page
@@ -285,6 +345,7 @@ def build_level6_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
uniquely had, so it moved here and the page retired; its id redirects.
"""
from ..architecture_mermaid import build_overview_mermaid
+ from ..overview_tables import select_capabilities
gen = run.gen
overview_mermaid = build_overview_mermaid(run.kg_ctx)
@@ -298,6 +359,24 @@ def build_level6_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
)
coros: list[tuple[str, Any]] = []
if run._emit(compute_page_id("repo_overview", run.repo_name)):
+ # What the repository calls its own capabilities, in its own words.
+ # Mined once per run and shared with level 8. A term reaches the page
+ # only when the structural side names it too, so the front page never
+ # carries a word the documents used and the graph never confirmed.
+ #
+ # Module *groups*, not written module pages: a group is cut and named
+ # on every run, so a scoped run that regenerates the overview alone
+ # selects the same rows as a full one.
+ capabilities = select_capabilities(_mine_house_terms(run), await _module_corroboration(run))
+ if not capabilities:
+ # No table beats an empty one, but a front-page section that
+ # quietly stops appearing is the failure shape this repository has
+ # shipped before. Said out loud with the counts that explain it.
+ log.info(
+ "generation.overview_capability_table_absent",
+ repo_name=run.repo_name,
+ module_groups=len(run.sel_module_groups),
+ )
coros.append(
(
compute_page_id("repo_overview", run.repo_name),
@@ -318,6 +397,7 @@ def build_level6_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
# directory the walker skipped reads as zero rather than
# going unmentioned.
parsed_files=run.parsed_files,
+ capabilities=capabilities,
),
)
)
@@ -341,11 +421,14 @@ def build_level7_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
def _mine_house_terms(run: _GenerationRun) -> tuple[HouseTerm, ...]:
- """The repository's own vocabulary, read once for the whole onboarding level.
+ """The repository's own vocabulary, read once per run.
Mined here rather than inside a subkind because reading it walks the
repository: once per run is a cost, once per slot is the same cost eight
- times over for the same answer.
+ times over for the same answer. Two levels want it now — the overview at
+ 6 and onboarding at 8 — so the result is memoised on the run rather than
+ the walk being paid twice. A run that emits neither still pays nothing,
+ because neither caller reaches this.
``repo_path`` is optional on every generation entry point, and a run
without one has nothing to read. That is reported rather than absorbed —
@@ -356,6 +439,10 @@ def _mine_house_terms(run: _GenerationRun) -> tuple[HouseTerm, ...]:
from ..concept_tree.vocabulary import extract_house_terms
from ..report import record_house_terms
+ cached = getattr(run, "_house_terms", None)
+ if cached is not None:
+ return cached
+
if not run.repo_path:
log.warning(
"onboarding.house_terms_skipped",
@@ -363,6 +450,7 @@ def _mine_house_terms(run: _GenerationRun) -> tuple[HouseTerm, ...]:
reason="no_repo_path",
)
record_house_terms(None)
+ run._house_terms = ()
return ()
# The names the codebase defines. A term matching one may be rendered in
@@ -384,6 +472,7 @@ def _mine_house_terms(run: _GenerationRun) -> tuple[HouseTerm, ...]:
terms=len(terms),
top=[t.term for t in terms[:8]],
)
+ run._house_terms = terms
return terms
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 ca67ef987..a84f8c5b0 100644
--- a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
+++ b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
@@ -714,7 +714,7 @@ class _GenerationRun:
# Levels 6 (repo_overview), 7 (infra_page), and 8 (onboarding) share
# no data dependencies — run merged.
final = (
- _levels.build_level6_coros(self)
+ await _levels.build_level6_coros(self)
+ _levels.build_level7_coros(self)
+ _levels.build_level8_coros(self)
)
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 60ab52dd8..c5be7354b 100644
--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py
+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py
@@ -9,6 +9,7 @@ each module under the project's 400-line ceiling.
from __future__ import annotations
import uuid
+from collections.abc import Sequence
from dataclasses import replace
from typing import Any
@@ -26,7 +27,13 @@ from ..models import (
GeneratedPage,
compute_source_hash,
)
-from ..overview_tables import build_package_table, embed_package_table
+from ..overview_tables import (
+ Capability,
+ build_capability_table,
+ build_package_table,
+ embed_capability_table,
+ embed_package_table,
+)
log = structlog.get_logger(__name__)
@@ -89,6 +96,24 @@ def _with_package_table(page: GeneratedPage, package_stats: list[dict]) -> Gener
return page
+def _with_capability_table(
+ page: GeneratedPage, capabilities: Sequence[Capability]
+) -> GeneratedPage:
+ """Embed the capability table into an already-built page.
+
+ Same three paths and the same reasoning as the package table. What the
+ repository calls its own capabilities is read from its documents and
+ corroborated against its module pages, both of which the run already
+ holds — so the model page, the ``--no-prose`` page and the outage fallback
+ carry identical bytes, and a reader diffing two updates sees a code change
+ rather than a re-roll.
+ """
+ if not capabilities:
+ return page
+ page.content = embed_capability_table(page.content, build_capability_table(capabilities))
+ return page
+
+
class PerTypeGenerationMixin:
"""Per-type ``generate_*`` methods. Requires the host to provide
``_assembler``, ``_render``, ``_call_provider`` and
@@ -323,6 +348,7 @@ class PerTypeGenerationMixin:
overview_mermaid: str | None = None,
source_map: dict[str, bytes] | None = None,
parsed_files: list[ParsedFile] | None = None,
+ capabilities: Sequence[Capability] = (),
) -> GeneratedPage:
ctx = self._assembler.assemble_repo_overview(
repo_structure,
@@ -358,7 +384,8 @@ class PerTypeGenerationMixin:
ctx, repo_name, f"Repository Overview: {repo_name}", repo_git_summary
)
page = _with_architecture_map(
- _with_package_table(stub, ctx.package_stats), overview_mermaid
+ _with_capability_table(_with_package_table(stub, ctx.package_stats), capabilities),
+ overview_mermaid,
)
selection = self._disabled_source_evidence("repo_overview", "deterministic_generation")
return self._attach_source_evidence(page, "repo_overview", selection)
@@ -375,8 +402,11 @@ class PerTypeGenerationMixin:
ctx, repo_name, f"Repository Overview: {repo_name}", repo_git_summary
)
page = _with_architecture_map(
- _with_package_table(
- _stub_fallback(stub, "repo_overview", exc), ctx.package_stats
+ _with_capability_table(
+ _with_package_table(
+ _stub_fallback(stub, "repo_overview", exc), ctx.package_stats
+ ),
+ capabilities,
),
overview_mermaid,
)
@@ -392,6 +422,13 @@ class PerTypeGenerationMixin:
response.content, build_package_table(ctx.package_stats)
),
)
+ if capabilities:
+ response = replace(
+ response,
+ content=embed_capability_table(
+ response.content, build_capability_table(capabilities)
+ ),
+ )
if overview_mermaid:
response = replace(
response,
diff --git a/tests/unit/generation/test_overview_capability_table.py b/tests/unit/generation/test_overview_capability_table.py
new file mode 100644
index 000000000..d425653c5
--- /dev/null
+++ b/tests/unit/generation/test_overview_capability_table.py
@@ -0,0 +1,476 @@
+"""The overview's capability table, and the rule that decides its rows.
+
+The selection rule is the whole of this feature. Mined vocabulary ranked by
+document frequency alone is not front-page material: on this repository the
+top of that list holds "DONE", "Architecture" and "Files changed" alongside
+the real capabilities, and half the rows would be junk.
+
+So a term reaches the page only with corroboration from a second,
+independently-derived artifact — a module page, grouped from the dependency
+graph and written from the code, has to name it. Nothing here is a stopword
+list, and nothing here is tuned per repository.
+
+Like the package table, the result is embedded after the page is written, so
+the model page, the ``--no-prose`` page and the provider-outage fallback carry
+identical bytes.
+"""
+
+from __future__ import annotations
+
+import pytest
+from structlog.testing import capture_logs
+
+from repowise.core.generation.concept_tree.vocabulary import HouseTerm
+from repowise.core.generation.context_assembler import ContextAssembler
+from repowise.core.generation.overview_tables import (
+ CAPABILITY_TABLE_HEADING,
+ build_capability_table,
+ embed_capability_table,
+ select_capabilities,
+)
+from repowise.core.ingestion.models import PackageInfo, RepoStructure
+
+from .conftest import _make_file_info
+
+
+def _term(
+ term: str,
+ *,
+ definition: str | None = None,
+ definition_source: str | None = None,
+ source_paths: tuple[str, ...] = ("README.md",),
+ doc_frequency: int = 1,
+ code_frequency: int = 5,
+) -> HouseTerm:
+ return HouseTerm(
+ term=term,
+ definition=definition,
+ definition_source=definition_source,
+ source_paths=source_paths,
+ doc_frequency=doc_frequency,
+ code_frequency=code_frequency,
+ is_indexed_symbol=False,
+ )
+
+
+#: What the structural side calls the parts of the system: module group
+#: titles, their community labels, and their paths. Cut from the dependency
+#: graph and named from the code, with no knowledge of the documents.
+MODULES = [
+ "Dead Code and Reachability Analysis",
+ "Blast Radius UI",
+ "Ledger Postings",
+ "src/analysis/dead_code",
+]
+
+
+# ---------------------------------------------------------------------------
+# The selection rule
+# ---------------------------------------------------------------------------
+
+
+def test_a_term_no_module_page_names_does_not_reach_the_page():
+ """The gate. "DONE" is a real heading in this repository's own documents
+ and leads the frequency ranking; no module page has ever mentioned it."""
+ picked = select_capabilities([_term("DONE"), _term("Dead code")], MODULES)
+ assert [c.term for c in picked] == ["Dead code"]
+
+
+def test_corroboration_may_come_from_a_title_or_from_a_path():
+ """Both are what the structure calls a part of the system."""
+ by_title = select_capabilities([_term("Blast radius")], MODULES)
+ by_path = select_capabilities([_term("Dead code")], ["src/analysis/dead_code"])
+ assert [c.term for c in by_title] == ["Blast radius"]
+ assert [c.term for c in by_path] == ["Dead code"]
+
+
+def test_multi_word_terms_come_before_single_word_ones():
+ """A subsystem is nearly always named with two words and an ordinary
+ English word with one. "Analysis" is corroborated — it is in a module
+ title — and it is still not what the front page should lead with."""
+ picked = select_capabilities([_term("Analysis"), _term("Dead code")], MODULES, limit=2)
+ assert [c.term for c in picked] == ["Dead code", "Analysis"]
+
+
+def test_a_single_word_still_reaches_the_table_when_there_is_room():
+ """Ordering, not a filter. A repository whose vocabulary is single words
+ -- django's is Models, Middleware, Migrations -- must still get a table."""
+ picked = select_capabilities([_term("Analysis")], MODULES)
+ assert [c.term for c in picked] == ["Analysis"]
+
+
+def test_the_table_is_capped():
+ terms = [_term(f"Term number {n}") for n in range(20)]
+ modules = [" ".join(t.term for t in terms)]
+ assert len(select_capabilities(terms, modules)) == 6
+
+
+def test_selection_does_not_depend_on_the_order_of_the_corroboration_corpus():
+ """The selection is a function of the inputs, not of how they arrived."""
+ terms = [_term("Dead code"), _term("Blast radius"), _term("Postings")]
+ forwards = select_capabilities(terms, MODULES)
+ backwards = select_capabilities(terms, list(reversed(MODULES)))
+ assert forwards == backwards
+
+
+def test_a_term_with_no_path_anywhere_is_not_offered():
+ """Every row cites where it was read. A row that cannot is a claim this
+ wiki does not make."""
+ assert select_capabilities([_term("Dead code", source_paths=())], MODULES) == []
+
+
+def test_selection_is_logged_with_what_it_kept_and_what_it_dropped():
+ with capture_logs() as logs:
+ select_capabilities([_term("DONE"), _term("Dead code")], MODULES)
+ event = next(e for e in logs if e["event"] == "overview_capabilities_selected")
+ assert event["mined"] == 2
+ assert event["corroborated"] == 1
+ assert event["terms"] == ["Dead code"]
+
+
+def test_mining_terms_that_no_module_page_corroborates_is_a_warning():
+ """Distinct from mining nothing: the documents name things the structure
+ does not. A real answer about a repository, and also what an empty
+ corroboration corpus looks like, so the counts that separate them go out."""
+ with capture_logs() as logs:
+ select_capabilities([_term("DONE")], MODULES)
+ assert any(e["event"] == "overview_capabilities_uncorroborated" for e in logs)
+
+
+# ---------------------------------------------------------------------------
+# Rendering
+# ---------------------------------------------------------------------------
+
+
+def test_the_table_carries_the_term_its_sentence_and_its_source():
+ picked = select_capabilities(
+ [
+ _term(
+ "Dead code",
+ definition="Dead code is code no import path reaches.",
+ definition_source="src/analysis/dead_code.py",
+ )
+ ],
+ MODULES,
+ )
+ table = build_capability_table(picked)
+ assert "| Capability | What it is | Where it is written |" in table
+ assert "| Dead code | Dead code is code no import path reaches. |" in table
+ assert "`src/analysis/dead_code.py`" in table
+
+
+ "text",
+ [
+ # Both real, both from this repository's own front page.
+ "repowise init [PATH] # index a codebase (one-time; asks, or --no-prose -y needs no LLM)",
+ "`repowise distill <cmd>` compresses command output *before* the agent reads it:",
+ "$ repowise update --all",
+ "Run it with --no-prose to skip the model",
+ "cat wiki.db | sqlite3 .dump",
+ "Two parts,",
+ "See below",
+ ],
+)
+def test_prose_that_is_not_a_statement_is_not_offered_as_a_definition(text):
+ """A mined definition is whatever prose sat nearest the term, and near a
+ term in a README that is often a command line or a lead-in. An em dash is
+ a better answer: the reader learns the capability exists and is not
+ misinformed about what it does."""
+ picked = select_capabilities([_term("Dead code", definition=text)], MODULES)
+ assert picked[0].definition is None
+
+
+ "text",
+ [
+ "Dead code is code no import path reaches.",
+ "Blast radius is the set of files a change can reach through the import graph.",
+ "Middleware for utilizing Web-server-provided authentication.",
+ # Terse, and still the repository's own answer. Both of these were
+ # rejected by a first cut of the test that was tuned too strict.
+ "Blast-radius request/response models.",
+ "Decisions are co-located in the page vector store under the "
+ "``decision:<record_id>`` namespace (no separate table).",
+ ],
+)
+def test_a_real_sentence_survives(text):
+ picked = select_capabilities([_term("Dead code", definition=text)], MODULES)
+ assert picked[0].definition == text
+
+
+def test_a_rejected_definition_does_not_leave_its_source_behind():
+ """Citing where prose the table declined to quote lives would point the
+ reader at a line that is not on the page."""
+ picked = select_capabilities(
+ [
+ _term(
+ "Dead code",
+ definition="$ repowise dead-code --json",
+ definition_source="README.md#usage",
+ source_paths=("docs/guide.md",),
+ )
+ ],
+ MODULES,
+ )
+ assert picked[0].definition is None
+ assert picked[0].source_path == "docs/guide.md"
+
+
+def test_a_rejected_definition_is_logged():
+ with capture_logs() as logs:
+ select_capabilities([_term("Dead code", definition="$ repowise dead-code")], MODULES)
+ assert any(e["event"] == "overview_capability_definition_rejected" for e in logs)
+
+
+def test_a_term_the_repository_never_defined_still_gets_a_row():
+ """Naming a capability and never writing a sentence about it is common,
+ and inventing the sentence is the one thing the miner refuses to do."""
+ table = build_capability_table(select_capabilities([_term("Dead code")], MODULES))
+ assert "| Dead code | — | `README.md` |" in table
+
+
+def test_the_source_falls_back_to_the_document_that_named_the_term():
+ picked = select_capabilities(
+ [_term("Dead code", source_paths=("docs/guide.md", "src/sweep.py"))], MODULES
+ )
+ assert picked[0].source_path == "docs/guide.md"
+
+
+def test_a_pipe_in_mined_prose_does_not_break_the_table():
+ """Definitions are the repository's text, not ours. One that quotes a
+ shell pipeline or a reStructuredText grid row would otherwise shift every
+ column to its right."""
+ table = build_capability_table(
+ select_capabilities(
+ [_term("Dead code", definition="Run `repowise dead-code | less` to read it all.")],
+ MODULES,
+ )
+ )
+ row = next(line for line in table.splitlines() if line.startswith("| Dead code"))
+ assert row.count("|") - row.count("\\|") == 4
+
+
+def test_a_long_definition_is_cut_rather_than_wrapping_the_row():
+ table = build_capability_table(
+ select_capabilities([_term("Dead code", definition="word " * 100)], MODULES)
+ )
+ row = next(line for line in table.splitlines() if line.startswith("| Dead code"))
+ assert "…" in row
+ assert len(row) < 260
+
+
+def test_no_capabilities_means_no_table_and_no_heading():
+ """A header over an empty table says less than no section at all."""
+ assert build_capability_table([]) is None
+ assert embed_capability_table("# Overview\n", None) == "# Overview\n"
+
+
+def test_the_empty_case_is_logged():
+ with capture_logs() as logs:
+ build_capability_table([])
+ assert any(e["event"] == "overview_capability_table_empty" for e in logs)
+
+
+def test_embedding_is_idempotent():
+ """A reused or cached page picks up the current selection rather than
+ accumulating a second one -- including over a section the model wrote."""
+ table = build_capability_table(select_capabilities([_term("Dead code")], MODULES))
+ once = embed_capability_table("# Overview\n\nSome prose.\n", table)
+ twice = embed_capability_table(once, table)
+ assert once == twice
+ assert twice.count(CAPABILITY_TABLE_HEADING) == 1
+
+
+def test_embedding_replaces_a_section_the_model_wrote_itself():
+ model_page = "# Overview\n\n## What it does\n\nIt does several things.\n\n## Packages\n\nrows\n"
+ table = build_capability_table(select_capabilities([_term("Dead code")], MODULES))
+ out = embed_capability_table(model_page, table)
+ assert "It does several things." not in out
+ assert out.count(CAPABILITY_TABLE_HEADING) == 1
+ # and the section after it survives
+ assert "## Packages" in out
+
+
+# ---------------------------------------------------------------------------
+# Through the generator, on every path
+# ---------------------------------------------------------------------------
+
+
+def _pkg(name: str, language: str = "python") -> PackageInfo:
+ return PackageInfo(
+ name=name,
+ path=f"packages/{name}",
+ language=language,
+ entry_points=[],
+ manifest_file="pyproject.toml",
+ )
+
+
+def _parsed(path: str, language: str = "python"):
+ from repowise.core.ingestion.models import ParsedFile
+
+ return ParsedFile(
+ file_info=_make_file_info(path, language=language), symbols=[], imports=[], exports=[]
+ )
+
+
+def structure():
+ return RepoStructure(
+ is_monorepo=True,
+ packages=[_pkg("core")],
+ root_language_distribution={"python": 1.0},
+ total_files=2,
+ total_loc=200,
+ entry_points=[],
+ )
+
+
+def parsed_files():
+ return [_parsed("packages/core/a.py"), _parsed("packages/core/b.py")]
+
+
+def capabilities():
+ return select_capabilities(
+ [
+ _term(
+ "Dead code",
+ definition="Dead code is code no import path reaches.",
+ definition_source="src/analysis/dead_code.py",
+ )
+ ],
+ MODULES,
+ )
+
+
+async def test_the_deterministic_page_carries_the_table(structure, parsed_files, capabilities):
+ """`repo_overview.j2` is a prompt, not a page. Asserting a table on it
+ asserts nothing about what ships, so this goes through the generator."""
+ from repowise.core.generation.models import GenerationConfig
+ from repowise.core.generation.page_generator import PageGenerator
+ from repowise.core.providers.llm.mock import MockProvider
+
+ config = GenerationConfig(deterministic=True)
+ gen = PageGenerator(MockProvider(), ContextAssembler(config), config)
+ page = await gen.generate_repo_overview(
+ structure,
+ {},
+ [],
+ {},
+ repo_name="testrepo",
+ parsed_files=parsed_files,
+ capabilities=capabilities,
+ )
+
+ assert "| Capability | What it is | Where it is written |" in page.content
+ assert "Dead code is code no import path reaches." in page.content
+ assert page.content.count(CAPABILITY_TABLE_HEADING) == 1
+
+
+async def test_the_model_written_page_carries_the_same_bytes(structure, parsed_files, capabilities):
+ from repowise.core.generation.models import GenerationConfig
+ from repowise.core.generation.page_generator import PageGenerator
+ from repowise.core.providers.llm.mock import MockProvider
+
+ deterministic = GenerationConfig(deterministic=True)
+ prose = GenerationConfig()
+ args = dict(repo_name="testrepo", parsed_files=parsed_files, capabilities=capabilities)
+
+ stub_page = await PageGenerator(
+ MockProvider(), ContextAssembler(deterministic), deterministic
+ ).generate_repo_overview(structure, {}, [], {}, **args)
+ model_page = await PageGenerator(
+ MockProvider(), ContextAssembler(prose), prose
+ ).generate_repo_overview(structure, {}, [], {}, **args)
+
+ table = build_capability_table(capabilities)
+ assert table in stub_page.content
+ assert table in model_page.content
+
+
+async def test_a_provider_outage_costs_the_prose_not_the_table(
+ structure, parsed_files, capabilities
+):
+ """The same reasoning as the architecture map: a fact the run already holds
+ should survive the provider that was not needed to produce it."""
+ from repowise.core.generation.models import GenerationConfig
+ from repowise.core.generation.page_generator import PageGenerator
+ from repowise.core.providers.llm.mock import MockProvider
+
+ class Failing(MockProvider):
+ async def generate(self, *a, **kw):
+ raise RuntimeError("upstream 529 overloaded")
+
+ config = GenerationConfig()
+ gen = PageGenerator(Failing(), ContextAssembler(config), config)
+ page = await gen.generate_repo_overview(
+ structure,
+ {},
+ [],
+ {},
+ repo_name="testrepo",
+ parsed_files=parsed_files,
+ capabilities=capabilities,
+ )
+
+ from repowise.core.generation.models import STUB_FALLBACK_ERROR
+
+ # The fallback path really was taken, rather than the assertion below
+ # passing because the provider was never reached.
+ assert "529 overloaded" in page.metadata[STUB_FALLBACK_ERROR]
+ assert "| Capability | What it is | Where it is written |" in page.content
+
+
+async def test_the_page_is_byte_identical_across_two_runs(structure, parsed_files, capabilities):
+ """The point of building this outside the model."""
+ from repowise.core.generation.models import GenerationConfig
+ from repowise.core.generation.page_generator import PageGenerator
+ from repowise.core.providers.llm.mock import MockProvider
+
+ config = GenerationConfig(deterministic=True)
+ gen = PageGenerator(MockProvider(), ContextAssembler(config), config)
+ args = dict(repo_name="testrepo", parsed_files=parsed_files, capabilities=capabilities)
+ first = await gen.generate_repo_overview(structure, {}, [], {}, **args)
+ second = await gen.generate_repo_overview(structure, {}, [], {}, **args)
+ assert first.content == second.content
+
+
+async def test_the_table_only_adds_path_citations(structure, parsed_files, capabilities):
+ """A page that reads better while citing less is a worse answer source.
+ The third column is a real path, so this can only go up."""
+ import re
+
+ from repowise.core.generation.models import GenerationConfig
+ from repowise.core.generation.page_generator import PageGenerator
+ from repowise.core.providers.llm.mock import MockProvider
+
+ def cites(text: str) -> int:
+ return len(re.findall(r"`[^`\n]*/[^`\n]*`", text))
+
+ config = GenerationConfig(deterministic=True)
+ gen = PageGenerator(MockProvider(), ContextAssembler(config), config)
+ args = dict(repo_name="testrepo", parsed_files=parsed_files)
+ without = await gen.generate_repo_overview(structure, {}, [], {}, **args)
+ with_table = await gen.generate_repo_overview(
+ structure, {}, [], {}, capabilities=capabilities, **args
+ )
+
+ assert cites(with_table.content) > cites(without.content)
+
+
+async def test_no_capabilities_leaves_the_page_as_it_was(structure, parsed_files):
+ """A repository whose documents name nothing its code also spells is a
+ supported and common outcome."""
+ from repowise.core.generation.models import GenerationConfig
+ from repowise.core.generation.page_generator import PageGenerator
+ from repowise.core.providers.llm.mock import MockProvider
+
+ config = GenerationConfig(deterministic=True)
+ gen = PageGenerator(MockProvider(), ContextAssembler(config), config)
+ page = await gen.generate_repo_overview(
+ structure, {}, [], {}, repo_name="testrepo", parsed_files=parsed_files
+ )
+ assert CAPABILITY_TABLE_HEADING not in page.content
diff --git a/tests/unit/generation/test_overview_capability_wiring.py b/tests/unit/generation/test_overview_capability_wiring.py
new file mode 100644
index 000000000..e04baf99f
--- /dev/null
+++ b/tests/unit/generation/test_overview_capability_wiring.py
@@ -0,0 +1,319 @@
+"""The capability table reaches the overview, and is mined once per run.
+
+The helpers can be right while the page has no table -- that already happened
+once with the package table -- so this goes through ``build_level6_coros`` and
+asserts what the generator was actually handed.
+
+The two things worth pinning are the corroboration corpus and the cost. Each
+module group contributes its title and its summary -- from this run when
+level 4 wrote the page, from the store when it did not, so a scoped run
+corroborates against as much as a full one and the front-page section does not
+vanish from a `repowise update`. And the miner walks the whole repository, so
+levels 6 and 8 must share one pass rather than paying for two.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from pathlib import Path
+from types import SimpleNamespace
+from typing import Any
+
+from structlog.testing import capture_logs
+
+from repowise.core.generation.page_generator.levels import (
+ build_level6_coros,
+ build_level8_coros,
+)
+from repowise.core.generation.report import reset_house_terms
+from repowise.core.ingestion.models import FileInfo, ParsedFile, RepoStructure, Symbol
+
+_README = """\
+# Ledger
+
+## Blast radius
+
+Blast radius is the set of files a change can reach through the import graph.
+
+## Change risk
+
+Change risk scores a diff against the history of the files it touches.
+"""
+
+_MODULE = '''\
+"""Compute the blast radius of a change, and its change risk.
+
+Blast radius is measured over the resolved import graph.
+"""
+
+
+class BlastRadius:
+ """One change's blast radius."""
+'''
+
+#: What the structural side independently arrived at. "Blast radius" is named
+#: by both; "Change risk" is in the documents only.
+MODULE_GROUPS = [SimpleNamespace(display="Blast Radius Evaluation", label="", key="src")]
+
+
+class _Store:
+ """A vector store holding one module summary from a previous run."""
+
+ def __init__(self, summaries: dict[str, str] | None = None, fail: bool = False) -> None:
+ self.summaries = summaries or {}
+ self.fail = fail
+ self.asked: list[str] = []
+
+ async def get_page_summaries_by_paths(self, paths: list[str]) -> dict[str, dict]:
+ self.asked.extend(paths)
+ if self.fail:
+ raise RuntimeError("store unavailable")
+ return {p: {"summary": s} for p, s in self.summaries.items() if p in paths}
+
+
+def _repo(tmp_path: Path) -> Path:
+ root = tmp_path / "ledger"
+ (root / "src").mkdir(parents=True)
+ (root / "src" / "blast_radius.py").write_text(_MODULE, encoding="utf-8")
+ (root / "README.md").write_text(_README, encoding="utf-8")
+ return root
+
+
+def _parsed_file(path: str) -> ParsedFile:
+ info = FileInfo(
+ path=path,
+ abs_path=f"/repo/{path}",
+ language="python",
+ size_bytes=256,
+ git_hash="abc",
+ last_modified=datetime(2026, 1, 1, tzinfo=UTC),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+ return ParsedFile(
+ file_info=info,
+ symbols=[
+ Symbol(
+ id=f"{path}::BlastRadius",
+ name="BlastRadius",
+ qualified_name=f"{path}::BlastRadius",
+ kind="class",
+ signature="class BlastRadius:",
+ start_line=1,
+ end_line=8,
+ docstring="One change's blast radius.",
+ decorators=[],
+ visibility="public",
+ is_async=False,
+ complexity_estimate=1,
+ language="python",
+ parent_name=None,
+ )
+ ],
+ imports=[],
+ exports=["BlastRadius"],
+ docstring=None,
+ parse_errors=[],
+ content_hash="abc",
+ )
+
+
+class _Gen:
+ """Keeps what the level builder handed it, and returns no coroutine."""
+
+ def __init__(self) -> None:
+ self.overview_kwargs: dict[str, Any] = {}
+ self.onboarding_signals: list[Any] = []
+
+ def generate_repo_overview(self, *args: Any, **kwargs: Any) -> object:
+ self.overview_kwargs = kwargs
+ return object()
+
+ def generate_onboarding_page(self, spec: Any, signals: Any) -> object:
+ self.onboarding_signals.append(signals)
+ return object()
+
+
+def _run(
+ tmp_path: Path,
+ *,
+ module_groups: list[Any] | None = None,
+ written: dict[str, str] | None = None,
+ store: Any = None,
+) -> SimpleNamespace:
+ reset_house_terms()
+ return SimpleNamespace(
+ gen=_Gen(),
+ config=SimpleNamespace(enable_onboarding=True, source_evidence_files={}),
+ repo_path=_repo(tmp_path),
+ repo_name="ledger",
+ repo_structure=RepoStructure(
+ is_monorepo=False,
+ packages=[],
+ root_language_distribution={"python": 1.0},
+ total_files=1,
+ total_loc=10,
+ entry_points=[],
+ ),
+ parsed_files=[_parsed_file("src/blast_radius.py")],
+ source_map={},
+ graph_builder=SimpleNamespace(
+ community_info=lambda: {},
+ execution_flows=lambda: SimpleNamespace(flows=[]),
+ ),
+ pagerank={},
+ betweenness={},
+ community={},
+ sccs=(),
+ git_meta_map=None,
+ dead_code_by_file={},
+ decisions_all=(),
+ external_systems=(),
+ completed_page_summaries=dict(written or {}),
+ sel_module_groups=MODULE_GROUPS if module_groups is None else module_groups,
+ vector_store=store,
+ tour_stops=(),
+ layer_order=(),
+ kg_ctx=None,
+ on_subphase=None,
+ _emit=lambda page_id: True,
+ )
+
+
+async def test_the_overview_is_handed_the_corroborated_terms(tmp_path):
+ run = _run(tmp_path)
+ assert await build_level6_coros(run), "level 6 produced no overview"
+
+ picked = [c.term for c in run.gen.overview_kwargs["capabilities"]]
+ assert picked == ["Blast radius"]
+
+
+async def test_a_term_no_module_page_names_does_not_reach_the_overview(tmp_path):
+ """ "Change risk" is in the README and in a docstring, so it is a mined
+ term. No module page mentions it, so the front page does not claim it."""
+ run = _run(tmp_path)
+ await build_level6_coros(run)
+
+ picked = [c.term for c in run.gen.overview_kwargs["capabilities"]]
+ assert "Change risk" not in picked
+
+
+async def test_a_community_label_does_not_corroborate(tmp_path):
+ """The corpus is a group's title and summary. Its label is not in it.
+
+ A community label is a broad phrase covering a whole layer, so it
+ corroborates almost any common word that appears in it. Including labels
+ put "Architecture" and "Workspace" on the front page of a real render. A
+ title and a summary describe one part of the system, which is the claim
+ the corroboration is supposed to be making.
+ """
+ run = _run(
+ tmp_path,
+ module_groups=[
+ SimpleNamespace(
+ display="Ledger Postings",
+ label="Change Risk and Ingestion Engine",
+ key="src/change_risk",
+ )
+ ],
+ )
+ await build_level6_coros(run)
+
+ assert [c.term for c in run.gen.overview_kwargs["capabilities"]] == []
+
+
+async def test_a_summary_written_this_run_corroborates(tmp_path):
+ """Titles are ~90 short strings and too thin a net on their own. The
+ summaries are what make the corroboration mean something."""
+ run = _run(
+ tmp_path, written={"src": "Scores a diff by the change risk of the files it touches."}
+ )
+ await build_level6_coros(run)
+
+ assert "Change risk" in [c.term for c in run.gen.overview_kwargs["capabilities"]]
+
+
+async def test_a_summary_from_the_store_corroborates_when_this_run_wrote_none(tmp_path):
+ """The case that made the first version wrong.
+
+ A scoped run -- every `repowise update` -- writes no module pages, so the
+ corpus was empty and the front-page section disappeared. The summaries
+ are still in the store from the last full run.
+ """
+ store = _Store({"src": "Scores a diff by the change risk of the files it touches."})
+ run = _run(tmp_path, store=store)
+ await build_level6_coros(run)
+
+ assert store.asked == ["src"]
+ assert "Change risk" in [c.term for c in run.gen.overview_kwargs["capabilities"]]
+
+
+async def test_this_run_wins_over_the_store(tmp_path):
+ """A page written a moment ago is fresher than the one in the store, and
+ asking for it again would be a round-trip for a worse answer."""
+ store = _Store({"src": "stale text naming nothing"})
+ run = _run(
+ tmp_path,
+ written={"src": "Scores a diff by the change risk of the files it touches."},
+ store=store,
+ )
+ await build_level6_coros(run)
+
+ assert store.asked == []
+ assert "Change risk" in [c.term for c in run.gen.overview_kwargs["capabilities"]]
+
+
+async def test_a_store_that_cannot_answer_costs_reach_not_the_page(tmp_path):
+ """Corroboration is best-effort. A store failure must not lose the
+ overview, and must not pass silently either."""
+ run = _run(tmp_path, store=_Store(fail=True))
+ with capture_logs() as logs:
+ assert await build_level6_coros(run), "the overview was lost to a store error"
+
+ assert any(e["event"] == "generation.overview_corroboration_store_read_failed" for e in logs)
+ # The titles still corroborate on their own.
+ assert [c.term for c in run.gen.overview_kwargs["capabilities"]] == ["Blast radius"]
+
+
+async def test_no_module_groups_means_no_table_and_a_log(tmp_path):
+ """A repository the grouper produced nothing for has nothing to
+ corroborate against. The section going missing is correct, not silent."""
+ run = _run(tmp_path, module_groups=[])
+ with capture_logs() as logs:
+ await build_level6_coros(run)
+
+ assert run.gen.overview_kwargs["capabilities"] == []
+ assert any(e["event"] == "generation.overview_capability_table_absent" for e in logs)
+
+
+async def test_the_repository_is_mined_once_for_both_levels(tmp_path):
+ """Mining walks the whole repository. Two consumers, one walk."""
+ run = _run(tmp_path)
+ await build_level6_coros(run)
+ build_level8_coros(run)
+
+ from_overview = tuple(c.term for c in run.gen.overview_kwargs["capabilities"])
+ onboarding_terms = run.gen.onboarding_signals[0].house_terms
+ assert from_overview
+ assert onboarding_terms
+ # Same objects, so the same pass produced both.
+ assert run._house_terms is onboarding_terms
+ assert all(
+ t.term in {h.term for h in onboarding_terms}
+ for t in run.gen.overview_kwargs["capabilities"]
+ )
+
+
+async def test_onboarding_still_gets_its_terms_when_the_overview_mined_first(tmp_path):
+ """Order independence: level 6 now runs the miner, and level 8 read it
+ from a warm cache rather than from a fresh walk."""
+ run = _run(tmp_path)
+ await build_level6_coros(run)
+ build_level8_coros(run)
+
+ assert [t.term for t in run.gen.onboarding_signals[0].house_terms] == [
+ "Blast radius",
+ "Change risk",
+ ]