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): a module page names its own symbols, not only prose about them (#1211)

Swati Ahuja42035a26c70c
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py
index 2c4552423..dffb5c465 100644
--- a/packages/core/src/repowise/core/generation/context/assembler.py
+++ b/packages/core/src/repowise/core/generation/context/assembler.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import re
from pathlib import PurePosixPath
from typing import Any
@@ -54,6 +55,83 @@ def _is_foreign_edge(node: str, path: str) -> bool:
_MAX_IMPORTS = 30
# Maximum top-files to include in repo overview
_MAX_TOP_FILES = 20
+# How many rows the concept index may carry. A module page groups directories,
+# so a wide one can reach several hundred public symbols and the table would
+# then be longer than the page it is attached to. Rows past this are counted
+# rather than dropped silently, so a truncated table cannot read as a complete
+# public surface.
+_MAX_CONCEPT_ROWS = 40
+
+# Identifier word splits: a snake_case underscore, or the boundary before a
+# capital that starts a new word. The second pattern keeps acronym runs whole —
+# ``HTTPAdapter`` is two words, not nine — which matters because the acronym is
+# usually the word a reader would actually say.
+_IDENTIFIER_SPLIT = re.compile(r"_+|(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])")
+
+
+def concept_wording(identifier: str) -> str:
+ """Spell an identifier the way prose would say it.
+
+ ``ResolverContext`` becomes "Resolver context" — the noun a reader who has
+ only read the page's prose would use, next to the token they have to type
+ to find it. Derived rather than written: a described column could name a
+ symbol that is not there, and the point of this table is that it cannot.
+ """
+ words = [w for w in _IDENTIFIER_SPLIT.split(identifier) if w]
+ if not words:
+ return identifier
+ # An acronym inside a camel-cased name keeps its case ("HTTPAdapter" →
+ # "HTTP adapter"), because the acronym is the word a reader would say. An
+ # underscore-separated name is lowered whole: ``EMBED_BATCH_MAX_ITEMS`` is a
+ # constant spelled in caps, not four acronyms.
+ keep_case = "_" not in identifier
+ spelled = [w if keep_case and w.isupper() and len(w) > 1 else w.lower() for w in words]
+ first = spelled[0]
+ return " ".join([first[:1].upper() + first[1:], *spelled[1:]])
+
+
+def build_concept_index(
+ file_contexts: list[FilePageContext],
+) -> tuple[list[dict[str, str]], int]:
+ """Rows pairing each public symbol's prose name with its identifier and file.
+
+ Returns the rows and how many were left off by the cap.
+
+ Module pages are written by the model and come out as prose: a real run
+ produced 89 of them carrying four fenced code blocks between them. So the
+ identifiers a reader needs to grep for, and an identifier-exact query needs
+ to match, are not on the page in any spelling. These rows put them there,
+ straight from the assembled symbol data, which is why the table can be
+ trusted where the surrounding prose has to be read as a summary.
+
+ Only top-level public symbols. Methods would multiply the table by the size
+ of the classes without adding a name a reader would search for on its own,
+ and a private symbol is not a route into the module.
+ """
+ ranked = sorted(file_contexts, key=lambda fc: fc.pagerank_score, reverse=True)
+ rows: list[dict[str, str]] = []
+ total = 0
+ for fc in ranked:
+ for symbol in sorted(fc.symbols, key=lambda s: s.get("start_line") or 0):
+ name = (symbol.get("name") or "").strip()
+ if not name or name.startswith("_"):
+ continue
+ if symbol.get("visibility") != "public":
+ continue
+ # A method's own name is rarely what a reader searches for, and
+ # including them turns a 40-row cap into 40 rows of one class.
+ if symbol.get("parent_name"):
+ continue
+ total += 1
+ if len(rows) < _MAX_CONCEPT_ROWS:
+ rows.append(
+ {
+ "concept": concept_wording(name),
+ "symbol": name,
+ "file": fc.file_path,
+ }
+ )
+ return rows, total - len(rows)
def _file_dependency_neighbors(graph: Any, path: str, *, incoming: bool) -> list[str]:
@@ -577,9 +655,7 @@ class ContextAssembler:
# list is a different list on every run.
sorted_pr = sorted(pagerank.items(), key=lambda x: (-x[1], x[0]))
top_files = [
- _TopFile(path=p, score=s)
- for p, s in sorted_pr[:_MAX_TOP_FILES]
- if not is_external(p)
+ _TopFile(path=p, score=s) for p, s in sorted_pr[:_MAX_TOP_FILES] if not is_external(p)
]
# SCCs with len > 1 are true circular deps
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 99cddd50d..f43522a11 100644
--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py
+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py
@@ -18,6 +18,7 @@ from repowise.core.ingestion.models import ParsedFile, RepoStructure
from .. import onboarding as _onboarding
from ..architecture_mermaid import embed_mermaid
+from ..context.assembler import build_concept_index
from ..context_assembler import FilePageContext
from ..models import (
GENERATION_LEVELS,
@@ -233,9 +234,31 @@ class PerTypeGenerationMixin:
page.structural_key = structural_key or page.structural_key
return page
+ def _with_concept_index(page: GeneratedPage) -> GeneratedPage:
+ """Append the module's own identifiers to whatever wrote the page.
+
+ After generation rather than inside the prompt, and that placement
+ is the point. ``module_page.j2`` is a prompt: a table put in it is
+ material the model may reformat, abbreviate or drop, and a page
+ whose identifiers came out of a provider is exactly as trustworthy
+ as the prose around them. Appended here, every name and path is the
+ symbol index's and no response can change it.
+
+ After ``_build_generated_page`` too, so the page summary is still
+ drawn from the model's opening rather than from a table row.
+ """
+ rows, omitted = build_concept_index(file_contexts)
+ if not rows:
+ return page
+ table = self._render(
+ "_concept_index_table.j2", style_prefix=False, rows=rows, omitted=omitted
+ )
+ page.content = f"{(page.content or '').rstrip()}\n\n{table.strip()}\n"
+ return page
+
if self._config.deterministic:
page = self._stub_module_page(ctx, page_target, title, module_git_summary)
- return _stamp_concept(page)
+ return _stamp_concept(_with_concept_index(page))
user_prompt = self._render("module_page.j2", ctx=ctx, module_git_summary=module_git_summary)
try:
response = await self._call_provider(
@@ -243,7 +266,7 @@ class PerTypeGenerationMixin:
)
except Exception as exc:
stub = self._stub_module_page(ctx, page_target, title, module_git_summary)
- return _stamp_concept(_stub_fallback(stub, "module_page", exc))
+ return _stamp_concept(_with_concept_index(_stub_fallback(stub, "module_page", exc)))
page = self._build_generated_page(
"module_page",
page_target,
@@ -252,7 +275,7 @@ class PerTypeGenerationMixin:
compute_source_hash(user_prompt),
GENERATION_LEVELS["module_page"],
)
- return _stamp_concept(page)
+ return _stamp_concept(_with_concept_index(page))
async def generate_scc_page(
self,
diff --git a/packages/core/src/repowise/core/generation/report.py b/packages/core/src/repowise/core/generation/report.py
index 4c5cee792..466f25991 100644
--- a/packages/core/src/repowise/core/generation/report.py
+++ b/packages/core/src/repowise/core/generation/report.py
@@ -122,6 +122,28 @@ def measure_opening_frames(pages: list[GeneratedPage]) -> OpeningFrameReport:
)
+# The heading over the identifiers appended to a module page after the model
+# has written it. Counted for the same reason the questions block is: the table
+# is conditional (a module exporting nothing renders none), so only the ratio
+# is readable, and nothing else in a run would report it going to zero.
+CONCEPT_INDEX_HEADING = "## Concept index"
+
+
+def _count_concept_indexes(pages: list[GeneratedPage]) -> dict[str, int]:
+ """How many module pages carry their identifiers, out of how many exist.
+
+ The append happens after the provider call, which is the failure mode worth
+ watching: an exception path or a refactor that returns the page before the
+ append would leave every module page pure prose again, and every test in
+ the suite would still pass because the templates are all still correct.
+ """
+ eligible = [p for p in pages if p.page_type == "module_page"]
+ return {
+ "eligible_pages": len(eligible),
+ "with_index": sum(1 for p in eligible if CONCEPT_INDEX_HEADING in (p.content or "")),
+ }
+
+
def _count_question_blocks(pages: list[GeneratedPage]) -> dict[str, int]:
"""How many template pages carry question-shaped text, out of how many.
@@ -185,6 +207,11 @@ class GenerationReport:
# standing as the description of several different subsystems. Read
# ``measured`` before reading the counts.
opening_frames: OpeningFrameReport = field(default_factory=OpeningFrameReport)
+ # How far the module-page concept index reached across this run. Same shape
+ # and same reason as ``question_blocks``: with its own denominator, "this
+ # run wrote no module pages" and "the append stopped happening" stay
+ # separate facts, and neither one raises on its own.
+ concept_indexes: dict[str, int] = field(default_factory=dict)
@classmethod
def from_pages(
@@ -221,6 +248,7 @@ class GenerationReport:
pages_denied_a_vector=pages_denied_a_vector(),
question_blocks=_count_question_blocks(pages),
opening_frames=measure_opening_frames(pages),
+ concept_indexes=_count_concept_indexes(pages),
overview_prose_words=next(
(
prose_word_count(p.content or "")
@@ -269,6 +297,25 @@ class GenerationReport:
return "not measured (0 template pages)"
return f"{self.question_blocks.get('with_questions', 0)} of {eligible} pages"
+ @property
+ def concept_indexes_missing(self) -> bool:
+ """Whether a module page this run wrote came out without its identifiers.
+
+ Warn-only and legitimately non-zero: a module whose members export
+ nothing has no rows to render. The case worth seeing is the number
+ falling to zero across a run that wrote module pages, which is what the
+ append having stopped looks like from outside.
+ """
+ eligible = self.concept_indexes.get("eligible_pages", 0)
+ return bool(eligible) and self.concept_indexes.get("with_index", 0) < eligible
+
+ def concept_index_summary(self) -> str:
+ """One line saying how far the concept index reached this run."""
+ eligible = self.concept_indexes.get("eligible_pages", 0)
+ if not eligible:
+ return "not measured (0 module pages)"
+ return f"{self.concept_indexes.get('with_index', 0)} of {eligible} pages"
+
def artifact_check_summary(self) -> str:
"""One line saying whether the artifact checks ran, and what they found."""
checked = self.artifact_checks.get("responses_checked", 0)
@@ -372,6 +419,10 @@ def render_generation_checks(report: GenerationReport, console: object) -> None:
if frames.over_budget:
frames_text = f"[yellow]{frames_text}[/yellow]"
table.add_row("Module page openings", frames_text)
+ concept_text = report.concept_index_summary()
+ if report.concept_indexes_missing:
+ concept_text = f"[yellow]{concept_text}[/yellow]"
+ table.add_row("Module concept index", concept_text)
console.print(table) # type: ignore[union-attr]
diff --git a/packages/core/src/repowise/core/generation/templates/_concept_index_table.j2 b/packages/core/src/repowise/core/generation/templates/_concept_index_table.j2
new file mode 100644
index 000000000..9b2c0ef49
--- /dev/null
+++ b/packages/core/src/repowise/core/generation/templates/_concept_index_table.j2
@@ -0,0 +1,18 @@
+{#- The identifiers behind the page's prose, rendered from the assembled symbol
+ data and appended after the model has written the page. Nothing here passes
+ through a provider, so the names and paths are the index's own.
+
+ Rendered only when there is at least one row: a header with nothing under
+ it claims the module exports nothing, in the same shape as a real answer. -#}
+## Concept index
+
+What the prose above calls things, the identifier to search for, and where it lives.
+
+| Concept | Symbol | File |
+| --- | --- | --- |
+{% for row in rows -%}
+| {{ row.concept }} | `{{ row.symbol }}` | `{{ row.file }}` |
+{% endfor -%}
+{%- if omitted %}
+_{{ omitted }} further public symbol{{ "s" if omitted != 1 else "" }} in this module are not listed._
+{% endif -%}
diff --git a/tests/unit/generation/test_concept_index_reaches_search.py b/tests/unit/generation/test_concept_index_reaches_search.py
new file mode 100644
index 000000000..e9ad64dd2
--- /dev/null
+++ b/tests/unit/generation/test_concept_index_reaches_search.py
@@ -0,0 +1,173 @@
+"""The concept index has to reach the index, not just the rendered page.
+
+The table exists to make an identifier-exact query match the identifier rather
+than the model's description of it. That only happens if the table text lands
+in the full-text row. Nothing raises if it does not: the write path is handed
+``page.content`` verbatim, so a table appended after the row was written, or
+stripped on the way to persistence, would show up as a page that reads well and
+cannot be found by the one token a reader would search for.
+
+Module pages are the page type with the least to match on — a real run produced
+89 of them carrying four fenced code blocks between them — so this round trip
+is the whole mechanism, not a detail of it.
+"""
+
+from __future__ import annotations
+
+import networkx as nx
+import pytest
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.core.generation.context_assembler import ContextAssembler, FilePageContext
+from repowise.core.generation.models import GenerationConfig
+from repowise.core.generation.page_generator import PageGenerator
+from repowise.core.persistence.crud import upsert_page, upsert_repository
+from repowise.core.persistence.database import init_db
+from repowise.core.persistence.search import FullTextSearch
+from repowise.core.providers.llm.mock import MockProvider
+
+
+class _ProseOnlyProvider(MockProvider):
+ """Writes a page naming no symbol, so a match can only come from the table."""
+
+ async def generate(self, *args, **kwargs):
+ response = await super().generate(*args, **kwargs)
+ response.content = (
+ "# Resolution Layer\n\nThe layer turns references into edges it can walk.\n"
+ )
+ return response
+
+
+async def fts():
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+ search = FullTextSearch(engine)
+ await search.ensure_index()
+ yield engine, search
+ await engine.dispose()
+
+
+def _file_context(path: str, names: list[str]) -> FilePageContext:
+ return FilePageContext(
+ file_path=path,
+ language="python",
+ docstring=None,
+ symbols=[
+ {
+ "name": name,
+ "qualified_name": name,
+ "kind": "class",
+ "signature": "",
+ "docstring": "",
+ "visibility": "public",
+ "is_async": False,
+ "complexity_estimate": 1,
+ "decorators": [],
+ "parent_name": "",
+ "start_line": i,
+ "end_line": i,
+ }
+ for i, name in enumerate(names, start=1)
+ ],
+ imports=[],
+ exports=names,
+ file_source_snippet="",
+ pagerank_score=0.5,
+ betweenness_score=0.0,
+ community_id=0,
+ dependents=[],
+ dependencies=[],
+ is_api_contract=False,
+ is_entry_point=False,
+ is_test=False,
+ parse_errors=[],
+ estimated_tokens=10,
+ )
+
+
+async def _index(engine, search, *, page_id, title, target_path, content):
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as session:
+ repo = await upsert_repository(session, name="r", local_path="/tmp/r")
+ await session.commit()
+ await upsert_page(
+ session,
+ page_id=page_id,
+ repository_id=repo.id,
+ page_type="module_page",
+ title=title,
+ content=content,
+ summary="",
+ target_path=target_path,
+ source_hash="h",
+ model_name="mock",
+ provider_name="mock",
+ )
+ await session.commit()
+ await search.index(page_id, title, content, summary="", target_path=target_path)
+
+
+async def _matches(search: FullTextSearch, query: str) -> list[str]:
+ return [r.page_id for r in await search.search(query, limit=10)]
+
+
+async def test_a_module_page_is_findable_by_a_symbol_it_contains(fts):
+ engine, search = fts
+ config = GenerationConfig(max_tokens=1024, token_budget=2000, max_concurrency=2)
+ generator = PageGenerator(_ProseOnlyProvider(), ContextAssembler(config), config)
+
+ page = await generator.generate_module_page(
+ "Resolution Layer",
+ "python",
+ [_file_context("core/resolvers/context.py", ["ResolverContext"])],
+ nx.DiGraph(),
+ target_path="core/resolvers",
+ structural_key="k",
+ )
+ # The prose the model wrote does not contain the identifier, so a hit below
+ # can only have come from the appended table.
+ assert "ResolverContext" not in page.content.split("## Concept index")[0]
+
+ await _index(
+ engine,
+ search,
+ page_id=page.page_id,
+ title=page.title,
+ target_path=page.target_path,
+ content=page.content,
+ )
+
+ assert page.page_id in await _matches(search, "ResolverContext")
+
+
+async def test_the_prose_spelling_finds_the_page_too(fts):
+ """Both columns are indexed, so the reader who only knows the words for the
+ thing and the reader who knows the token land on the same page."""
+ engine, search = fts
+ config = GenerationConfig(max_tokens=1024, token_budget=2000, max_concurrency=2)
+ generator = PageGenerator(_ProseOnlyProvider(), ContextAssembler(config), config)
+
+ page = await generator.generate_module_page(
+ "Resolution Layer",
+ "python",
+ [_file_context("core/resolvers/tsconfig.py", ["TsconfigResolver"])],
+ nx.DiGraph(),
+ target_path="core/resolvers",
+ structural_key="k",
+ )
+ await _index(
+ engine,
+ search,
+ page_id=page.page_id,
+ title=page.title,
+ target_path=page.target_path,
+ content=page.content,
+ )
+
+ assert page.page_id in await _matches(search, "Tsconfig resolver")
diff --git a/tests/unit/generation/test_concept_index_report.py b/tests/unit/generation/test_concept_index_report.py
new file mode 100644
index 000000000..c05789020
--- /dev/null
+++ b/tests/unit/generation/test_concept_index_report.py
@@ -0,0 +1,98 @@
+"""The run reports how far the module concept index reached.
+
+The table is appended in code, after the provider call, which is a quieter
+place to lose something than a template. An early return on an error path, or a
+refactor that hands back the page before the append, leaves every module page
+pure prose again — and every template test in the suite still passes, because
+none of the templates changed. This counter is the only thing that would say so.
+
+Its own denominator, for the same reason the questions counter carries one: a
+bare zero is either "this run wrote no module pages" or "the append stopped",
+and those need different responses.
+"""
+
+from __future__ import annotations
+
+from repowise.core.generation.models import GeneratedPage
+from repowise.core.generation.report import CONCEPT_INDEX_HEADING, GenerationReport
+
+_WITH = (
+ "# Resolution Layer\n\nProse.\n\n"
+ f"{CONCEPT_INDEX_HEADING}\n\n"
+ "| Concept | Symbol | File |\n| --- | --- | --- |\n"
+ "| Resolver context | `ResolverContext` | `a.py` |\n"
+)
+_WITHOUT = "# Resolution Layer\n\nProse.\n"
+
+
+def _page(page_id: str, page_type: str, content: str) -> GeneratedPage:
+ return GeneratedPage(
+ page_id=page_id,
+ page_type=page_type,
+ title=page_id,
+ content=content,
+ source_hash="",
+ model_name="mock",
+ provider_name="mock",
+ input_tokens=0,
+ output_tokens=0,
+ cached_tokens=0,
+ generation_level=3,
+ target_path="",
+ created_at="2026-08-01T00:00:00Z",
+ updated_at="2026-08-01T00:00:00Z",
+ )
+
+
+def test_the_report_counts_module_pages_carrying_their_identifiers():
+ report = GenerationReport.from_pages(
+ [
+ _page("module_page:a", "module_page", _WITH),
+ _page("module_page:b", "module_page", _WITHOUT),
+ _page("file_page:c.py", "file_page", _WITHOUT),
+ ]
+ )
+
+ assert report.concept_indexes == {"eligible_pages": 2, "with_index": 1}
+ assert report.concept_index_summary() == "1 of 2 pages"
+
+
+def test_a_run_with_no_module_pages_says_so_rather_than_reporting_zero():
+ report = GenerationReport.from_pages([_page("file_page:a.py", "file_page", _WITHOUT)])
+
+ assert report.concept_indexes == {"eligible_pages": 0, "with_index": 0}
+ assert report.concept_index_summary() == "not measured (0 module pages)"
+ assert report.concept_indexes_missing is False
+
+
+def test_the_check_flags_a_run_where_the_append_stopped():
+ """The failure this exists to catch: module pages written, none of them
+ carrying the identifiers they were supposed to gain."""
+ report = GenerationReport.from_pages(
+ [
+ _page("module_page:a", "module_page", _WITHOUT),
+ _page("module_page:b", "module_page", _WITHOUT),
+ ]
+ )
+
+ assert report.concept_indexes == {"eligible_pages": 2, "with_index": 0}
+ assert report.concept_indexes_missing is True
+
+
+def test_a_full_run_is_not_flagged():
+ report = GenerationReport.from_pages([_page("module_page:a", "module_page", _WITH)])
+
+ assert report.concept_indexes_missing is False
+
+
+def test_the_check_prints_even_when_it_measured_nothing():
+ from io import StringIO
+
+ from rich.console import Console
+
+ from repowise.core.generation.report import render_generation_checks
+
+ buffer = StringIO()
+ render_generation_checks(GenerationReport.from_pages([]), Console(file=buffer, width=100))
+
+ assert "Module concept index" in buffer.getvalue()
diff --git a/tests/unit/generation/test_module_page_concept_index.py b/tests/unit/generation/test_module_page_concept_index.py
new file mode 100644
index 000000000..518237489
--- /dev/null
+++ b/tests/unit/generation/test_module_page_concept_index.py
@@ -0,0 +1,246 @@
+"""A module page carries its members' identifiers, not only prose about them.
+
+Module pages are the one page type written entirely by the model, and they come
+out as prose: across a real run of 89 of them, four carried a fenced code block
+at all. A reader who has just read "the resolver context" has no identifier to
+grep for, and an identifier-exact query matches the description of the code
+rather than the code.
+
+The concept index closes that. It is rendered from the assembled symbol data
+and appended after the model has written the page, so the identifiers and the
+paths in it are the index's, not the model's, and no provider response can
+change them. That placement is the whole point: put the same table in the
+prompt and the model may reformat it, abbreviate a path, or drop it.
+
+A page whose members export nothing renders no table rather than an empty one —
+a header row with no rows under it is a claim that the module has no public
+surface, made in the same shape as a real answer.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import pytest
+
+from repowise.core.generation.context.assembler import build_concept_index
+from repowise.core.generation.context_assembler import ContextAssembler, FilePageContext
+from repowise.core.generation.page_generator import PageGenerator
+from repowise.core.providers.llm.mock import MockProvider
+
+CONCEPT_INDEX_HEADING = "## Concept index"
+
+
+class _ProseOnlyProvider(MockProvider):
+ """A provider whose answer names no symbol and no path.
+
+ Every identifier in the assertions below therefore has exactly one possible
+ source: the deterministic append. A mock that echoed part of its prompt
+ would make this test pass on a page the model wrote itself.
+ """
+
+ async def generate(self, *args, **kwargs):
+ response = await super().generate(*args, **kwargs)
+ response.content = (
+ "# Resolution Layer\n\n"
+ "The resolution layer turns cross-file references into edges the "
+ "rest of the pipeline can walk. It sits between parsing and "
+ "persistence and owns nothing else.\n"
+ )
+ return response
+
+
+def _symbol(name: str, *, visibility: str = "public", parent: str = "", line: int = 1) -> dict:
+ return {
+ "name": name,
+ "qualified_name": name,
+ "kind": "function",
+ "signature": f"def {name}()",
+ "docstring": "",
+ "visibility": visibility,
+ "is_async": False,
+ "complexity_estimate": 1,
+ "decorators": [],
+ "parent_name": parent,
+ "start_line": line,
+ "end_line": line + 4,
+ }
+
+
+def _file_context(path: str, symbols: list[dict], *, pagerank: float = 0.1) -> FilePageContext:
+ return FilePageContext(
+ file_path=path,
+ language="python",
+ docstring=None,
+ symbols=symbols,
+ imports=[],
+ exports=[],
+ file_source_snippet="",
+ pagerank_score=pagerank,
+ betweenness_score=0.0,
+ community_id=0,
+ dependents=[],
+ dependencies=[],
+ is_api_contract=False,
+ is_entry_point=False,
+ is_test=False,
+ parse_errors=[],
+ estimated_tokens=10,
+ )
+
+
+def prose_only_generator(sample_config) -> PageGenerator:
+ return PageGenerator(_ProseOnlyProvider(), ContextAssembler(sample_config), sample_config)
+
+
+@dataclass
+class _Fixture:
+ contexts: list[FilePageContext]
+
+
+def resolver_module() -> _Fixture:
+ """Two files whose public symbols are the identifiers a reader would grep."""
+ return _Fixture(
+ contexts=[
+ _file_context(
+ "packages/core/src/repowise/core/ingestion/resolvers/context.py",
+ [
+ _symbol("ResolverContext", line=20),
+ _symbol("resolve_imports", line=60),
+ _symbol("_private_helper", visibility="private", line=90),
+ ],
+ pagerank=0.4,
+ ),
+ _file_context(
+ "packages/core/src/repowise/core/ingestion/resolvers/tsconfig.py",
+ [_symbol("TsconfigResolver", line=12)],
+ pagerank=0.1,
+ ),
+ ]
+ )
+
+
+async def _module_page(gen: PageGenerator, contexts: list[FilePageContext]):
+ import networkx as nx
+
+ return await gen.generate_module_page(
+ "Resolution Layer",
+ "python",
+ contexts,
+ nx.DiGraph(),
+ target_path="packages/core/src/repowise/core/ingestion/resolvers",
+ structural_key="k",
+ )
+
+
+async def test_rendered_page_carries_real_symbol_names_and_paths(
+ prose_only_generator, resolver_module
+):
+ """The identifiers reach the page the model wrote, spelled exactly."""
+ page = await _module_page(prose_only_generator, resolver_module.contexts)
+
+ assert CONCEPT_INDEX_HEADING in page.content
+ assert "| Concept | Symbol | File |" in page.content
+ assert "`ResolverContext`" in page.content
+ assert "`resolve_imports`" in page.content
+ assert "`TsconfigResolver`" in page.content
+ assert "`packages/core/src/repowise/core/ingestion/resolvers/context.py`" in page.content
+ assert "`packages/core/src/repowise/core/ingestion/resolvers/tsconfig.py`" in page.content
+
+
+async def test_concept_column_spells_the_identifier_as_prose(prose_only_generator, resolver_module):
+ """The bridge the table exists to build: prose noun on the left, grep target
+ on the right, both on one line so either wording finds the page."""
+ page = await _module_page(prose_only_generator, resolver_module.contexts)
+
+ assert "| Resolver context | `ResolverContext` |" in page.content
+ assert "| Resolve imports | `resolve_imports` |" in page.content
+
+
+async def test_non_public_symbols_stay_off_the_table(prose_only_generator, resolver_module):
+ page = await _module_page(prose_only_generator, resolver_module.contexts)
+
+ assert "_private_helper" not in page.content
+
+
+async def test_a_module_with_no_public_symbols_renders_no_table(prose_only_generator):
+ """No table at all, not an empty one."""
+ contexts = [
+ _file_context("pkg/a.py", [_symbol("_hidden", visibility="private")]),
+ _file_context("pkg/b.py", []),
+ ]
+
+ page = await _module_page(prose_only_generator, contexts)
+
+ assert CONCEPT_INDEX_HEADING not in page.content
+ assert "| Concept | Symbol | File |" not in page.content
+
+
+async def test_the_table_starts_on_its_own_line(prose_only_generator, resolver_module):
+ """Appending is string concatenation, and a heading glued to the last line
+ of the model's prose renders as body text. Assert the separator that has to
+ be there, not merely the absence of extra ones."""
+ page = await _module_page(prose_only_generator, resolver_module.contexts)
+
+ assert f"\n\n{CONCEPT_INDEX_HEADING}\n" in page.content
+ assert "\n\n\n" not in page.content
+
+
+def test_concept_index_orders_by_the_page_rank_of_the_file():
+ """The reader's first rows are the module's most-depended-on file."""
+ rows, omitted = build_concept_index(
+ [
+ _file_context("pkg/low.py", [_symbol("LowValue")], pagerank=0.01),
+ _file_context("pkg/high.py", [_symbol("HighValue")], pagerank=0.9),
+ ]
+ )
+
+ assert [r["symbol"] for r in rows] == ["HighValue", "LowValue"]
+ assert omitted == 0
+
+
+def test_concept_index_caps_its_length_and_says_how_many_it_dropped():
+ """A module with hundreds of exports would otherwise bury the page it is
+ attached to. The count is reported so a truncated table cannot read as a
+ complete public surface."""
+ symbols = [_symbol(f"symbol_number_{i}", line=i) for i in range(80)]
+ rows, omitted = build_concept_index([_file_context("pkg/wide.py", symbols)])
+
+ assert len(rows) + omitted == 80
+ assert omitted > 0
+
+
+def test_duplicate_identifiers_across_files_each_keep_their_own_row():
+ """Two files can export the same name; collapsing them would send a reader
+ to one arbitrary file."""
+ rows, _ = build_concept_index(
+ [
+ _file_context("pkg/a.py", [_symbol("handler")], pagerank=0.5),
+ _file_context("pkg/b.py", [_symbol("handler")], pagerank=0.4),
+ ]
+ )
+
+ assert [(r["symbol"], r["file"]) for r in rows] == [
+ ("handler", "pkg/a.py"),
+ ("handler", "pkg/b.py"),
+ ]
+
+
+ ("identifier", "concept"),
+ [
+ ("ResolverContext", "Resolver context"),
+ ("resolve_imports", "Resolve imports"),
+ ("EMBED_BATCH_MAX_ITEMS", "Embed batch max items"),
+ ("HTTPAdapter", "HTTP adapter"),
+ ("parse", "Parse"),
+ ],
+)
+def test_concept_wording_is_derived_from_the_identifier(identifier, concept):
+ """Derived, never written: a model-written column could describe a symbol
+ that is not there, which is the failure this table exists to rule out."""
+ rows, _ = build_concept_index([_file_context("pkg/a.py", [_symbol(identifier)])])
+
+ assert rows[0]["concept"] == concept