Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(generation): package pages and a computed Public API (#2712)
Swati Ahuja547df91a7e7b
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.pyindex 8b7bd803a..8bcc115e6 100644--- a/packages/core/src/repowise/core/generation/context/assembler.py+++ b/packages/core/src/repowise/core/generation/context/assembler.py@@ -56,6 +56,8 @@ log = structlog.get_logger(__name__)# Maximum imports to include before truncating_MAX_IMPORTS = 30+# Tokens of code excerpts a module page prompt carries; the Public API claims them first.+_MODULE_EXCERPT_BUDGET = 10_000# Maximum top-files to include in repo overview_MAX_TOP_FILES = 20@@ -503,8 +505,13 @@ class ContextAssembler:is_rollup: bool = False,child_pages: list[dict] | None = None,packages: list[dict] | None = None,+ public_api: list[dict] | None = None,) -> ModulePageContext:- """Assemble context for the module_page template."""+ """Assemble context for the module_page template.++ *public_api* (see :func:`~.public_api.compute_public_api`) has first+ claim on the excerpt budget; entries past it keep only their name.+ """total_symbols = sum(len(fc.symbols) for fc in file_contexts)public_symbols = sum(sum(1 for s in fc.symbols if s.get("visibility") == "public") for fc in file_contexts@@ -646,6 +653,7 @@ class ContextAssembler:is_rollup=is_rollup,child_pages=child_pages or [],packages=packages or [],+ public_api=self._excerpt_public_api(public_api or []),hotspot_count=hotspot_count,stable_count=stable_count,single_owner_files=single_owner_files,@@ -654,6 +662,12 @@ class ContextAssembler:most_fixed_file=most_fixed_file,)+ def _excerpt_public_api(self, api: list[dict]) -> list[dict]:+ """Every entry, excerpted (signature + doc line) in order while the budget lasts."""+ cost = lambda e: self._estimate_tokens(f"{e['signature']} {e['doc']}") # noqa: E731+ kept, _ = items_within_budget(api, 0, _MODULE_EXCERPT_BUDGET, cost)+ return kept + [{**e, "signature": "", "doc": ""} for e in api[len(kept) :]]+def _package_boundaries(self, known_paths: set[str]) -> set[str]:"""Package roots for this repo, resolved once.diff --git a/packages/core/src/repowise/core/generation/context/contexts.py b/packages/core/src/repowise/core/generation/context/contexts.pyindex 1554a3a64..00af364a1 100644--- a/packages/core/src/repowise/core/generation/context/contexts.py+++ b/packages/core/src/repowise/core/generation/context/contexts.py@@ -122,6 +122,9 @@ class ModulePageContext:child_pages: list[dict] = field(default_factory=list)# Sibling packages a package roll-up covers: [{"path", "files"}].packages: list[dict] = field(default_factory=list)+ # What the page's packages publish, computed from manifests and re-exports:+ # [{"name", "kind", "file", "signature", "doc", "alias_of"}]; past the budget, names only.+ public_api: list[dict] = field(default_factory=list)# Git-derived subsystem health, aggregated over the page's member files.# All degrade to zero/empty when no git metadata is available, so the# template renders nothing rather than a wrong number.diff --git a/packages/core/src/repowise/core/generation/context/public_api.py b/packages/core/src/repowise/core/generation/context/public_api.pynew file mode 100644index 000000000..6c310010b--- /dev/null+++ b/packages/core/src/repowise/core/generation/context/public_api.py@@ -0,0 +1,187 @@+"""The Public API of a page's files, computed from manifests and re-exports.++A package's public surface is what a consumer can import from it: whatever its+manifest names as the start (``package.json`` ``bin``/``main``/``exports["."]``,+``[project.scripts]``, a distribution's ``__init__.py``; stamped at ingestion as+``FileInfo.is_manifest_entry``) declares or re-exports through barrels. It is+read off the parsed imports, never guessed by a model, so a class that nothing+in the repo imports still appears when the package's front door publishes it.+"""++from __future__ import annotations++from collections.abc import Iterable, Mapping+from pathlib import Path, PurePosixPath+from typing import Any++from repowise.core.analysis.dead_code.file_reachability import BARREL_FILENAMES+from repowise.core.ingestion.package_roots import module_for+from repowise.core.workspace.code_api import dunder_all++# A Rust ``impl`` block is not a name anyone imports.+_UNPUBLISHED_KINDS = frozenset({"impl"})+# (public name, Symbol or None for a namespace export, declaring file)+_Published = list[tuple[str, Any, str]]+++def api_roots(+ material: Iterable[str], parsed: Mapping[str, Any], package_roots: set[str]+) -> list[str]:+ """The files a page's public API is read from, per package it covers.++ Per package (or per page when no package holds the files): its+ manifest-declared entries, else its shallowest barrels.+ """+ by_owner: dict[str, list[str]] = {}+ for path in sorted(set(material)):+ if path in parsed:+ owner = module_for(path, package_roots)+ by_owner.setdefault(owner if owner in package_roots else "", []).append(path)+ roots: list[str] = []+ for _owner, paths in sorted(by_owner.items()):+ declared = [p for p in paths if getattr(parsed[p].file_info, "is_manifest_entry", False)]+ if not declared:+ barrels = [p for p in paths if PurePosixPath(p).name in BARREL_FILENAMES]+ depth = min((p.count("/") for p in barrels), default=0)+ declared = [p for p in barrels if p.count("/") == depth]+ roots.extend(declared)+ return roots+++def _forwards(imp: Any, pf: Any) -> bool:+ """Whether *imp* publishes what it imports (a re-export), not just uses it."""+ if imp.is_reexport or imp.raw_statement.lstrip().startswith("export"):+ return True+ # A Python package's ``__init__`` imports are its published namespace.+ return pf.file_info.path.rsplit("/", 1)[-1] == "__init__.py"+++def _declared(pf: Any) -> dict[str, Any]:+ """The public top-level symbols *pf* declares, by name."""+ # Declarations sort first so an overload's implementation wins the name.+ return {+ s.name: s+ for s in sorted(pf.symbols, key=lambda s: not s.is_declaration)+ if s.parent_name is None+ and s.visibility == "public"+ and s.kind not in _UNPUBLISHED_KINDS+ and s.name != "__all__"+ }+++def _entry(name: str, sym: Any, path: str, alias_of: str) -> dict:+ """One Public API row; a second name for a symbol carries no excerpt."""+ if sym is None: # a namespace export+ return {+ "name": name,+ "kind": "module",+ "file": path,+ "signature": "",+ "doc": "",+ "alias_of": alias_of,+ }+ doc = (sym.docstring or "").strip().splitlines()+ return {+ "name": name,+ "kind": sym.kind,+ "file": path,+ "signature": "" if alias_of else " ".join((sym.signature or "").split()),+ "doc": "" if alias_of or not doc else doc[0].strip(),+ "alias_of": alias_of,+ }+++class _Resolver:+ def __init__(self, parsed: Mapping[str, Any]) -> None:+ self._parsed = parsed+ self._memo: dict[str, _Published] = {}+ self._visiting: set[str] = set()+ # Set when a cycle cut a walk short; such partial results are not memoized.+ self._cut = False++ def published(self, path: str) -> _Published:+ """Every public name *path* binds: its own declarations, then its re-exports.++ What a named import can reach; :meth:`exported` narrows it to what+ the module publishes.+ """+ if path in self._memo:+ return self._memo[path]+ pf = self._parsed.get(path)+ if pf is None:+ return []+ if path in self._visiting:+ self._cut = True+ return []+ self._visiting.add(path)+ outer_cut, self._cut = self._cut, False+ own = _declared(pf)+ out: _Published = [(name, sym, path) for name, sym in own.items()]+ # ``export { local as alias }`` publishes a declared symbol under a new name.+ out += [+ (alias, own[local], path) for alias, local in pf.export_aliases.items() if local in own+ ]+ for imp in pf.imports:+ if _forwards(imp, pf) and imp.resolved_file in self._parsed:+ out += self._forwarded(imp)+ self._visiting.discard(path)+ if not self._cut:+ self._memo[path] = out+ self._cut = self._cut or outer_cut+ return out++ def exported(self, path: str) -> _Published:+ """What *path* publishes: a Python ``__all__`` when it has one, else no ``_`` names."""+ out = self.published(path)+ pf = self._parsed.get(path)+ if pf is None or pf.file_info.language != "python":+ return out+ listed = dunder_all(Path(pf.file_info.abs_path)) if pf.file_info.abs_path else None+ if listed is None:+ return [r for r in out if not r[0].startswith("_")]+ return [r for r in out if r[0] in listed]++ def _forwarded(self, imp: Any) -> _Published:+ if "*" in imp.imported_names:+ # ``export * as ns`` publishes the module itself under ``ns``.+ ns = next((b.exported_name for b in imp.bindings if b.local_name == "*"), None)+ if ns:+ return [(ns, None, imp.resolved_file)]+ return list(self.exported(imp.resolved_file))+ out: _Published = []+ for b in imp.bindings:+ if b.local_name == "*" or b.is_module_alias:+ continue+ wanted = b.exported_name or b.local_name+ hit = next(+ (r for r in self.published(b.source_file or imp.resolved_file) if r[0] == wanted),+ None,+ )+ if hit is not None:+ out.append((b.local_name, hit[1], hit[2]))+ return out+++def compute_public_api(+ material: Iterable[str], parsed: Mapping[str, Any], package_roots: set[str]+) -> list[dict]:+ """``[{name, kind, file, signature, doc}]`` a page's files publish, entry order.++ A symbol published under a second name (``export { A as B }``) is listed+ again with ``alias_of`` and no excerpt. Ceiling: ``export { default as X }``,+ a computed ``__all__`` and an ``import`` followed by a bare ``export { X }``+ are not followed.+ """+ resolver = _Resolver(parsed)+ first_name: dict[tuple[str, str], str] = {} # (file, symbol) -> first public name+ seen: set[tuple[str, str, str]] = set()+ api: list[dict] = []+ for root in api_roots(material, parsed, package_roots):+ for name, sym, path in resolver.exported(root):+ key = (path, sym.name if sym is not None else "")+ if (name, *key) in seen:+ continue+ seen.add((name, *key))+ first = first_name.setdefault(key, name)+ api.append(_entry(name, sym, path, "" if first == name else first))+ return apidiff --git a/packages/core/src/repowise/core/generation/page_generator/levels.py b/packages/core/src/repowise/core/generation/page_generator/levels.pyindex 39aa68f77..ce4d9488f 100644--- a/packages/core/src/repowise/core/generation/page_generator/levels.py+++ b/packages/core/src/repowise/core/generation/page_generator/levels.py@@ -15,9 +15,11 @@ from typing import TYPE_CHECKING, Anyimport structlogfrom repowise.core.ids import is_external+from repowise.core.ingestion.package_roots import package_roots_from_pathsfrom .. import onboarding as _onboardingfrom ..concept_tree.grouping import package_file_counts+from ..context.public_api import compute_public_apifrom ..context_assembler import FilePageContextfrom ..models import compute_page_idfrom .helpers import _is_infra_file, decisions_for_files, rank_decisions@@ -233,21 +235,25 @@ def build_level3_coros(run: _GenerationRun) -> list[tuple[str, Any]]:def _rollup_child_pages(rollup: Any, groups: list[Any]) -> list[dict]:- """The pages a rollup links down to: its *immediate* children only.-- A page is an immediate child when the rollup's key is exactly the parent- directory of the page's key. Immediate rather than recursive so a nested- overview links to the next level down (a sub-overview or a leaf), not to- every descendant leaf — otherwise ``a/b`` and ``a/b/c`` would both list the- same leaves under ``a/b/c``. A sub-rollup is a legitimate child and is kept;- the rollup itself is excluded. Titles are read after naming, so they match- what the tree shows.+ """The pages a rollup links down to: those it is the nearest chapter of.++ The same rule ``assign_page_tree`` nests by, so the links match the tree:+ a nested overview links to the next level down (a sub-overview or a leaf),+ not to every descendant leaf, and a leaf several directories below a+ package chapter with no chapter in between is still linked. The rollup+ itself is excluded. Titles are read after naming, so they match what the+ tree shows."""- children = [- g- for g in groups- if g.key != rollup.key and "/" in g.key and g.key.rsplit("/", 1)[0] == rollup.key- ]+ chapters = {g.key for g in groups if getattr(g, "is_rollup", False)}++ def nearest_chapter(key: str) -> str | None:+ while "/" in key:+ key = key.rsplit("/", 1)[0]+ if key in chapters:+ return key+ return None++ children = [g for g in groups if g.key != rollup.key and nearest_chapter(g.key) == rollup.key]children.sort(key=lambda g: g.key)return [{"title": g.display, "path": g.key} for g in children]@@ -256,6 +262,11 @@ def build_level4_coros(run: _GenerationRun) -> list[tuple[str, Any]]:"""Level 4 (module_page), allow-set filtered."""gen = run.gencoros: list[tuple[str, Any]] = []+ # The whole indexed set, not this run's slice: re-exports reach unchanged files.+ parsed_by_path = getattr(run.graph_builder, "_parsed_files", None)+ if not isinstance(parsed_by_path, dict) or not parsed_by_path:+ parsed_by_path = {p.file_info.path: p for p in run.parsed_files}+ package_roots = package_roots_from_paths(set(parsed_by_path))for mg in run.sel_module_groups:# Read from the wider set: a chapter's prose is about its whole# subsystem, while ``file_paths`` is the narrower, disjoint claim on who@@ -319,6 +330,7 @@ def build_level4_coros(run: _GenerationRun) -> list[tuple[str, Any]]:{"path": path, "files": count}for path, count in package_file_counts(mg.file_paths, mg.packages)],+ public_api=compute_public_api(material, parsed_by_path, package_roots),),))diff --git a/packages/core/src/repowise/core/generation/page_generator/pertype.py b/packages/core/src/repowise/core/generation/page_generator/pertype.pyindex 212ee8865..27b892a4a 100644--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py@@ -210,6 +210,7 @@ class PerTypeGenerationMixin:child_pages: list[dict] | None = None,owns_files: bool = True,packages: list[dict] | None = None,+ public_api: list[dict] | None = None,) -> GeneratedPage:ctx = self._assembler.assemble_module_page(title,@@ -227,6 +228,7 @@ class PerTypeGenerationMixin:is_rollup=is_rollup,child_pages=child_pages,packages=packages,+ public_api=public_api,)module_git_summary = Noneif git_meta_map:diff --git a/packages/core/src/repowise/core/generation/selection/selector.py b/packages/core/src/repowise/core/generation/selection/selector.pyindex fefae1b0c..d58bd50a7 100644--- a/packages/core/src/repowise/core/generation/selection/selector.py+++ b/packages/core/src/repowise/core/generation/selection/selector.py@@ -9,6 +9,7 @@ emitted.from __future__ import annotationsfrom collections import Counter+from collections.abc import Iterablefrom dataclasses import dataclass, field, replacefrom pathlib import Pathfrom typing import Any@@ -538,7 +539,7 @@ def _build_module_groups(inputs: SelectionInputs) -> ConceptCandidates:# Which directories head a subsystem. Computed before the groups are built# so a directory that is both a chapter and a leaf becomes one page rather# than colliding with itself on ``module_page:{dir}``.- chapters = _chapter_members(groups, files)+ chapters = _chapter_members(groups, files, package_roots)scored: list[tuple[float, ModuleGroup]] = []for group, title in zip(groups, titles, strict=True):@@ -608,7 +609,9 @@ def _chapter_scope(parent: str, *, owns: bool) -> str:return f"{lead}; the detail lives on those child pages, not here."-def _chapter_members(groups: list[ConceptGroup], files: list[str]) -> dict[str, list[str]]:+def _chapter_members(+ groups: list[ConceptGroup], files: list[str], package_roots: Iterable[str] = ()+) -> dict[str, list[str]]:"""Directories that head a subsystem → every production file beneath them.The partition splits a large subsystem into path-local leaves, so a@@ -637,6 +640,12 @@ def _chapter_members(groups: list[ConceptGroup], files: list[str]) -> dict[str,loose files and heads its children; see ``ModuleGroup.context_paths`` for howownership stays disjoint while the prose still covers the subsystem.+ A package root whose files span two or more groups is always a chapter,+ whatever its depth or size: a package is what a consumer installs, so it+ gets one page covering all of it (and its Public API) even when that is+ most of the repository. A package in one group already has that page, and+ a roll-up of thin packages is their shared page.+All paths here are POSIX-normalised upstream (the grouper lowercasesseparators), so the ``/`` splits below are safe."""@@ -655,6 +664,11 @@ def _chapter_members(groups: list[ConceptGroup], files: list[str]) -> dict[str,if not members or (total and len(members) > _ROLLUP_MAX_MEMBER_FRACTION * total):continueout[parent] = members+ for root in sorted(package_roots):+ members = sorted(f for f in files if f.startswith(root + "/"))+ spanned = sum(1 for g in groups if any(m.startswith(root + "/") for m in g.members))+ if spanned > 1:+ out[root] = membersreturn outdiff --git a/packages/core/src/repowise/core/generation/templates/module_page.j2 b/packages/core/src/repowise/core/generation/templates/module_page.j2index bd2260951..ba1198e65 100644--- a/packages/core/src/repowise/core/generation/templates/module_page.j2+++ b/packages/core/src/repowise/core/generation/templates/module_page.j2@@ -31,6 +31,14 @@ Name each in backticks by its path so it resolves to a wiki link; explain in one{% endfor %}{% endif %}+{% if ctx.public_api %}+### Public API (computed from the package manifests and re-exports; what a consumer imports)+Name the central ones in backticks exactly as written and say what each is for; do not invent members beyond these.+{% for e in ctx.public_api %}+- `{{ e.name }}` ({{ e.kind }}, `{{ e.file }}`){% if e.alias_of %}, another name for `{{ e.alias_of }}`{% endif %}{% if e.signature %}: `` {{ e.signature }} ``{% endif %}{% if e.doc %}: {{ e.doc }}{% endif %}+{% endfor %}+{% endif %}+{% if ctx.entry_points %}### Entry points{% for ep in ctx.entry_points %}diff --git a/packages/core/src/repowise/core/workspace/code_api.py b/packages/core/src/repowise/core/workspace/code_api.pyindex a3b6ad2c4..024f7430b 100644--- a/packages/core/src/repowise/core/workspace/code_api.py+++ b/packages/core/src/repowise/core/workspace/code_api.py@@ -200,36 +200,42 @@ def _pypi_package_dirs(data: dict[str, Any]) -> list[str]:return [d.strip("/") for d in dirs if isinstance(d, str) and d.strip("/")]-def _dunder_all(repo_path: Path, entry_files: frozenset[str]) -> frozenset[str]:- """Names an entry ``__init__.py`` re-exports via ``__all__``.+def dunder_all(path: Path) -> frozenset[str] | None:+ """The string literals a module's ``__all__`` lists; None when it has none.- Python's entry file usually *declares* nothing — it is a wall of- ``from .x import Y`` — so without this a distribution's surface reads as- empty. Only plain string literals count; a computed ``__all__`` is refused+ Only plain string literals count; a computed ``__all__`` is refusedwhole rather than half-read, per the same rule the signature mapper follows."""import ast- names: set[str] = set()- for rel in entry_files:- path = repo_path / rel- try:- tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))- except (OSError, SyntaxError, ValueError):+ try:+ tree = ast.parse(path.read_text(encoding="utf-8", errors="replace"))+ except (OSError, SyntaxError, ValueError):+ return None+ names: set[str] | None = None+ for node in tree.body:+ if not isinstance(node, ast.Assign) or not any(+ isinstance(t, ast.Name) and t.id == "__all__" for t in node.targets+ ):continue- for node in tree.body:- if not isinstance(node, ast.Assign) or not any(- isinstance(t, ast.Name) and t.id == "__all__" for t in node.targets- ):- continue- if not isinstance(node.value, ast.List | ast.Tuple):- continue- names.update(- el.value- for el in node.value.elts- if isinstance(el, ast.Constant) and isinstance(el.value, str)- )- return frozenset(names)+ if not isinstance(node.value, ast.List | ast.Tuple):+ continue+ names = (names or set()) | {+ el.value+ for el in node.value.elts+ if isinstance(el, ast.Constant) and isinstance(el.value, str)+ }+ return None if names is None else frozenset(names)+++def _dunder_all(repo_path: Path, entry_files: frozenset[str]) -> frozenset[str]:+ """Names an entry ``__init__.py`` re-exports via ``__all__``.++ Python's entry file usually *declares* nothing (it is a wall of+ ``from .x import Y``), so without this a distribution's surface reads as+ empty.+ """+ return frozenset(name for rel in entry_files for name in dunder_all(repo_path / rel) or ())def _cargo(text: str, root: str) -> tuple[str, frozenset[str]] | None:diff --git a/tests/unit/generation/test_package_public_api.py b/tests/unit/generation/test_package_public_api.pynew file mode 100644index 000000000..67b22d6cf--- /dev/null+++ b/tests/unit/generation/test_package_public_api.py@@ -0,0 +1,240 @@+"""Package pages and their computed Public API.++A package root always heads a page covering the whole package, and that page's+prompt carries what the package publishes: read from the manifest's entries+and the re-exports behind them, never guessed. A class nothing in the repo+imports is still public when the package's front door re-exports it.+"""++from __future__ import annotations++import json+from pathlib import Path+from types import SimpleNamespace++import networkx as nx++from repowise.core.generation.context.public_api import (+ _Resolver,+ api_roots,+ compute_public_api,+)+from repowise.core.generation.context_assembler import ContextAssembler, FilePageContext+from repowise.core.generation.page_generator import PageGenerator+from repowise.core.generation.page_generator.levels import _rollup_child_pages+from repowise.core.generation.selection.selector import _build_module_groups+from repowise.core.ingestion.graph import GraphBuilder+from repowise.core.ingestion.package_roots import package_roots_from_paths+from repowise.core.ingestion.parser import ASTParser+from repowise.core.ingestion.traverser import FileTraverser+from repowise.core.providers.llm.mock import MockProvider+from tests.unit.generation.test_concept_package_walls import _selection_inputs+from tests.unit.generation.test_selection_contract import FakeFileInfo, FakeParsedFile+++def _index(repo: Path, files: dict[str, str]) -> dict:+ for rel, body in files.items():+ (repo / rel).parent.mkdir(parents=True, exist_ok=True)+ (repo / rel).write_text(body, encoding="utf-8")+ parser = ASTParser()+ builder = GraphBuilder(repo)+ for fi in FileTraverser(repo).traverse():+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))+ builder.build()+ return builder._parsed_files+++_SDK = {+ "packages/sdk/package.json": json.dumps({"name": "sdk", "main": "./dist/index.js"}),+ "packages/sdk/src/index.ts": (+ "export * from './client';\nexport { Tool as SdkTool } from './tools';\n"+ "export { Client as LegacyClient } from './client';\n"+ "export * as tools from './tools';\n"+ ),+ "packages/sdk/src/client.ts": (+ "/** Talks to the service. */\nexport class Client {\n send(): void {}\n}\n"+ "function helper(): number { return 1; }\n"+ ),+ "packages/sdk/src/tools.ts": "export class Tool {}\nexport class Hidden {}\n",+ "packages/sdk/src/internal.ts": "export function notPublished(): void {}\n",+ "packages/py/pyproject.toml": '[project]\nname = "pysdk"\n',+ "packages/py/pysdk/__init__.py": "from ._client import Client\nfrom .models import *\n",+ "packages/py/pysdk/_client.py": 'class Client:\n """Python client."""\n',+ "packages/py/pysdk/models.py": "class Model:\n pass\n\ndef _private():\n pass\n",+}+++def _api(parsed: dict, prefix: str) -> list[dict]:+ material = [p for p in parsed if p.startswith(prefix)]+ return compute_public_api(material, parsed, package_roots_from_paths(set(parsed)))+++def test_manifest_entries_are_the_roots(tmp_path):+ parsed = _index(tmp_path, _SDK)+ roots = api_roots(list(parsed), parsed, package_roots_from_paths(set(parsed)))+ assert roots == ["packages/py/pysdk/__init__.py", "packages/sdk/src/index.ts"]+++def test_reexported_class_with_no_importers_is_public(tmp_path):+ parsed = _index(tmp_path, _SDK)+ ts = {(e["name"], e["file"]) for e in _api(parsed, "packages/sdk/")}+ # ``Client`` has in-degree 0 in the repo; the barrel alone publishes it.+ assert ("Client", "packages/sdk/src/client.ts") in ts+ assert ("SdkTool", "packages/sdk/src/tools.ts") in ts+ names = {name for name, _ in ts}+ assert not names & {"Hidden", "notPublished", "helper", "send", "Tool"}+ by_name = {e["name"]: e for e in _api(parsed, "packages/sdk/")}+ # A second name for one symbol is listed, pointing at the first, with no excerpt.+ assert by_name["LegacyClient"]["alias_of"] == "Client"+ assert not by_name["LegacyClient"]["signature"]+ # ``export * as ns`` publishes the module itself, not its members.+ assert (by_name["tools"]["kind"], by_name["tools"]["file"]) == (+ "module",+ "packages/sdk/src/tools.ts",+ )++ py = {(e["name"], e["file"]) for e in _api(parsed, "packages/py/")}+ assert py == {+ ("Client", "packages/py/pysdk/_client.py"),+ ("Model", "packages/py/pysdk/models.py"),+ }+++def test_barrel_is_the_root_when_no_manifest_names_one(tmp_path):+ parsed = _index(+ tmp_path,+ {+ "lib/__init__.py": "from .core import Engine\n",+ "lib/core.py": "class Engine:\n pass\n",+ "lib/sub/__init__.py": "from .x import Deep\n",+ "lib/sub/x.py": "class Deep:\n pass\n",+ },+ )+ assert [e["name"] for e in compute_public_api(list(parsed), parsed, set())] == ["Engine"]+++class _RecordingProvider(MockProvider):+ async def generate(self, *args, **kwargs):+ response = await super().generate(*args, **kwargs)+ response.content = "# SDK\n\nThe SDK client.\n"+ return response+++def _context(path: str) -> FilePageContext:+ return FilePageContext(+ file_path=path,+ language="typescript",+ docstring=None,+ symbols=[],+ imports=[],+ exports=[],+ pagerank_score=0.1,+ 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 test_public_api_reaches_the_prompt_excerpts(tmp_path, sample_config):+ parsed = _index(tmp_path, _SDK)+ api = _api(parsed, "packages/sdk/")+ provider = _RecordingProvider()+ gen = PageGenerator(provider, ContextAssembler(sample_config), sample_config)+ await gen.generate_module_page(+ "SDK",+ "typescript",+ [_context("packages/sdk/src/index.ts")],+ nx.DiGraph(),+ target_path="packages/sdk",+ public_api=api,+ )+ prompt = provider._calls[-1]["user_prompt"]+ assert "### Public API" in prompt+ assert "- `Client` (class, `packages/sdk/src/client.ts`): `` class Client" in prompt+ assert "Talks to the service." in prompt+++def test_public_api_past_the_budget_keeps_every_name(sample_config):+ api = [+ {"name": f"f{i}", "kind": "function", "file": "a.ts", "signature": "x" * 400, "doc": ""}+ for i in range(200)+ ]+ ctx = ContextAssembler(sample_config).assemble_module_page(+ "A", "typescript", [_context("a.ts")], nx.DiGraph(), public_api=api+ )+ assert [e["name"] for e in ctx.public_api] == [e["name"] for e in api]+ assert ctx.public_api[0]["signature"] and not ctx.public_api[-1]["signature"]+++def test_a_package_split_across_groups_gets_its_own_whole_package_page():+ """``packages/kernel`` splits into leaves one level below its root, so no+ chapter would sit at the root itself; being a package puts one there."""+ inputs = _selection_inputs()+ groups = [mg for _, mg in _build_module_groups(inputs).scored]+ kernel = [mg for mg in groups if mg.key == "packages/kernel"]+ assert len(kernel) == 1 and kernel[0].is_rollup+ files = {p.file_info.path for p in inputs.parsed_files}+ assert set(kernel[0].context_paths) == {+ f for f in files if f.startswith("packages/kernel/") and f.endswith(".ts")+ }+++def test_a_package_page_is_kept_even_when_it_is_most_of_the_repo():+ files = [f"packages/core/src/{d}/f{i}.py" for d in "abcdef" for i in range(10)]+ parsed = [FakeParsedFile(file_info=FakeFileInfo(path=p)) for p in files]+ parsed.append(FakeParsedFile(file_info=FakeFileInfo(path="packages/core/pyproject.toml")))+ inputs = _selection_inputs()+ inputs.parsed_files = parsed+ keys = {mg.key for _, mg in _build_module_groups(inputs).scored}+ assert "packages/core" in keys+++def test_rollup_links_to_leaves_below_it_with_no_chapter_between():+ g = lambda key, rollup=False: SimpleNamespace(key=key, display=key, is_rollup=rollup) # noqa: E731+ pkg, sub = g("pkgs/a", True), g("pkgs/a/src/x/deep", True)+ groups = [pkg, g("pkgs/a/src/io"), g("pkgs/a/src/model"), sub, g("pkgs/a/src/x/deep/y")]+ assert [c["path"] for c in _rollup_child_pages(pkg, groups)] == [+ "pkgs/a/src/io",+ "pkgs/a/src/model",+ "pkgs/a/src/x/deep",+ ]+ assert [c["path"] for c in _rollup_child_pages(sub, groups)] == ["pkgs/a/src/x/deep/y"]+++def test_python_dunder_all_decides_what_is_published(tmp_path):+ parsed = _index(+ tmp_path,+ {+ "pyproject.toml": '[project]\nname = "lib"\n',+ "lib/__init__.py": (+ "from .__version__ import __version__\nfrom ._models import *\n"+ "from ._util import helper\n\n__all__ = ['__version__', 'Request', 'helper']\n"+ ),+ "lib/__version__.py": '__version__ = "1.0"\n',+ "lib/_models.py": "__all__ = ['Request']\n\nclass Request:\n pass\n\nclass Unlisted:\n pass\n",+ "lib/_util.py": "__all__ = []\n\ndef helper():\n pass\n",+ },+ )+ # A named import reaches past the source's ``__all__``; a wildcard does not.+ names = [e["name"] for e in compute_public_api(list(parsed), parsed, set())]+ assert sorted(names) == ["Request", "__version__", "helper"]+++def test_barrels_that_re_export_each_other_publish_everything_from_every_root(tmp_path):+ parsed = _index(+ tmp_path,+ {+ "one/index.ts": "export * from '../two';\nexport class One {}\n",+ "two/index.ts": "export * from '../one';\nexport class Two {}\n",+ },+ )+ resolver = _Resolver(parsed)+ for root in ("one/index.ts", "two/index.ts"):+ # The cycle cut short while walking the first root must not stick to the second.+ assert sorted(name for name, _, _ in resolver.exported(root)) == ["One", "Two"]