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): readable file pages and an honest overview capability table (#2741)

Raghav Chamadiyaefd47599c896
diff --git a/packages/core/src/repowise/core/generation/overview_tables.py b/packages/core/src/repowise/core/generation/overview_tables.py
index 51ba9b4bb..8f4dc0abd 100644
--- a/packages/core/src/repowise/core/generation/overview_tables.py
+++ b/packages/core/src/repowise/core/generation/overview_tables.py
@@ -159,10 +159,12 @@ def embed_capability_table(content: str, table: str | None) -> str:
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.
+ selection instead of accumulating a second one. With no table the section
+ is removed: a page reused verbatim from an earlier run still carries the
+ rows that run selected, and the current selection has none.
"""
if not table:
- return content
+ return _CAPABILITY_SECTION_RE.sub("", content, count=1)
section = f"{CAPABILITY_TABLE_HEADING}\n\n{table}\n\n"
if _CAPABILITY_SECTION_RE.search(content):
diff --git a/packages/core/src/repowise/core/generation/page_generator/file_facts.py b/packages/core/src/repowise/core/generation/page_generator/file_facts.py
new file mode 100644
index 000000000..55885d367
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/page_generator/file_facts.py
@@ -0,0 +1,169 @@
+"""The facts a file page opens with, reduced to what a sentence can carry.
+
+A file page is rendered without a model, so its first paragraph is the one
+place a reader, the wiki list and ``get_context`` meet the file in prose. That
+paragraph leads with the author's own words when the file has a docstring and
+otherwise says what the file defines and who imports it. The sentences live in
+``file_page.j2`` so they stay in the label catalog; this module only counts,
+picks and orders, which the template language does badly.
+
+Every value is derived from the parse, the import graph or the knowledge graph,
+and every ordering is fixed (by name, or by kind then declaration order), so the
+same index renders the same bytes.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import Counter
+from collections.abc import Iterable, Mapping
+from typing import Any
+
+from repowise.core.test_paths import is_test_related_path
+
+from .structural import api_symbols, as_markdown, code_span, oneline, signature
+
+# Names quoted in a sentence before it switches to "and N more"; one more
+# than this is named in full, since "and 1 more" is longer than the name.
+_NAMED_IN_SENTENCE = 3
+# A dependency list this short is named in full, not counted.
+_LIST_IN_FULL = 3
+# One line of a symbol's docstring beside its signature.
+_SYMBOL_DOC_LIMIT = 140
+_SENTENCE_END_RE = re.compile(r"(?<=[.!?])\s")
+# The opening names types first, then callables, then values: a module's
+# classes say what it is about, its type variables and constants rarely do.
+_KIND_ORDER = {
+ "class": 0,
+ "interface": 0,
+ "struct": 0,
+ "trait": 0,
+ "enum": 0,
+ "type_alias": 0,
+ "function": 1,
+}
+# Not definitions in their own right: a Rust ``impl`` block restates its
+# type's name, and a Rust field belongs to a struct.
+_NOT_DEFINITIONS = frozenset({"impl", "property"})
+
+
+def first_sentence(text: object, limit: int = _SYMBOL_DOC_LIMIT) -> str:
+ """The first sentence of a docstring's prose, flattened to one line."""
+ prose = "\n".join(ln for ln in as_markdown(text).splitlines() if not ln.startswith("#"))
+ paragraph = prose.strip().split("\n\n", 1)[0]
+ flat = " ".join(paragraph.split())
+ sentence = _SENTENCE_END_RE.split(flat, 1)[0]
+ line = oneline(sentence, limit)
+ # A cut through a code span would leave it open and swallow the rest of
+ # the line into code.
+ if line.count("`") % 2:
+ cut = line.endswith("…")
+ line = line.rstrip("…") + "`" + ("…" if cut else "")
+ return line
+
+
+def _largest_group(paths: Iterable[str]) -> tuple[str, int]:
+ """The directory holding most of *paths* and how many, or ("", 0).
+
+ Only a clear winner is named: at least two files and more than any other
+ directory. A tie or a spread of singletons names nothing, not an arbitrary
+ directory.
+ """
+ counts = Counter(p.rsplit("/", 1)[0] if "/" in p else "." for p in paths)
+ ranked = sorted(counts.items(), key=lambda item: (-item[1], item[0]))
+ if not ranked or ranked[0][1] < 2:
+ return "", 0
+ if len(ranked) > 1 and ranked[1][1] == ranked[0][1]:
+ return "", 0
+ return ranked[0]
+
+
+def _neighbours(paths: list[str]) -> dict[str, Any]:
+ """Count, short list and largest directory of an import neighbourhood."""
+ tests = {p for p in paths if is_test_related_path(p)}
+ code = [p for p in paths if p not in tests]
+ # Where the code that uses it lives says more than where its tests do.
+ directory, share = _largest_group(code)
+ return {
+ "count": len(paths),
+ "tests": len(tests),
+ "listed": [code_span(p) for p in sorted(paths)] if len(paths) <= _LIST_IN_FULL else [],
+ "directory": code_span(directory) if directory else "",
+ "share": share,
+ "all_in_one": bool(directory) and share == len(paths),
+ }
+
+
+def file_facts(ctx: Any) -> dict[str, Any]:
+ """The values ``file_page.j2`` builds its opening sentences from."""
+ api = api_symbols(ctx.symbols)
+ # Only the file's own top-level definitions: a method of a class the API
+ # does not list is not what the file defines.
+ top_level = sorted(
+ (s for s in api if not s.get("parent_name") and s.get("kind") not in _NOT_DEFINITIONS),
+ key=lambda s: _KIND_ORDER.get(s.get("kind", ""), 2),
+ )
+ named = len(top_level) if len(top_level) <= _NAMED_IN_SENTENCE + 1 else _NAMED_IN_SENTENCE
+ purpose = ""
+ if ctx.docstring:
+ purpose = as_markdown(ctx.docstring)
+ elif ctx.kg_node_summary and (ctx.is_test or "barrel" in ctx.kg_tags):
+ # The graph names what a test file tests and that a barrel re-exports;
+ # for other code its one-line role only restates the symbols, which
+ # the sentences below do better.
+ purpose = oneline(ctx.kg_node_summary)
+ return {
+ "name": code_span(ctx.file_path.rsplit("/", 1)[-1]),
+ "purpose": purpose,
+ "defines": [code_span(s["name"]) for s in top_level[:named]],
+ "defines_more": len(top_level) - len(top_level[:named]),
+ "importers": _neighbours(list(ctx.dependents)),
+ "imports": _neighbours(list(ctx.dependencies)),
+ }
+
+
+def _entry(declared: str, doc: str = "") -> dict[str, Any]:
+ return {"declared": code_span(declared), "doc": doc, "members": []}
+
+
+def symbol_entries(symbols: Iterable[Mapping[str, Any]]) -> list[dict[str, Any]]:
+ """The API list: one entry per symbol, members nested under their type.
+
+ A method whose class the API does not list is nested under that class's
+ bare name, so it neither reads as a module function nor leaves the page.
+ An ``impl`` block folds into the type it implements and is listed once.
+ """
+ entries: list[dict[str, Any]] = []
+ by_name: dict[str, dict[str, Any]] = {}
+ for sym in api_symbols(symbols):
+ name = sym["name"]
+ declared = signature(sym.get("signature") or "") or name
+ if name not in declared:
+ declared = f"{name}: {declared}"
+ doc = first_sentence(sym.get("docstring")) if sym.get("docstring") else ""
+ parent_name = sym.get("parent_name") or ""
+ if parent_name:
+ parent = by_name.get(parent_name)
+ if parent is None:
+ parent = by_name[parent_name] = _entry(parent_name)
+ entries.append(parent)
+ parent["members"].append(_entry(declared, doc))
+ continue
+ if sym.get("kind") == "impl" and name in by_name:
+ continue
+ if name in by_name and not by_name[name]["doc"] and by_name[name]["declared"] == code_span(name):
+ # A stand-in made for members seen before their type: fill it in.
+ by_name[name].update(declared=code_span(declared), doc=doc)
+ continue
+ by_name[name] = _entry(declared, doc)
+ entries.append(by_name[name])
+ return entries
+
+
+def with_subject(sentences: Iterable[str], first: str, rest: str) -> list[str]:
+ """Fill each sentence's ``{subject}`` slot: *first* once, *rest* after.
+
+ ``str.replace``, not ``format``: the sentences already carry file paths
+ and signatures, whose braces ``format`` would read as fields.
+ """
+ return [s.replace("{subject}", first if i == 0 else rest) for i, s in enumerate(sentences)]
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 24ed6c956..e9e0f665f 100644
--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py
+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py
@@ -499,13 +499,12 @@ class PerTypeGenerationMixin:
# the model, and both embeds are idempotent so a reused page picks them
# up too. Appended in reading order, so what the repository does lands
# above what it is made of, and both above the diagram.
- if capabilities:
- response = replace(
- response,
- content=embed_capability_table(
- response.content, build_capability_table(capabilities)
- ),
- )
+ # Unconditional: content reused from an earlier run keeps that run's
+ # rows, and an empty selection has to remove them.
+ response = replace(
+ response,
+ content=embed_capability_table(response.content, build_capability_table(capabilities)),
+ )
if ctx.package_stats:
response = replace(
response,
diff --git a/packages/core/src/repowise/core/generation/page_generator/structural.py b/packages/core/src/repowise/core/generation/page_generator/structural.py
index 24570fa1f..0801ca865 100644
--- a/packages/core/src/repowise/core/generation/page_generator/structural.py
+++ b/packages/core/src/repowise/core/generation/page_generator/structural.py
@@ -45,7 +45,7 @@ log = structlog.get_logger(__name__)
# output without changing any template's bytes: new context fields, a changed
# helper, a reordered section. Template edits are picked up automatically
# (their source is hashed), so this is only for the cases hashing cannot see.
-STRUCTURAL_GENERATION_VERSION = "3"
+STRUCTURAL_GENERATION_VERSION = "4"
# Keyless stub templates live one directory down so their filenames can match
# the prompt templates they stand in for.
@@ -88,6 +88,13 @@ _REST_ROLE_RE = re.compile(
_REST_DIRECTIVE_RE = re.compile(
r"^([ \t]*)\.\.[ \t]+[a-z-]+::.*(?:\n(?:\1[ \t]+.*|[ \t]*(?=\n|$)))*", re.MULTILINE
)
+# A reStructuredText section title: a line underlined by at least as many
+# punctuation characters. Left alone, markdown shows the underline as text and
+# the title becomes the page summary.
+_REST_TITLE_RE = re.compile(
+ r"^(?:([=\-~^\"'*+#])\1{2,}[ \t]*\n)?([^\n]*\S)[ \t]*\n([=\-~^\"'*+#])\3{2,}[ \t]*$",
+ 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)
@@ -120,11 +127,24 @@ def as_markdown(value: object) -> str:
text = _REST_ROLE_RE.sub(r"`\1`", text)
text = _DOUBLE_TICK_RE.sub(r"`\1`", text)
text = dedent_body(text).strip()
+ text = _REST_TITLE_RE.sub(_rest_title, text)
for i, fence in enumerate(fences):
text = text.replace(f"\x00FENCE{i}\x00", fence)
return text
+def _rest_title(match: re.Match[str]) -> str:
+ """A reST title as a level-3 heading, when the underline is long enough.
+
+ An overline, when present, has to use the underline's character.
+ """
+ overline, title, mark = match.group(1), match.group(2).strip(), match.group(3)
+ underline = match.group(0).splitlines()[-1].strip()
+ if len(underline) < len(title) or (overline and overline != mark):
+ return match.group(0)
+ return f"### {title}"
+
+
def dedent_body(text: str) -> str:
"""Strip the common indent from every line after the first.
@@ -502,6 +522,9 @@ def register_filters(env: Any) -> None:
that reaches for a filter the caller forgot raises at render time, and the
callers are the generator and four test fixtures.
"""
+ # Local: file_facts builds on the filters defined in this module.
+ from .file_facts import file_facts, symbol_entries, with_subject
+
for name, fn in (
("oneline", oneline),
("as_markdown", as_markdown),
@@ -515,6 +538,10 @@ def register_filters(env: Any) -> None:
("code_span", code_span),
("group_paths", group_paths),
("datestamp", datestamp),
+ # The file page's opening sentences and its API list.
+ ("file_facts", file_facts),
+ ("symbol_entries", symbol_entries),
+ ("with_subject", with_subject),
):
env.filters.setdefault(name, fn)
diff --git a/packages/core/src/repowise/core/generation/structural_labels.py b/packages/core/src/repowise/core/generation/structural_labels.py
index 5c2005689..8095fffde 100644
--- a/packages/core/src/repowise/core/generation/structural_labels.py
+++ b/packages/core/src/repowise/core/generation/structural_labels.py
@@ -40,42 +40,32 @@ ENGLISH_LABELS: dict[str, str] = {
"file_plural": "files",
"symbol": "Symbol",
"kind": "Kind",
- "signature": "Signature",
"questions_heading": "Questions this page answers",
# -- file page ---------------------------------------------------------
- # The overview sentence is assembled from fragments rather than stored
- # whole: four independent optional clauses would need sixteen variants as
- # one string. A translation that needs a different order pays for it here.
- "is_a": "is a",
- "entry_point": "entry-point",
- "test": "test",
- "source_file": "source file",
- "in_layer": "in the {layer} layer",
- "part_of_module_cluster_intro": "part of the {community} module cluster",
- "exposes_symbols": "It exposes {symbol_count} {symbol_word}.",
- "exposes_symbols_and_depends": (
- "It exposes {symbol_count} {symbol_word} and depends on {file_count} {file_word}."
- ),
- "public_symbol_singular": "public symbol",
- "public_symbol_plural": "public symbols",
- "other_file_singular": "other file",
- "other_file_plural": "other files",
+ # The opening sentences carry a ``{subject}`` slot the template fills with
+ # the file's name for the page's first sentence and ``it_subject`` after.
+ "and_word": "and",
+ "and_count_more": "{count} more",
+ "it_subject": "It",
+ "file_defines": "{subject} defines {names}.",
+ "file_imported_by": "{subject} is imported by {names}.",
+ "file_imported_by_count": "{subject} is imported by {count} files{tests}.",
+ "of_them_tests": " ({count} of them tests)",
+ "largest_share": "{count} of them are in {directory}.",
+ "largest_share_code": "Of the others, {count} are in {directory}.",
+ "all_in_directory": "All of them are in {directory}.",
+ "file_imports": "{subject} imports {names}.",
+ "file_imports_count": "{subject} imports {count} files from this repository.",
+ "file_layer": "{subject} belongs to the {layer} layer.",
+ "file_layer_boundary": "{subject} belongs to the {layer} layer, and other layers import it.",
+ "file_layer_entry": "{subject} belongs to the {layer} layer and is an entry point into it.",
+ "file_entry_point": "{subject} is an entry point.",
+ "file_fallback": "{subject} is {article} {language} file.",
"public_api": "Public API",
"depends_on": "Depends on",
"used_by": "Used by",
- "imported_by_files": "Imported by {count} {file_word} in this repository.",
- "usage_notes": "Usage Notes",
- "part_of_module_cluster": "Part of the **{community}** module cluster.",
- "layer": "Layer",
- "role": "Role",
- # The knowledge graph's three roles, spelled for a reader. The stored
- # values are enum members and one of them, ``edge_connector``, says
- # nothing at all outside the code that computes it.
- "role_entry_point": "entry point into its layer",
- "role_internal": "internal to its layer",
- "role_boundary": "boundary — imported from other layers",
- # Symbols the API table leaves out, named so the identifier stays on the
- # page even though the row does not.
+ # Symbols the API list leaves out, named so the identifier stays on the
+ # page even though the entry does not.
"also_defined": "Also defined: {names}.",
# -- file page: history ------------------------------------------------
"history": "History",
@@ -195,34 +185,31 @@ LOCALIZED_LABELS: dict[str, dict[str, str]] = {
"file_plural": "Dateien",
"symbol": "Symbol",
"kind": "Art",
- "signature": "Signatur",
"questions_heading": "Fragen, die diese Seite beantwortet",
- "is_a": "ist eine",
- "entry_point": "Einstiegspunkt",
- "test": "Test",
- "source_file": "Quelldatei",
- "in_layer": "in der Schicht {layer}",
- "part_of_module_cluster_intro": "Teil des Modulclusters {community}",
- "exposes_symbols": "Sie stellt {symbol_count} {symbol_word} bereit.",
- "exposes_symbols_and_depends": (
- "Sie stellt {symbol_count} {symbol_word} bereit und hängt von {file_count} "
- "{file_word} ab."
+ "and_word": "und",
+ "and_count_more": "{count} weitere",
+ "it_subject": "Die Datei",
+ "file_defines": "{subject} definiert {names}.",
+ "file_imported_by": "{subject} wird von {names} importiert.",
+ "file_imported_by_count": "{subject} wird von {count} Dateien{tests} importiert.",
+ "of_them_tests": " (davon {count} Tests)",
+ "largest_share": "{count} davon liegen in {directory}.",
+ "largest_share_code": "Von den übrigen liegen {count} in {directory}.",
+ "all_in_directory": "Alle liegen in {directory}.",
+ "file_imports": "{subject} importiert {names}.",
+ "file_imports_count": "{subject} importiert {count} Dateien aus diesem Repository.",
+ "file_layer": "{subject} gehört zur Schicht {layer}.",
+ "file_layer_boundary": (
+ "{subject} gehört zur Schicht {layer} und wird aus anderen Schichten importiert."
+ ),
+ "file_layer_entry": (
+ "{subject} gehört zur Schicht {layer} und ist ein Einstiegspunkt in sie."
),
- "public_symbol_singular": "öffentliches Symbol",
- "public_symbol_plural": "öffentliche Symbole",
- "other_file_singular": "weiteren Datei",
- "other_file_plural": "weiteren Dateien",
+ "file_entry_point": "{subject} ist ein Einstiegspunkt.",
+ "file_fallback": "{subject} ist eine {language}-Datei.",
"public_api": "Öffentliche API",
"depends_on": "Abhängigkeiten",
"used_by": "Wird verwendet von",
- "imported_by_files": "Importiert von {count} {file_word} in diesem Repository.",
- "usage_notes": "Nutzungshinweise",
- "part_of_module_cluster": "Teil des Modulclusters **{community}**.",
- "layer": "Schicht",
- "role": "Rolle",
- "role_entry_point": "Einstiegspunkt in ihre Schicht",
- "role_internal": "innerhalb ihrer Schicht",
- "role_boundary": "Randstelle — wird aus anderen Schichten importiert",
"also_defined": "Ebenfalls definiert: {names}.",
"history": "Historie",
"history_commits": (
diff --git a/packages/core/src/repowise/core/generation/templates/file_page.j2 b/packages/core/src/repowise/core/generation/templates/file_page.j2
index 0b4afb924..848a2de9c 100644
--- a/packages/core/src/repowise/core/generation/templates/file_page.j2
+++ b/packages/core/src/repowise/core/generation/templates/file_page.j2
@@ -1,45 +1,134 @@
-{#- Deterministic (no-LLM) tier-2 file page.
+{#- Deterministic (no-LLM) 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
- structured, factual stub built entirely from parsed AST + graph signals,
- and is embedded for search like any other page.
+ Rendered straight from the assembled FilePageContext: no model call, every
+ statement comes from the parse, the import graph, git history or the
+ knowledge graph. It is read on the file view and embedded for search, so it
+ serves both a reader and the index.
- 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. Where readability and
- retrieval disagree, retrieval wins and the reader personas in
- ``docs/reader-persona.ts`` decide what a reader is shown — a section is
- hidden client-side rather than dropped here, since dropping it would take
- it out of the index with it.
+ For the reader it opens with prose (the docstring, or sentences built from
+ what the file defines and who imports it) and follows with a compact
+ reference. For the index every identifier the context carried stays in the
+ text: symbols, neighbour paths and the layer are spelled in full. Sections
+ written only for retrieval stay on the page and the reader personas in
+ ``docs/reader-persona.ts`` hide them client-side.
Every section below the Overview is conditional. A heading with nothing
- under it costs a reader a stop and puts the same stock sentence into the
- search index on thousands of pages, where it matches every query and
- distinguishes none of them. The Overview is the one exception: it is
- generated rather than looked up, so it always has something to say, and
- ``_extract_summary`` reads it back as the summary shown in search results
- and the wiki list.
+ under it costs a reader a stop and puts the same stock sentence on
+ thousands of pages. The Overview always says something, and
+ ``_extract_summary`` reads its first paragraph back as the summary shown in
+ search results, the wiki list and ``get_context``.
-#}
{%- set api_syms = ctx.symbols | api_symbols -%}
{%- set other_syms = ctx.symbols | internal_symbols -%}
{%- set git = ctx.git_metadata or {} -%}
+{%- set facts = ctx | file_facts -%}
+{#- "`a`, `b` and `c`", or "`a`, `b`, `c` and 4 more". -#}
+{%- macro name_list(names, more=0) -%}
+{%- set items = names + ([labels.and_count_more.format(count=more)] if more else []) -%}
+{%- if items | length > 1 -%}{{ items[:-1] | join(", ") }} {{ labels.and_word }} {{ items[-1] }}{%- else -%}{{ items | join("") }}{%- endif -%}
+{%- endmacro -%}
+{#- The opening, which is also the page summary the wiki list, search results
+ and ``get_context`` show. The author's docstring leads when there is one;
+ otherwise the first sentence names the file and says what it defines and
+ who imports it, and a second paragraph says where it sits. Every sentence
+ is conditional on the fact behind it. Sentences carry a ``{subject}`` slot:
+ the page's first sentence names the file, the rest say "it". -#}
+{%- set about = [] -%}
+{%- set where = [] -%}
+{%- if facts.defines -%}
+{%- set _ = about.append(labels.file_defines.format(subject="{subject}", names=name_list(facts.defines, facts.defines_more))) -%}
+{%- endif -%}
+{%- set imp = facts.importers -%}
+{%- if imp.listed -%}
+{%- set _ = about.append(labels.file_imported_by.format(subject="{subject}", names=name_list(imp.listed))) -%}
+{%- elif imp.count -%}
+{%- set _ = about.append(labels.file_imported_by_count.format(subject="{subject}", count=imp.count, tests=labels.of_them_tests.format(count=imp.tests) if imp.tests else "")) -%}
+{%- if imp.all_in_one -%}
+{%- set _ = about.append(labels.all_in_directory.format(directory=imp.directory)) -%}
+{%- elif imp.directory -%}
+{%- set _ = about.append((labels.largest_share_code if imp.tests else labels.largest_share).format(count=imp.share, directory=imp.directory)) -%}
+{%- endif -%}
+{%- endif -%}
+{%- set dep = facts.imports -%}
+{%- if dep.listed -%}
+{%- set _ = where.append(labels.file_imports.format(subject="{subject}", names=name_list(dep.listed))) -%}
+{%- elif dep.count -%}
+{%- set _ = where.append(labels.file_imports_count.format(subject="{subject}", count=dep.count)) -%}
+{%- if dep.all_in_one -%}
+{%- set _ = where.append(labels.all_in_directory.format(directory=dep.directory)) -%}
+{%- elif dep.directory -%}
+{%- set _ = where.append(labels.largest_share.format(count=dep.share, directory=dep.directory)) -%}
+{%- endif -%}
+{%- endif -%}
+{%- if ctx.kg_layer_name and ctx.kg_layer_role == "entry_point" -%}
+{%- set _ = where.append(labels.file_layer_entry.format(subject="{subject}", layer=ctx.kg_layer_name)) -%}
+{%- elif ctx.kg_layer_name and ctx.kg_layer_role == "edge_connector" -%}
+{%- set _ = where.append(labels.file_layer_boundary.format(subject="{subject}", layer=ctx.kg_layer_name)) -%}
+{%- elif ctx.kg_layer_name -%}
+{%- set _ = where.append(labels.file_layer.format(subject="{subject}", layer=ctx.kg_layer_name)) -%}
+{%- endif -%}
+{%- if ctx.is_entry_point and not (ctx.kg_layer_name and ctx.kg_layer_role == "entry_point") -%}
+{%- set _ = where.append(labels.file_entry_point.format(subject="{subject}")) -%}
+{%- endif -%}
+{%- if not (facts.purpose or about or where) -%}
+{%- set _ = about.append(labels.file_fallback.format(subject="{subject}", article=labels.article_an if ctx.language and ctx.language[0] in "aeiou" else labels.article_a, language=ctx.language)) -%}
+{%- endif -%}
+{%- set sentences = (about + where) | with_subject(labels.it_subject if facts.purpose else facts.name, labels.it_subject) -%}
+{%- set paragraphs = [facts.purpose, sentences] if facts.purpose else [sentences[:about | length], sentences[about | length:]] -%}
# {{ ctx.file_path }}
## {{ labels.overview }}
+{%- for paragraph in paragraphs if paragraph %}
+
+{{ paragraph if paragraph is string else paragraph | join(" ") }}
+{%- endfor %}
+{%- if ctx.decision_records %}
-{% if ctx.docstring %}{{ ctx.docstring | as_markdown }}{% else %}{% if ctx.kg_node_summary %}{{ ctx.kg_node_summary | oneline }} {% endif %}`{{ ctx.file_path }}` {{ labels.is_a }} {{ ctx.language }} {% if ctx.is_entry_point %}{{ labels.entry_point }} {% endif %}{% if ctx.is_test %}{{ labels.test }} {% endif %}{{ labels.source_file }}{% if ctx.kg_layer_name %} {{ labels.in_layer.format(layer=ctx.kg_layer_name) }}{% endif %}{% if ctx.community_label %}, {{ labels.part_of_module_cluster_intro.format(community=ctx.community_label) }}{% endif %}.{% endif %}
+## {{ labels.decisions_heading }}
+{% for dr in ctx.decision_records[:3] %}
+- **{{ dr.title | oneline(80) }}**: {{ dr.decision | oneline }}{% if dr.rationale %} *({{ dr.rationale | oneline(120) }})*{% endif %}
+{%- endfor %}
+{%- endif %}
+{#- The declared surface as a list a reader scans: each symbol's declaration
+ and the first sentence of its docstring, methods under their class.
+
+ Names that are public to the parser without being anything a caller
+ reaches for (``log``, ``__all__``) are declared under the list, not
+ dropped, with their signatures: ``content`` is also the index entry, and
+ ``log`` alone would take ``structlog`` and ``get_logger`` out of it.
+-#}
+{%- if api_syms or other_syms %}
+
+## {{ labels.public_api }}
{%- if api_syms %}
-{%- set symbol_word = labels.public_symbol_plural if api_syms | length != 1 else labels.public_symbol_singular %}
+{% for entry in api_syms | symbol_entries %}
+- {{ entry.declared }}{% if entry.doc %}: {{ entry.doc }}{% endif %}
+{%- for member in entry.members %}
+ - {{ member.declared }}{% if member.doc %}: {{ member.doc }}{% endif %}
+{%- endfor %}
+{%- endfor %}
+{%- endif %}
+{%- if other_syms %}
-{% if ctx.dependencies %}{{ labels.exposes_symbols_and_depends.format(symbol_count=api_syms | length, symbol_word=symbol_word, file_count=ctx.dependencies | length, file_word=labels.other_file_plural if ctx.dependencies | length != 1 else labels.other_file_singular) }}{% else %}{{ labels.exposes_symbols.format(symbol_count=api_syms | length, symbol_word=symbol_word) }}{% endif %}
+{{ labels.also_defined.format(names=other_syms | declarations | map("code_span") | join(", ")) }}
{%- endif %}
-{#- What the history knows and the code cannot say.
+{%- endif %}
+{#- Import neighbourhoods, one line per directory. The opening already says
+ how many and where most of them are; this is the lookup. Each path is
+ printed whole: it is what the reader's link resolves and what a question
+ matches in the index. -#}
+{%- for heading, paths in [(labels.used_by, ctx.dependents), (labels.depends_on, ctx.dependencies)] if paths %}
+
+## {{ heading }}
+{% for group in paths | group_paths %}
+- {{ group.paths | map("code_span") | join(", ") }}
+{%- endfor %}
+{%- if paths | length > 25 %}
- All of this was assembled already and thrown away at render time. That a
- file has been fixed twice and moves with ``incremental.py`` is something a
- reader acts on; twenty-five import paths are something they could have got
- from grep.
+_{{ labels.and_more.format(count=paths | length - 25) }}_
+{%- endif %}
+{%- endfor %}
+{#- What the history knows and the code cannot say, as one short paragraph.
Every clause is conditional on the number behind it, so a repository with
no git history renders no heading rather than a row of zeroes. Dates are
@@ -93,92 +182,9 @@
{{ labels.changes_with_intro }}
{% for cc in ctx.co_change_pages %}
-- `{{ cc.path }}` — {{ labels.changes_with_entry.format(count=cc.commits, commit_word=labels.commit_plural if cc.commits != 1 else labels.commit_singular) }}{% if cc.last %} ({{ labels.last_together.format(date=cc.last | datestamp) }}){% endif %}
-{%- endfor %}
-{%- endif %}
-{%- if ctx.decision_records %}
-
-## {{ labels.decisions_heading }}
-{% for dr in ctx.decision_records[:3] %}
-- **{{ dr.title | oneline(80) }}** — {{ dr.decision | oneline }}{% if dr.rationale %} *({{ dr.rationale | oneline(120) }})*{% endif %}
+- `{{ cc.path }}`: {{ labels.changes_with_entry.format(count=cc.commits, commit_word=labels.commit_plural if cc.commits != 1 else labels.commit_singular) }}{% if cc.last %} ({{ labels.last_together.format(date=cc.last | datestamp) }}){% endif %}
{%- endfor %}
{%- endif %}
-{#- The declared surface, and the names that are public to the parser without
- being anything a caller reaches for.
-
- ``log``, ``__all__`` and ``__init__`` made the table read as a symbol dump
- rather than as an API. They are declared under it instead of dropped, with
- their signatures and not just their names: ``content`` is also the index
- entry, and ``log`` alone would take ``structlog``, ``get_logger`` and
- ``__name__`` out of it. A constructor keeps its parameter list this way
- too, which the class's own row does not carry.
--#}
-{%- if api_syms or other_syms %}
-
-## {{ labels.public_api }}
-{%- if api_syms %}
-
-| {{ labels.symbol }} | {{ labels.kind }} | {{ labels.signature }} |
-| --- | --- | --- |
-{%- for s in api_syms %}
-| `{{ s.name }}` | {{ s.kind }} | {{ (s.signature or "") | signature | replace("|", "\\|") }} |
-{%- endfor %}
-{%- endif %}
-{%- if other_syms %}
-
-{{ labels.also_defined.format(names=other_syms | declarations | map("code_span") | join(", ")) }}
-{%- endif %}
-{%- endif %}
-{#- Dependency lists, grouped by the directory each path sits in.
-
- Flat, these were twenty-five strings in graph order — the same twenty-five
- a reader could have got from grep, and nothing about their shape. Grouped,
- the shape shows: of the files importing ``fs_walk``, nine are import
- resolvers. Each path is still printed whole, because dropping a directory
- prefix from a bullet would drop it from the index.
--#}
-{%- if ctx.dependencies %}
-
-## {{ labels.depends_on }}
-{%- for group in ctx.dependencies | group_paths %}
-
-**`{{ group.directory }}`**
-{% for dep in group.paths %}
-- `{{ dep }}`
-{%- endfor %}
-{%- endfor %}
-{%- if ctx.dependencies | length > 25 %}
-
-_{{ labels.and_more.format(count=ctx.dependencies | length - 25) }}_
-{%- endif %}
-{%- endif %}
-{%- if ctx.dependents %}
-
-## {{ labels.used_by }}
-
-{{ labels.imported_by_files.format(count=ctx.dependents | length, file_word=labels.file_plural if ctx.dependents | length != 1 else labels.file_singular) }}
-{%- for group in ctx.dependents | group_paths %}
-
-**`{{ group.directory }}`**
-{% for dep in group.paths %}
-- `{{ dep }}`
-{%- endfor %}
-{%- endfor %}
-{%- if ctx.dependents | length > 25 %}
-
-_{{ labels.and_more.format(count=ctx.dependents | length - 25) }}_
-{%- endif %}
-{%- endif %}
-{%- if ctx.community_label or ctx.kg_layer_name %}
-
-## {{ labels.usage_notes }}
-{% if ctx.community_label %}
-{{ labels.part_of_module_cluster.format(community=ctx.community_label) }}
-{%- endif %}
-{%- if ctx.kg_layer_name %}
-**{{ labels.layer }}:** {{ ctx.kg_layer_name }}{% if ctx.kg_layer_role %} | **{{ labels.role }}:** {% if ctx.kg_layer_role == "entry_point" %}{{ labels.role_entry_point }}{% elif ctx.kg_layer_role == "edge_connector" %}{{ labels.role_boundary }}{% else %}{{ labels.role_internal }}{% endif %}{% endif %}
-{%- endif %}
-{%- endif %}
{#- Question-shaped text, built from structure rather than prose.
Every search query is a question and this page is a declarative reference,
diff --git a/tests/unit/generation/test_deterministic_templates.py b/tests/unit/generation/test_deterministic_templates.py
index 4a5d65501..362dcda3a 100644
--- a/tests/unit/generation/test_deterministic_templates.py
+++ b/tests/unit/generation/test_deterministic_templates.py
@@ -230,6 +230,28 @@ def test_as_markdown_drops_rest_directives():
assert "Body text." in out
+def test_as_markdown_turns_a_rest_title_into_a_heading():
+ """Left as text, the underline renders and the title becomes the summary."""
+ from repowise.core.generation.page_generator.structural import as_markdown
+
+ out = as_markdown("Tagged JSON\n~~~~~~~~~~~\n\nA compact representation.\n")
+ assert out == "### Tagged JSON\n\nA compact representation."
+
+
+def test_as_markdown_drops_the_overline_of_a_rest_title():
+ from repowise.core.generation.page_generator.structural import as_markdown
+
+ out = as_markdown("=========\nBig Title\n=========\n\nSome prose.")
+ assert out == "### Big Title\n\nSome prose."
+
+
+def test_as_markdown_leaves_a_short_rule_under_prose_alone():
+ """reST requires the underline to be at least as long as the title."""
+ from repowise.core.generation.page_generator.structural import as_markdown
+
+ assert as_markdown("A longer line of prose.\n---\n") == "A longer line of prose.\n---"
+
+
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.structural import as_markdown
@@ -529,14 +551,15 @@ def test_file_page_renders_german_headings_and_prose(german_generator):
"## Öffentliche API",
"## Abhängigkeiten",
"## Wird verwendet von",
- "## Nutzungshinweise",
"## Fragen, die diese Seite beantwortet",
):
assert heading in page.content, heading
# The file vocabulary is embedded from metadata, never rendered.
assert "## Im Code" not in page.content
- assert "Sie stellt 1 öffentliches Symbol bereit" in page.content
- assert "Importiert von 1 Datei in diesem Repository." in page.content
+ assert "`parser.py` definiert `parse_file`." in page.content
+ assert "Die Datei wird von `src/pipeline.py` importiert." in page.content
+ assert "Die Datei gehört zur Schicht ingestion." in page.content
+ assert "Die Datei ist ein Einstiegspunkt." in page.content
# Identifiers are never translated, in any language.
assert "`src/service/parser.py`" in page.content
assert "`parse_file`" in page.content
diff --git a/tests/unit/generation/test_kg_aware_file_pages.py b/tests/unit/generation/test_kg_aware_file_pages.py
index fd2451124..69b74761a 100644
--- a/tests/unit/generation/test_kg_aware_file_pages.py
+++ b/tests/unit/generation/test_kg_aware_file_pages.py
@@ -349,9 +349,9 @@ class TestFilePageTemplate:
kg_layer_role="internal",
)
rendered = tmpl.render(ctx=ctx)
- assert "**Layer:** Core Pipeline" in rendered
- # The stored value is an enum member; the page spells it for a reader.
- assert "**Role:** internal to its layer" in rendered
+ assert "`utils.py` belongs to the Core Pipeline layer." in rendered
+ # The stored value is an enum member and never reaches the page.
+ assert "internal" not in rendered
def test_file_page_without_kg(self, jinja_env):
tmpl = jinja_env.get_template("file_page.j2")
@@ -374,4 +374,4 @@ class TestFilePageTemplate:
estimated_tokens=0,
)
rendered = tmpl.render(ctx=ctx)
- assert "**Layer:**" not in rendered
+ assert "layer" not in rendered
diff --git a/tests/unit/generation/test_overview_capability_table.py b/tests/unit/generation/test_overview_capability_table.py
index f94e46f01..08ca0d33e 100644
--- a/tests/unit/generation/test_overview_capability_table.py
+++ b/tests/unit/generation/test_overview_capability_table.py
@@ -495,3 +495,37 @@ async def test_no_capabilities_leaves_the_page_as_it_was(structure, parsed_files
structure, {}, [], {}, repo_name="testrepo", parsed_files=parsed_files
)
assert CAPABILITY_TABLE_HEADING not in page.content
+
+
+def test_embedding_nothing_removes_a_section_an_earlier_run_left():
+ """A model page is reused verbatim while its prompt is unchanged, and the
+ table is not part of the prompt. Rows an earlier selection embedded stay
+ on that page unless an empty selection takes them off."""
+ reused = "# Overview\n\nProse.\n\n## What it does\n\n| a | b |\n\n## Packages\n\nrows\n"
+ out = embed_capability_table(reused, None)
+ assert CAPABILITY_TABLE_HEADING not in out
+ assert out.startswith("# Overview\n\nProse.\n\n## Packages")
+
+
+async def test_a_reused_model_page_loses_rows_the_selection_no_longer_has(
+ structure, parsed_files
+):
+ from repowise.core.generation.models import GenerationConfig
+ from repowise.core.generation.page_generator import PageGenerator
+ from repowise.core.providers.llm.base import GeneratedResponse
+ from repowise.core.providers.llm.mock import MockProvider
+
+ earlier = (
+ "## Project Summary\n\nProse.\n\n## What it does\n\n"
+ "| Capability | What it is | Where it is written |\n|---|---|---|\n"
+ "| Dead code | — | `README.md` |\n"
+ )
+ provider = MockProvider(
+ responses=[GeneratedResponse(content=earlier, input_tokens=0, output_tokens=0)]
+ )
+ config = GenerationConfig()
+ page = await PageGenerator(provider, ContextAssembler(config), config).generate_repo_overview(
+ structure, {}, [], {}, repo_name="testrepo", parsed_files=parsed_files
+ )
+ assert CAPABILITY_TABLE_HEADING not in page.content
+ assert "| Dead code | — |" not in page.content
diff --git a/tests/unit/generation/test_structural_pages_read_like_a_wiki.py b/tests/unit/generation/test_structural_pages_read_like_a_wiki.py
index 0e2c866cc..ca00699cc 100644
--- a/tests/unit/generation/test_structural_pages_read_like_a_wiki.py
+++ b/tests/unit/generation/test_structural_pages_read_like_a_wiki.py
@@ -218,13 +218,13 @@ class TestPublicApi:
_symbol("SourceFile", "variable", signature="SourceFile = tuple[str, str]"),
]
)
- table = render(generator, ctx).split("## Public API", 1)[1].split("Also defined", 1)[0]
+ listed = render(generator, ctx).split("## Public API", 1)[1].split("Also defined", 1)[0]
- assert "`walk_repo`" in table
+ assert "- `def walk_repo() -> None`" in listed
# A capitalised module-level variable is a type alias, not module state.
- assert "`SourceFile`" in table
- for demoted in ("`log`", "`__all__`", "`__init__`"):
- assert demoted not in table
+ assert "- `SourceFile = tuple[str, str]`" in listed
+ for demoted in ("structlog", "__all__", "__init__"):
+ assert demoted not in listed
def test_a_demoted_name_is_still_spelled_on_the_page(self, generator):
# ``content`` is the index entry as well as the page. A name the table
@@ -251,7 +251,7 @@ class TestPublicApi:
assert "## Public API" in page
assert '`__all__ = ["walk_repo"]`' in page
- def test_the_signature_column_reads_as_a_declaration(self, generator):
+ def test_the_signature_reads_as_a_declaration(self, generator):
ctx = _context(
symbols=[
_symbol(
@@ -266,10 +266,36 @@ class TestPublicApi:
)
]
)
- row = next(ln for ln in render(generator, ctx).splitlines() if ln.startswith("| `walk_repo`"))
+ row = next(
+ ln for ln in render(generator, ctx).splitlines() if ln.startswith("- `def walk_repo")
+ )
assert "( root" not in row
- assert row.rstrip(" |").endswith("-> Iterator[tuple[Path, list[str], list[str]]]")
+ assert row.endswith("-> Iterator[tuple[Path, list[str], list[str]]]`")
+
+ def test_each_entry_carries_the_first_sentence_of_its_docstring(self, generator):
+ walk = _symbol("walk_repo")
+ walk["docstring"] = "Yield every directory under *root*.\n\nPrunes as it goes."
+ page = render(generator, _context(symbols=[walk]))
+
+ assert "- `def walk_repo() -> None`: Yield every directory under *root*." in page
+ assert "Prunes as it goes." not in page
+
+ def test_methods_sit_under_their_class(self, generator):
+ ctx = _context(
+ symbols=[
+ _symbol("WalkSnapshot", "class", signature="class WalkSnapshot"),
+ _symbol(
+ "is_live",
+ "method",
+ signature="def is_live(self, path: str) -> bool",
+ parent_name="WalkSnapshot",
+ ),
+ ]
+ )
+ page = render(generator, ctx)
+
+ assert "- `class WalkSnapshot`\n - `def is_live(self, path: str) -> bool`" in page
# ---------------------------------------------------------------------------
@@ -287,17 +313,23 @@ DEPS = [
class TestDependencyGrouping:
- def test_paths_are_grouped_by_directory_busiest_first(self, generator):
+ def test_one_line_per_directory_busiest_first(self, generator):
section = render(generator, _context(dependencies=DEPS)).split("## Depends on", 1)[1]
- headings = [ln for ln in section.splitlines() if ln.startswith("**`")]
+ lines = [ln for ln in section.splitlines() if ln.startswith("- ")]
- assert headings[:2] == ["**`pkg/resolvers`**", "**`pkg/pipeline`**"]
+ assert lines[:2] == [
+ "- `pkg/resolvers/go.py`, `pkg/resolvers/ruby.py`, `pkg/resolvers/swift.py`",
+ "- `pkg/pipeline/run.py`",
+ ]
def test_every_path_is_still_printed_whole(self, generator):
page = render(generator, _context(dependencies=DEPS, dependents=DEPS))
+ used_by = page.split("## Used by", 1)[1].split("## Depends on", 1)[0]
+ depends_on = page.split("## Depends on", 1)[1]
for path in DEPS:
- assert f"- `{path}`" in page
+ assert f"`{path}`" in used_by
+ assert f"`{path}`" in depends_on
def test_grouping_leaves_no_gap_between_sections(self, generator):
page = render(
@@ -312,29 +344,36 @@ class TestLayerRole:
@pytest.mark.parametrize(
"role,expected",
[
- ("edge_connector", "boundary"),
- ("entry_point", "entry point"),
- ("internal", "internal to its layer"),
+ ("edge_connector", "It belongs to the Core Pipeline layer, and other layers import it."),
+ ("entry_point", "It belongs to the Core Pipeline layer and is an entry point into it."),
+ ("internal", "It belongs to the Core Pipeline layer."),
],
)
def test_the_role_is_spelled_for_a_reader(self, generator, role, expected):
page = render(generator, _context(kg_layer_name="Core Pipeline", kg_layer_role=role))
assert expected in page
- assert "edge_connector" not in page
+ assert role not in page
class TestOverview:
- def test_a_file_with_no_docstring_borrows_the_graph_summary(self, generator):
+ def test_a_test_file_borrows_the_graph_summary(self, generator):
page = render(
generator,
- _context(docstring=None, kg_node_summary="Prunes junk directories during a walk."),
+ _context(docstring=None, is_test=True, kg_node_summary="Tests for the walker."),
)
- assert "Prunes junk directories during a walk." in page
- # The structural sentence still follows it: it is what names the
- # language and the layer.
- assert "is a python source file" in page
+ assert "## Overview\n\nTests for the walker." in page
+
+ def test_code_that_defines_symbols_is_described_by_them(self, generator):
+ # The graph's summary would only restate the names, less precisely.
+ page = render(
+ generator,
+ _context(docstring=None, kg_node_summary="Service module walk defining walk_repo."),
+ )
+
+ assert "Service module" not in page
+ assert "`walk.py` defines `walk_repo`." in page
def test_a_docstring_still_wins(self, generator):
page = render(generator, _context(kg_node_summary="Machine summary."))
@@ -343,6 +382,235 @@ class TestOverview:
assert "Machine summary." not in page
+class TestOpening:
+ """The first paragraph is the page summary ``get_context`` and search show,
+ so it has to say something specific about the file on every page."""
+
+ def test_without_a_docstring_it_says_what_the_file_defines_and_who_uses_it(
+ self, generator
+ ):
+ ctx = _context(
+ docstring=None,
+ symbols=[_symbol(n) for n in ("walk_repo", "load", "dump", "prune", "scan")],
+ dependents=[*DEPS, "tests/test_walk.py"],
+ )
+ page = generator._render_page(
+ page_type="file_page",
+ target_path=ctx.file_path,
+ title="File: pkg/mod/walk.py",
+ template="file_page.j2",
+ ctx=ctx,
+ )
+
+ assert page.summary == (
+ "`walk.py` defines `walk_repo`, `load`, `dump` and 2 more. "
+ "It is imported by 5 files (1 of them tests). "
+ "Of the others, 3 are in `pkg/resolvers`."
+ )
+
+ def test_a_short_neighbourhood_is_named_in_full(self, generator):
+ page = render(
+ generator,
+ _context(docstring=None, dependents=["pkg/cli/main.py"], dependencies=DEPS[:2]),
+ )
+
+ assert "It is imported by `pkg/cli/main.py`." in page
+ assert "It imports `pkg/resolvers/go.py` and `pkg/resolvers/ruby.py`." in page
+
+ def test_the_docstring_leads_and_the_facts_follow_it(self, generator):
+ page = render(generator, _context(dependents=["pkg/cli/main.py"]))
+ overview = page.split("## Overview\n\n", 1)[1].split("\n\n## ", 1)[0]
+
+ assert overview == (
+ "Walks a repository tree.\n\n"
+ "It defines `walk_repo`. It is imported by `pkg/cli/main.py`."
+ )
+
+ def test_a_rest_titled_docstring_is_summarised_by_its_prose(self, generator):
+ ctx = _context(docstring="Tagged JSON\n~~~~~~~~~~~\n\nA compact representation.")
+ page = generator._render_page(
+ page_type="file_page",
+ target_path=ctx.file_path,
+ title="File: pkg/mod/walk.py",
+ template="file_page.j2",
+ ctx=ctx,
+ )
+
+ assert page.summary == "A compact representation."
+
+ def test_an_overlined_rest_title_is_not_the_summary(self, generator):
+ ctx = _context(docstring="=========\nBig Title\n=========\n\nSome prose.")
+ page = generator._render_page(
+ page_type="file_page",
+ target_path=ctx.file_path,
+ title="File: pkg/mod/walk.py",
+ template="file_page.j2",
+ ctx=ctx,
+ )
+
+ assert page.summary == "Some prose."
+
+ def test_rust_impl_blocks_and_fields_are_not_definitions(self, generator):
+ ctx = _context(
+ docstring=None,
+ symbols=[
+ _symbol("Foo", "struct", signature="pub struct Foo"),
+ _symbol("x", "property", signature="pub x: i32"),
+ _symbol("Foo", "impl", signature="impl Foo"),
+ _symbol("area", "method", signature="pub fn area(&self) -> f64", parent_name="Foo"),
+ _symbol("Foo", "impl", signature="impl Foo"),
+ ],
+ )
+ page = render(generator, ctx)
+
+ assert "`walk.py` defines `Foo`." in page
+ assert page.count("impl Foo") == 0
+ assert "- `pub struct Foo`\n - `pub fn area(&self) -> f64`" in page
+
+ def test_a_method_of_an_unlisted_class_is_nested_not_top_level(self, generator):
+ ctx = _context(
+ docstring=None,
+ symbols=[_symbol("run", "method", signature="def run(self)", parent_name="_Impl")],
+ )
+ page = render(generator, ctx)
+
+ assert "defines `run`" not in page
+ assert "- `_Impl`\n - `def run(self)`" in page
+
+ def test_a_barrel_keeps_the_graph_summary(self, generator):
+ page = render(
+ generator,
+ _context(docstring=None, kg_tags=["barrel"], kg_node_summary="Re-export barrel for x/."),
+ )
+
+ assert "## Overview\n\nRe-export barrel for x/." in page
+
+ def test_the_fallback_uses_the_right_article(self, generator):
+ page = render(generator, _context(docstring=None, symbols=[], language="elixir"))
+
+ assert "`walk.py` is an elixir file." in page
+
+ def test_a_directory_is_named_only_when_it_clearly_leads(self, generator):
+ spread = ["a/one.py", "b/two.py", "c/three.py", "d/four.py"]
+ page = render(generator, _context(docstring=None, dependents=spread))
+
+ assert "It is imported by 4 files." in page
+ assert " are in " not in page
+
+ def test_types_are_named_before_values(self, generator):
+ ctx = _context(
+ docstring=None,
+ symbols=[
+ _symbol("T_hook", "variable", signature="T_hook = TypeVar('T_hook')"),
+ _symbol("helper"),
+ _symbol("Walker", "class", signature="class Walker"),
+ ],
+ )
+
+ assert "`walk.py` defines `Walker`, `helper` and `T_hook`." in render(generator, ctx)
+
+ def test_a_single_directory_is_said_once(self, generator):
+ page = render(generator, _context(dependents=[*DEPS[:3], "pkg/resolvers/zig.py"]))
+
+ assert "It is imported by 4 files. All of them are in `pkg/resolvers`." in page
+
+ def test_importers_that_are_all_tests_name_no_directory(self, generator):
+ tests = [f"tests/test_{n}.py" for n in ("a", "b", "c", "d")]
+ page = render(generator, _context(dependents=tests))
+
+ assert "It is imported by 4 files (4 of them tests)." in page
+ assert "Of the others" not in page
+
+ def test_an_entry_point_says_so(self, generator):
+ page = render(generator, _context(is_entry_point=True))
+
+ assert "It is an entry point." in page
+
+ def test_a_file_the_index_knows_nothing_about_still_gets_a_sentence(self, generator):
+ page = render(generator, _context(docstring=None, symbols=[]))
+
+ assert "## Overview\n\n`walk.py` is a python file." in page
+
+
+# A backslash at a line end joins it to the next: the page's paragraphs are
+# single lines, wider than the source allows.
+GOLDEN = """# pkg/mod/walk.py
+
+## Overview
+
+`walk.py` defines `WalkSnapshot` and `walk_repo`. It is imported by `pkg/cli/main.py`.
+
+It imports 4 files from this repository. 3 of them are in `pkg/resolvers`. \
+It belongs to the Core Pipeline layer, and other layers import it.
+
+## Public API
+
+- `def walk_repo() -> None`: Yield every directory under *root*.
+- `class WalkSnapshot`
+ - `def is_live(self, path: str) -> bool`
+
+Also defined: `log = structlog.get_logger(__name__)`.
+
+## Used by
+
+- `pkg/cli/main.py`
+
+## Depends on
+
+- `pkg/resolvers/go.py`, `pkg/resolvers/ruby.py`, `pkg/resolvers/swift.py`
+- `pkg/pipeline/run.py`
+
+## History
+
+27 commits in its history, 9 in the last 90 days. The last landed on 2026-08-17. \
+**Ada Lovelace** is its primary maintainer, at 62% of commits. \
+12 of those commits fixed a bug. It is one of the repository's change hotspots.
+
+## Changes together with
+
+Files that change in the same commits as this one without importing it or being imported by it.
+
+- `pkg/mod/persist.py`: 28 shared commits (last together on 2026-08-29)
+
+## Questions this page answers
+
+- What does `pkg/mod/walk.py` export?
+- Where is `walk_repo` defined?
+- What imports `pkg/mod/walk.py`?
+
+---
+
+*Generated from parsed code, the import graph and git history.*"""
+
+
+def test_a_whole_page_renders_as_expected(generator):
+ """One page end to end, so spacing and section order are pinned too."""
+ walk = _symbol("walk_repo")
+ walk["docstring"] = "Yield every directory under *root*. Prunes as it goes."
+ ctx = _context(
+ docstring=None,
+ symbols=[
+ walk,
+ _symbol("WalkSnapshot", "class", signature="class WalkSnapshot"),
+ _symbol(
+ "is_live",
+ "method",
+ signature="def is_live(self, path: str) -> bool",
+ parent_name="WalkSnapshot",
+ ),
+ _symbol("log", "variable", signature="log = structlog.get_logger(__name__)"),
+ ],
+ dependents=["pkg/cli/main.py"],
+ dependencies=DEPS,
+ git_metadata=GIT,
+ co_change_pages=[{"path": "pkg/mod/persist.py", "commits": 28, "last": "2026-08-29"}],
+ kg_layer_name="Core Pipeline",
+ kg_layer_role="edge_connector",
+ )
+
+ assert render(generator, ctx).strip() == GOLDEN
+
+
# ---------------------------------------------------------------------------
# The constraint: nothing leaves ``content``
# ---------------------------------------------------------------------------