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.

fix(wiki): template pages only for real API contracts, never for tests (#2702)

Swati Ahuja34d26015a11d
diff --git a/packages/core/src/repowise/core/generation/api_contract_detector.py b/packages/core/src/repowise/core/generation/api_contract_detector.py
index 733caf0d2..219cff2f0 100644
--- a/packages/core/src/repowise/core/generation/api_contract_detector.py
+++ b/packages/core/src/repowise/core/generation/api_contract_detector.py
@@ -1,13 +1,13 @@
"""Cross-language API-contract detection for ParsedFile objects.
-Traverser sets ``FileInfo.is_api_contract = True`` for OpenAPI/Swagger/proto/
-GraphQL files purely from filename/extension. That misses framework-defined
+Traverser sets ``FileInfo.is_api_contract = True`` for non-test OpenAPI/Swagger/
+proto/GraphQL spec files from extension and filename. That misses framework-defined
HTTP surfaces (FastAPI routers, ASP.NET controllers, etc.) where the contract
is expressed in code, not in a schema file.
This module runs after parsing and flips ``is_api_contract`` for those code
-files based on small per-language heuristics that read only the parsed
-``Symbol``/``Import`` data — no source re-read, no LLM call.
+non-test files that declare at least one operation, using small per-language
+heuristics that read only the parsed ``Symbol``/``Import``/heritage data — no source re-read, no LLM call.
Adding a new framework: write a ``Detector`` callable and register it in
``_DETECTORS`` keyed by ``LanguageTag``. Keep the heuristic conservative —
@@ -24,6 +24,14 @@ from repowise.core.ingestion.models import ParsedFile
Detector = Callable[[ParsedFile], bool]
+_HTTP_VERBS = frozenset({"get", "post", "put", "patch", "delete", "head", "options", "api_route"})
+
+
+def _decorator_name(dec: str) -> str:
+ """``@router.get('/x')`` -> ``router.get``; ``[HttpGet("x")]`` -> ``HttpGet``."""
+ return dec.lstrip("@[").split("(", 1)[0].rstrip("]")
+
+
def _python_is_fastapi_router(parsed: ParsedFile) -> bool:
# The parser sometimes resolves "from fastapi import APIRouter" with
# module_path = "fastapi" and imported_names = ["APIRouter"], and
@@ -35,38 +43,43 @@ def _python_is_fastapi_router(parsed: ParsedFile) -> bool:
)
if not imports_fastapi:
return False
- fastapi_names = {"APIRouter", "FastAPI"}
- for imp in parsed.imports:
- if set(imp.imported_names) & fastapi_names:
- return True
- # Decorator form: any symbol decorated with @router.get / @app.post / etc.
+ # The contract is the operations: a file that only builds the app or mounts
+ # routers declares none (``@router.get`` / ``@app.post`` and friends).
for sym in parsed.symbols:
for dec in sym.decorators:
- head = dec.lstrip("@").split("(", 1)[0]
- if "." in head and head.rsplit(".", 1)[1] in {
- "get", "post", "put", "patch", "delete", "head", "options",
- }:
+ head = _decorator_name(dec)
+ if "." in head and head.rsplit(".", 1)[1] in _HTTP_VERBS:
return True
return False
+# ApiController is also the classic Web API 2 base class, not only the attribute.
_ASPNET_CONTROLLER_BASES = frozenset({"ControllerBase", "Controller", "ApiController"})
-_ASPNET_ATTRIBUTES = frozenset({"ApiController", "Route", "HttpGet", "HttpPost", "HttpPut", "HttpDelete", "HttpPatch"})
+_ASPNET_CLASS_ATTRIBUTES = frozenset({"ApiController", "Route"})
+_ASPNET_ACTION_ATTRIBUTES = frozenset(
+ {"HttpGet", "HttpPost", "HttpPut", "HttpDelete", "HttpPatch", "HttpHead", "HttpOptions"}
+)
def _csharp_is_aspnet_controller(parsed: ParsedFile) -> bool:
- for sym in parsed.symbols:
- if sym.kind != "class":
- continue
- # Inheritance encoded in signature as ": Base" / ", Interface" in C#.
- sig = sym.signature or ""
- if any(base in sig for base in _ASPNET_CONTROLLER_BASES):
- return True
- for dec in sym.decorators:
- attr = dec.lstrip("@").lstrip("[").split("(", 1)[0].rstrip("]")
- if attr in _ASPNET_ATTRIBUTES:
- return True
- return False
+ controllers = {
+ h.child_name for h in parsed.heritage if h.parent_name in _ASPNET_CONTROLLER_BASES
+ }
+ controllers.update(
+ sym.name
+ for sym in parsed.symbols
+ if sym.kind == "class"
+ and any(_decorator_name(d) in _ASPNET_CLASS_ATTRIBUTES for d in sym.decorators)
+ )
+ # An operation: a verb-attributed method, or a public action on a controller.
+ return any(
+ sym.kind == "method"
+ and (
+ any(_decorator_name(d) in _ASPNET_ACTION_ATTRIBUTES for d in sym.decorators)
+ or (sym.visibility == "public" and sym.parent_name in controllers)
+ )
+ for sym in parsed.symbols
+ )
_DETECTORS: dict[str, Detector] = {
@@ -83,7 +96,8 @@ def detect_code_api_contracts(parsed_files: list[ParsedFile]) -> int:
"""
flipped = 0
for pf in parsed_files:
- if pf.file_info.is_api_contract:
+ # A test that calls an API is not its contract.
+ if pf.file_info.is_api_contract or pf.file_info.is_test:
continue
detector = _DETECTORS.get(pf.file_info.language)
if detector is None:
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py
index 4c3323b11..8b7bd803a 100644
--- a/packages/core/src/repowise/core/generation/context/assembler.py
+++ b/packages/core/src/repowise/core/generation/context/assembler.py
@@ -452,11 +452,8 @@ class ContextAssembler:
) -> SymbolSpotlightContext:
"""Assemble context for the symbol_spotlight template."""
path = parsed.file_info.path
- # Callers = files that import the containing file (in-edges)
- if path in graph:
- callers = [e for e in graph.predecessors(path) if not is_external(e)]
- else:
- callers = []
+ # The file page's own importer list, so the two pages report one count.
+ callers = file_dependency_neighbors(graph, path, incoming=True)
call_sites = _resolved_call_sites(symbol, graph)
diff --git a/packages/core/src/repowise/core/generation/selection/selector.py b/packages/core/src/repowise/core/generation/selection/selector.py
index b1a4d6e3a..fefae1b0c 100644
--- a/packages/core/src/repowise/core/generation/selection/selector.py
+++ b/packages/core/src/repowise/core/generation/selection/selector.py
@@ -16,7 +16,7 @@ from typing import Any
import structlog
from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
-from repowise.core.ingestion.package_roots import package_roots_from_paths
+from repowise.core.ingestion.package_roots import package_manifest_names, package_roots_from_paths
from ..concept_tree.grouping import ConceptGroup, group_files
from ..concept_tree.naming import (
@@ -45,9 +45,8 @@ _CODE_LANGUAGES = _LANG_REGISTRY.code_languages()
# Top-level directories whose contents document or illustrate the repository
# rather than being it. Matched as a whole first path segment only. See
# ``_is_support_file`` for why the anchoring is the point.
-_SUPPORT_ROOT_DIRS = frozenset(
- {"docs", "doc", "documentation", "docs_src", "examples", "example", "samples", "sample"}
-)
+_DOC_ROOT_DIRS = frozenset({"docs", "doc", "documentation"})
+_SUPPORT_ROOT_DIRS = _DOC_ROOT_DIRS | {"docs_src", "examples", "example", "samples", "sample"}
# ---------------------------------------------------------------------------
@@ -280,13 +279,11 @@ def count_documentable_files(parsed_files: list[Any]) -> int:
nothing about. Exists so a caller can report what the volume policy is about
to do before generation starts, in the same terms the policy uses.
"""
- return sum(
- 1 for p in parsed_files if _is_code_file(p) and _passes_importance_floor(p.file_info.path)
- )
+ return sum(1 for p in parsed_files if _is_code_file(p) and _passes_importance_floor(p))
-def _passes_importance_floor(path: str) -> bool:
- """Whether *path* is worth a file page at all.
+def _passes_importance_floor(parsed: Any) -> bool:
+ """Whether *parsed* is worth a file page at all.
Two exclusions, both measured rather than assumed: test files and pure
``__init__.py`` re-export files. Pages for either only dilute retrieval
@@ -298,11 +295,14 @@ def _passes_importance_floor(path: str) -> bool:
more because every file that clears this floor gets a page, so the floor is
now simply what file-page selection means. The rule is unchanged; only the
set it applies to grew from the remainder to the whole.
+
+ Tests are read off ``FileInfo.is_test``, the flag ingestion stamps once, so
+ ``e2e-tests/`` and ``foo.spec.ts`` are caught exactly as everywhere else.
"""
- norm = path.replace("\\", "/")
- if norm.startswith("tests/") or "/tests/" in norm:
+ fi = parsed.file_info
+ if fi.is_test:
return False
- return norm.rsplit("/", 1)[-1] != "__init__.py"
+ return fi.path.replace("\\", "/").rsplit("/", 1)[-1] != "__init__.py"
# ---------------------------------------------------------------------------
@@ -323,9 +323,9 @@ def _build_file_candidates(
for p in inputs.parsed_files:
if not _is_code_file(p):
continue
- path = p.file_info.path
- if not _passes_importance_floor(path):
+ if not _passes_importance_floor(p):
continue
+ path = p.file_info.path
is_hotspot = bool(git.get(path, {}).get("is_hotspot", False))
s = score_file(
p,
@@ -365,6 +365,7 @@ def _build_symbol_candidates(
) -> list[tuple[float, tuple[str, str]]]:
"""Return ``[(score, (file_path, symbol_name)), ...]`` descending."""
max_pr = max(inputs.pagerank.values(), default=0.0)
+ test_paths = {p.file_info.path for p in inputs.parsed_files if p.file_info.is_test}
scored: list[tuple[float, tuple[str, str]]] = []
for p in inputs.parsed_files:
file_pr = inputs.pagerank.get(p.file_info.path, 0.0)
@@ -400,11 +401,11 @@ def _build_symbol_candidates(
pct = getattr(inputs.config, "top_symbol_percentile", 0.10) or 0.0
if pct <= 0:
return []
- if pct >= 1.0:
- return deduped
# At least one, so a repo with few public symbols still gets a spotlight.
- keep = max(1, int(len(deduped) * pct))
- return deduped[:keep]
+ keep = len(deduped) if pct >= 1.0 else max(1, int(len(deduped) * pct))
+ # Sized on the whole pool so production never loses a slot it had; tests only
+ # hand theirs to the next production symbol.
+ return [c for c in deduped if c[1][0] not in test_paths][:keep]
def _layer_map_from_kg(
@@ -432,7 +433,24 @@ def _layer_map_from_kg(
return layer_of_file, labels
-def _is_support_file(path: str) -> bool:
+def _doc_app_roots(parsed_files: list[Any]) -> frozenset[str]:
+ """Top-level doc directories that hold their own package manifest.
+
+ A ``docs/package.json`` makes ``docs/`` a separately built app (a docs
+ site), which is part of the subject. Read from the parsed file list, so a
+ manifest the traverser drops (``go.mod``, ``Gemfile``) is not seen here;
+ a docs app is in practice an npm or Python package.
+ """
+ names = package_manifest_names()
+ roots: set[str] = set()
+ for p in parsed_files:
+ head, sep, rest = p.file_info.path.partition("/")
+ if sep and rest in names and head.lower() in _DOC_ROOT_DIRS:
+ roots.add(head.lower())
+ return frozenset(roots)
+
+
+def _is_support_file(path: str, doc_app_roots: frozenset[str]) -> bool:
"""Whether *path* is documentation or example source rather than the subject.
Anchored at the repository root and matched on whole path segments, which
@@ -447,10 +465,11 @@ def _is_support_file(path: str) -> bool:
concept query on vocabulary without answering how the system works, and a
wiki that documents its subject's documentation has said nothing about the
subject. They keep their deterministic file pages, so nothing becomes
- unreachable.
+ unreachable. A doc directory in *doc_app_roots* is an app, not prose, and
+ stays in (see :func:`_doc_app_roots`).
"""
head = path.split("/", 1)[0].lower()
- return head in _SUPPORT_ROOT_DIRS
+ return head in _SUPPORT_ROOT_DIRS and head not in doc_app_roots
def _build_module_groups(inputs: SelectionInputs) -> ConceptCandidates:
@@ -479,7 +498,8 @@ def _build_module_groups(inputs: SelectionInputs) -> ConceptCandidates:
for p in inputs.parsed_files
if _is_code_file(p) and not getattr(p.file_info, "is_test", False)
]
- files = [p for p in production if not _is_support_file(p)]
+ doc_apps = _doc_app_roots(inputs.parsed_files)
+ files = [p for p in production if not _is_support_file(p, doc_apps)]
if not files:
# A repository whose production code is entirely under one of those
# roots. Documenting the docs is a bad wiki; having no wiki at all is
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.py
index e041dcb83..cf5e741ea 100644
--- a/packages/core/src/repowise/core/ingestion/traverser.py
+++ b/packages/core/src/repowise/core/ingestion/traverser.py
@@ -793,6 +793,7 @@ class FileTraverser:
_is_console_script_target(rel_str, self._console_script_modules)
or rel_str in self._distribution_inits
)
+ is_test = is_test_related_path(rel_str, language)
return FileInfo(
path=rel_str,
abs_path=str(abs_path),
@@ -800,9 +801,9 @@ class FileTraverser:
size_bytes=size_bytes,
git_hash="",
last_modified=datetime.fromtimestamp(stat.st_mtime),
- is_test=is_test_related_path(rel_str, language),
+ is_test=is_test,
is_config=_is_config_file(language),
- is_api_contract=_is_api_contract(abs_path, language),
+ is_api_contract=not is_test and _is_api_contract(abs_path, language),
is_entry_point=_is_entry_point(rel_str, abs_path, language) or manifest_entry,
is_manifest_entry=manifest_entry,
)
@@ -1107,14 +1108,30 @@ def _is_config_file(language: LanguageTag) -> bool:
return language in ("yaml", "toml", "json", "dockerfile", "makefile")
+# A spec named in its filename is a data file; ``openapi.ts`` is code that reads
+# one, and a code file earns the flag only from its routes (api_contract_detector).
+_API_SPEC_LANGUAGES: frozenset[str] = frozenset({"yaml", "json"})
+_API_SPEC_NAME_WORDS: frozenset[str] = frozenset({"openapi", "swagger"})
+# The version key every OpenAPI/Swagger document carries (``openapi: 3.1.0``,
+# ``"swagger": "2.0"``); generator configs named after the format lack it.
+_API_SPEC_VERSION_KEY = re.compile(
+ rb"""^\s*\{?\s*["']?(?:openapi|swagger)["']?\s*:\s*["']?\d""", re.M
+)
+
+
def _is_api_contract(abs_path: Path, language: LanguageTag) -> bool:
if language in ("proto", "graphql"):
return True
- name_lower = abs_path.name.lower()
- return any(
- marker in name_lower
- for marker in ("openapi", "swagger", "schema.graphql", "api.yaml", "api.json")
- )
+ if language not in _API_SPEC_LANGUAGES:
+ return False
+ stem = abs_path.name.lower().rsplit(".", 1)[0]
+ # Whole words only: ``tsconfig.api.json`` is not an API spec, ``api.yaml`` may be.
+ if stem != "api" and _API_SPEC_NAME_WORDS.isdisjoint(re.split(r"[-_.]+", stem)):
+ return False
+ try:
+ return _API_SPEC_VERSION_KEY.search(abs_path.read_bytes()) is not None
+ except OSError:
+ return False
def _stem_is_entry_point(abs_path: Path) -> bool:
diff --git a/tests/unit/generation/test_api_contract_detector.py b/tests/unit/generation/test_api_contract_detector.py
index 66e9142ad..1a1eb8efe 100644
--- a/tests/unit/generation/test_api_contract_detector.py
+++ b/tests/unit/generation/test_api_contract_detector.py
@@ -4,11 +4,13 @@ from __future__ import annotations
from datetime import datetime
+import pytest
+
from repowise.core.generation.api_contract_detector import detect_code_api_contracts
-from repowise.core.ingestion.models import FileInfo, Import, ParsedFile, Symbol
+from repowise.core.ingestion.models import FileInfo, HeritageRelation, Import, ParsedFile, Symbol
-def _file(path: str, language: str) -> FileInfo:
+def _file(path: str, language: str, is_test: bool = False) -> FileInfo:
return FileInfo(
path=path,
abs_path=f"/repo/{path}",
@@ -16,14 +18,21 @@ def _file(path: str, language: str) -> FileInfo:
size_bytes=100,
git_hash="",
last_modified=datetime.now(),
- is_test=False,
+ is_test=is_test,
is_config=False,
is_api_contract=False,
is_entry_point=False,
)
-def _sym(name: str, kind: str = "function", decorators: list[str] | None = None, signature: str = "") -> Symbol:
+def _sym(
+ name: str,
+ kind: str = "function",
+ decorators: list[str] | None = None,
+ signature: str = "",
+ parent: str | None = None,
+ visibility: str = "public",
+) -> Symbol:
return Symbol(
id=f"x::{name}",
name=name,
@@ -34,6 +43,8 @@ def _sym(name: str, kind: str = "function", decorators: list[str] | None = None,
end_line=2,
docstring=None,
decorators=decorators or [],
+ parent_name=parent,
+ visibility=visibility, # type: ignore[arg-type]
)
@@ -47,21 +58,51 @@ def _imp(module: str, names: list[str]) -> Import:
)
-def _parsed(path: str, language: str, *, imports=(), symbols=()) -> ParsedFile:
+def _parsed(
+ path: str, language: str, *, imports=(), symbols=(), heritage=(), is_test=False
+) -> ParsedFile:
return ParsedFile(
- file_info=_file(path, language),
+ file_info=_file(path, language, is_test),
symbols=list(symbols),
imports=list(imports),
exports=[],
+ heritage=list(heritage),
)
-def test_detects_fastapi_router_via_import():
- pf = _parsed("app/routes.py", "python", imports=[_imp("fastapi", ["APIRouter"])])
+def _extends(child: str, parent: str) -> HeritageRelation:
+ return HeritageRelation(child_name=child, parent_name=parent, kind="extends", line=1)
+
+
+def test_fastapi_import_without_an_operation_is_not_a_contract():
+ """Building the app or mounting routers declares no endpoint."""
+ pf = _parsed("app/main.py", "python", imports=[_imp("fastapi", ["APIRouter", "FastAPI"])])
+ assert detect_code_api_contracts([pf]) == 0
+ assert pf.file_info.is_api_contract is False
+
+
+def test_detects_fastapi_router_with_an_operation():
+ pf = _parsed(
+ "app/routes.py",
+ "python",
+ imports=[_imp("fastapi", ["APIRouter"])],
+ symbols=[_sym("create", decorators=["@router.post('/items')"])],
+ )
assert detect_code_api_contracts([pf]) == 1
assert pf.file_info.is_api_contract is True
+def test_a_test_file_is_never_a_contract():
+ pf = _parsed(
+ "tests/test_routes.py",
+ "python",
+ imports=[_imp("fastapi", ["FastAPI"])],
+ symbols=[_sym("read", decorators=["@app.get('/')"])],
+ is_test=True,
+ )
+ assert detect_code_api_contracts([pf]) == 0
+
+
def test_detects_fastapi_via_method_decorator():
pf = _parsed(
"app/routes.py",
@@ -78,11 +119,16 @@ def test_skips_python_file_without_fastapi():
assert pf.file_info.is_api_contract is False
-def test_detects_aspnet_controller_via_inheritance():
[email protected]("base", ["ControllerBase", "Controller", "ApiController"])
+def test_detects_aspnet_controller_via_inheritance(base):
pf = _parsed(
"Controllers/UsersController.cs",
"csharp",
- symbols=[_sym("UsersController", kind="class", signature="class UsersController : ControllerBase")],
+ symbols=[
+ _sym("UsersController", kind="class", signature="class UsersController"),
+ _sym("Get", kind="method", parent="UsersController"),
+ ],
+ heritage=[_extends("UsersController", base)],
)
assert detect_code_api_contracts([pf]) == 1
@@ -91,11 +137,54 @@ def test_detects_aspnet_controller_via_attribute():
pf = _parsed(
"Controllers/UsersController.cs",
"csharp",
- symbols=[_sym("UsersController", kind="class", decorators=["[ApiController]"])],
+ symbols=[
+ _sym("UsersController", kind="class", decorators=["ApiController"]),
+ _sym("List", kind="method", parent="UsersController"),
+ ],
)
assert detect_code_api_contracts([pf]) == 1
+def test_detects_aspnet_action_on_a_custom_base_controller():
+ pf = _parsed(
+ "Controllers/UsersController.cs",
+ "csharp",
+ symbols=[
+ _sym("UsersController", kind="class"),
+ _sym("Get", kind="method", parent="UsersController", decorators=['HttpGet("{id}")']),
+ ],
+ heritage=[_extends("UsersController", "AppControllerBase")],
+ )
+ assert detect_code_api_contracts([pf]) == 1
+
+
+def test_aspnet_controller_without_a_public_action_is_not_a_contract():
+ pf = _parsed(
+ "Controllers/UsersController.cs",
+ "csharp",
+ symbols=[
+ _sym("UsersController", kind="class"),
+ _sym("Helper", kind="method", parent="UsersController", visibility="private"),
+ ],
+ heritage=[_extends("UsersController", "ControllerBase")],
+ )
+ assert detect_code_api_contracts([pf]) == 0
+
+
+def test_a_class_named_controller_is_not_a_contract():
+ """A name is not a base class: a game ``InputController`` serves no HTTP."""
+ pf = _parsed(
+ "Input/InputController.cs",
+ "csharp",
+ symbols=[
+ _sym("InputController", kind="class", signature="class InputController"),
+ _sym("Update", kind="method", parent="InputController"),
+ ],
+ heritage=[_extends("InputController", "MonoBehaviour")],
+ )
+ assert detect_code_api_contracts([pf]) == 0
+
+
def test_already_flagged_file_is_untouched():
pf = _parsed("api/openapi.yaml", "yaml")
pf.file_info.is_api_contract = True
diff --git a/tests/unit/generation/test_context_assembler.py b/tests/unit/generation/test_context_assembler.py
index e28218b3d..36e6358e9 100644
--- a/tests/unit/generation/test_context_assembler.py
+++ b/tests/unit/generation/test_context_assembler.py
@@ -158,11 +158,8 @@ def test_assemble_file_page_dependencies_from_graph(
assert "python_pkg/utils.py" in ctx.dependencies
-def test_assemble_file_page_filters_dependency_edges_by_semantics(
- sample_config, sample_parsed_file, graph_metrics, sample_source_bytes
-):
- """Only structural file-to-file edges become dependencies or dependents."""
- path = sample_parsed_file.file_info.path
+def _semantic_edge_graph(path: str) -> nx.DiGraph:
+ """Every kind of edge a file node carries, structural or not."""
graph = nx.DiGraph()
file_nodes = (
path,
@@ -188,6 +185,14 @@ def test_assemble_file_page_filters_dependency_edges_by_semantics(
graph.add_edge("historical_dependent.py", path, edge_type="co_changes")
graph.add_edge(path, "external:third-party", edge_type="imports")
graph.add_edge(path, "external_file.py", edge_type="imports")
+ return graph
+
+
+def test_assemble_file_page_filters_dependency_edges_by_semantics(
+ sample_config, sample_parsed_file, graph_metrics, sample_source_bytes
+):
+ """Only structural file-to-file edges become dependencies or dependents."""
+ graph = _semantic_edge_graph(sample_parsed_file.file_info.path)
ctx = ContextAssembler(sample_config).assemble_file_page(
sample_parsed_file,
@@ -262,6 +267,27 @@ def test_assemble_symbol_spotlight_callers(
assert "caller.py" in ctx.callers
+def test_spotlight_importers_match_the_file_page(
+ sample_config, sample_parsed_file, graph_metrics, sample_source_bytes
+):
+ """One importer count per file: co-change and containment edges count on neither."""
+ graph = _semantic_edge_graph(sample_parsed_file.file_info.path)
+ assembler = ContextAssembler(sample_config)
+ file_ctx = assembler.assemble_file_page(
+ sample_parsed_file,
+ graph,
+ graph_metrics["pagerank"],
+ graph_metrics["betweenness"],
+ graph_metrics["community"],
+ sample_source_bytes,
+ )
+ spot_ctx = assembler.assemble_symbol_spotlight(
+ sample_parsed_file.symbols[0], sample_parsed_file, graph_metrics["pagerank"], graph
+ )
+
+ assert spot_ctx.callers == file_ctx.dependents == ["importer.py", "framework_entrypoint.py"]
+
+
def test_assemble_symbol_spotlight_no_callers(
sample_config, sample_parsed_file, sample_graph, graph_metrics
):
diff --git a/tests/unit/generation/test_selection_concept_groups.py b/tests/unit/generation/test_selection_concept_groups.py
index de527dad1..4aa0d6638 100644
--- a/tests/unit/generation/test_selection_concept_groups.py
+++ b/tests/unit/generation/test_selection_concept_groups.py
@@ -238,6 +238,39 @@ def test_root_documentation_and_examples_get_no_concept_page():
assert any(p.startswith("docs_src/") for p in _support_paths())
+def _with_manifests(inputs: SelectionInputs, *manifests: str) -> SelectionInputs:
+ for path in manifests:
+ fi = FakeFileInfo(path=path, language="json" if path.endswith(".json") else "toml")
+ inputs.parsed_files.append(FakeParsedFile(file_info=fi))
+ return inputs
+
+
+def test_a_docs_directory_with_its_own_manifest_is_an_app_and_keeps_its_pages():
+ """``docs/package.json`` makes the docs site a built app, part of the subject."""
+ app = [f"docs/components/widget{i}.py" for i in range(6)]
+ inputs = _with_manifests(
+ _inputs(paths=_paths() + app + _support_paths()), "docs/package.json"
+ )
+ claimed = {p for _, g in _build_module_groups(inputs).scored for p in g.file_paths}
+
+ assert set(app) <= claimed, f"a docs app was excluded: {set(app) - claimed}"
+ # Only the doc roots: an examples tree stays illustration whatever it ships.
+ assert not any(p.startswith(("docs_src/", "examples/", "samples/")) for p in claimed)
+
+
+def test_a_docs_directory_without_a_root_manifest_stays_excluded():
+ """Prose plus a Sphinx ``conf.py``; a manifest deeper down is not the docs root."""
+ inputs = _with_manifests(
+ _inputs(paths=_paths() + _support_paths()),
+ "docs/examples/demo/package.json",
+ "examples/package.json",
+ )
+ claimed = [p for _, g in _build_module_groups(inputs).scored for p in g.file_paths]
+
+ assert not any(p.startswith("docs/") for p in claimed)
+ assert not any(p.startswith("examples/") for p in claimed)
+
+
def test_a_docs_directory_inside_a_package_keeps_its_pages():
"""The rule is anchored at the repository root, so a docs *feature* stays.
diff --git a/tests/unit/generation/test_selection_contract.py b/tests/unit/generation/test_selection_contract.py
index 1fe1d99e2..74921ca07 100644
--- a/tests/unit/generation/test_selection_contract.py
+++ b/tests/unit/generation/test_selection_contract.py
@@ -21,6 +21,7 @@ from repowise.core.generation.selection import (
recommended_file_page_cap,
select_pages,
)
+from repowise.core.test_paths import is_test_related_path
# ---------------------------------------------------------------------------
# Lightweight ParsedFile / Symbol stand-ins
@@ -142,17 +143,29 @@ def test_importance_floor_excludes_tests_and_reexports():
retrieval, so they get no page even though nothing is rationed any more.
"""
parsed, pagerank, betweenness, community = _build_synthetic_repo(6)
- for extra in ("tests/test_thing.py", "pkg0/sub/tests/test_more.py", "pkg0/__init__.py"):
- parsed.append(FakeParsedFile(file_info=FakeFileInfo(path=extra), symbols=[]))
+ extras = (
+ "tests/test_thing.py",
+ "pkg0/sub/tests/test_more.py",
+ "pkg0/__init__.py",
+ "e2e-tests/cli/run.ts",
+ "web/src/button.spec.ts",
+ "pkg0/conftest.py",
+ )
+ for extra in extras:
+ # Stamped the way ingestion stamps it; symbols so the score floor passes.
+ fi = FakeFileInfo(path=extra, is_test=is_test_related_path(extra))
+ parsed.append(FakeParsedFile(file_info=fi, symbols=[FakeSymbol(name="helper")]))
pagerank[extra] = 1.0
betweenness[extra] = 0.0
community[extra] = 0
sel = select_pages(_inputs(parsed, pagerank, betweenness, community, GenerationConfig()))
- assert "tests/test_thing.py" not in sel.file_page_paths
- assert "pkg0/sub/tests/test_more.py" not in sel.file_page_paths
- assert "pkg0/__init__.py" not in sel.file_page_paths
+ spotlit = {path for path, _ in sel.symbol_spotlights}
+ for extra in extras:
+ assert extra not in sel.file_page_paths
+ if is_test_related_path(extra):
+ assert extra not in spotlit
assert len(sel.file_page_paths) == 6
@@ -356,11 +369,28 @@ def test_explicit_cap_beats_the_policy_in_both_directions():
assert len(looser.file_page_paths) == FILE_PAGE_AUTO_CEILING + 100
+def test_test_symbols_hand_their_spotlight_slots_to_production():
+ """Tests outranking production must not shrink the production slice."""
+ parsed, pagerank, betweenness, community = _build_synthetic_repo(20)
+ base = select_pages(_inputs(parsed, pagerank, betweenness, community, GenerationConfig()))
+ for i in range(3):
+ path = f"aaa{i}/tests/test_thing.py"
+ fi = FakeFileInfo(path=path, is_test=True)
+ parsed.append(FakeParsedFile(file_info=fi, symbols=[FakeSymbol(name="helper")]))
+ pagerank[path] = 1.0
+
+ sel = select_pages(_inputs(parsed, pagerank, betweenness, community, GenerationConfig()))
+
+ assert set(base.symbol_spotlights) <= set(sel.symbol_spotlights)
+ assert not any(is_test_related_path(path) for path, _ in sel.symbol_spotlights)
+
+
def test_count_documentable_files_matches_the_floor():
"""The count a caller reports with is the count selection acts on."""
parsed, pagerank, betweenness, community = _build_synthetic_repo(20)
for extra in ("tests/test_thing.py", "pkg0/__init__.py"):
- parsed.append(FakeParsedFile(file_info=FakeFileInfo(path=extra), symbols=[]))
+ fi = FakeFileInfo(path=extra, is_test=is_test_related_path(extra))
+ parsed.append(FakeParsedFile(file_info=fi, symbols=[]))
pagerank[extra] = 1.0
betweenness[extra] = 0.0
community[extra] = 0
diff --git a/tests/unit/ingestion/test_traverser.py b/tests/unit/ingestion/test_traverser.py
index c0aa43ad8..d6c8f4d6d 100644
--- a/tests/unit/ingestion/test_traverser.py
+++ b/tests/unit/ingestion/test_traverser.py
@@ -1490,3 +1490,45 @@ class TestPackageScanPruning:
tv = FileTraverser(tmp_path)
language, _ = _scan_package_dir(pkg, tmp_path, is_pruned=tv.dir_chain_skipped)
assert language == "unknown"
+
+
+# ---------------------------------------------------------------------------
+# API contract flag
+# ---------------------------------------------------------------------------
+
+_YAML_SPEC = "openapi: 3.0.0\ninfo:\n title: t\npaths: {}\n"
+_JSON_SPEC = '{"swagger": "2.0", "paths": {}}\n'
+_PROTO = "syntax = 'proto3';\n"
+
+
+class TestApiContractFlag:
+ @pytest.mark.parametrize(
+ ("path", "content", "expected"),
+ [
+ ("api/openapi.yaml", _YAML_SPEC, True),
+ ("public/openapi-webhooks.json", _JSON_SPEC, True),
+ ("gen/echo.swagger.json", '{\n "swagger": "2.0",\n "info": {}\n}\n', True),
+ ("api.json", _JSON_SPEC, True),
+ ("proto/service.proto", _PROTO, True),
+ ("schema/schema.graphql", "type Query { a: Int }\n", True),
+ # Named after the format, but a generator config rather than a spec.
+ ("proto/openapi_merge.buf.gen.yaml", "plugins:\n - local: protoc-gen-openapiv2\n", False),
+ ("swagger-config.yaml", "url: /openapi.json\n", False),
+ # Code named after a spec reads or builds one; it is not the spec.
+ ("lib/openapi.ts", "export {}\n", False),
+ ("scripts/fetch-openapi.mjs", "export {}\n", False),
+ ("pkg/utils/openapi.py", "x = 1\n", False),
+ # Whole words: a config variant is not a spec.
+ ("tsconfig.api.json", _JSON_SPEC, False),
+ # A test that exercises a spec is not the spec.
+ ("tests/test_openapi.py", "x = 1\n", False),
+ ("tests/api/openapi.yaml", _YAML_SPEC, False),
+ ("src/test/protobuf/bag.proto", _PROTO, False),
+ ],
+ )
+ def test_flag(self, tmp_path: Path, path: str, content: str, expected: bool) -> None:
+ f = tmp_path / path
+ f.parent.mkdir(parents=True, exist_ok=True)
+ f.write_text(content)
+ by_path = {fi.path: fi for fi in FileTraverser(tmp_path).traverse()}
+ assert by_path[path].is_api_contract is expected