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(ingestion): multi-language import resolution — lightweight resolvers, same-scope linking, spec metadata (#392)

Swati Ahuja5a1a8b5b4eb9
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index 581e47ad3..38bc787da 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -47,13 +47,13 @@ call resolution, named bindings, heritage extraction, and docstrings.
|----------|-----------|-------------|-------------|
| **Python** | `.py` `.pyi` | `main.py` `app.py` `__main__.py` `manage.py` `wsgi.py` `asgi.py` | `import x` / `from x import y` |
| **TypeScript** | `.ts` `.tsx` | `index.ts` `main.ts` `app.ts` `server.ts` | `import { x } from 'y'` / `export { x } from 'y'` & `export * from 'y'` re-export barrels / `require()` with tsconfig path aliases, npm/yarn/pnpm `workspaces`, and optional `.vue`/`.svelte`/`.astro` SFC probing |
-| **JavaScript** | `.js` `.jsx` `.mjs` `.cjs` | `index.js` `main.js` `app.js` `server.js` | `import` / `require()` |
-| **Java** | `.java` | `Main.java` `Application.java` | `import pkg.Class` / `import pkg.*` / `import static pkg.Class.*` with Maven `pom.xml` reactor + Gradle `settings.gradle(.kts)` source-sets + `gradle/libs.versions.toml` discovery, JPMS `module-info.java` / `package-info.java` recognition, fan-out to every file in the imported package (siblings share importers), same-package implicit identifier resolution |
-| **Kotlin** | `.kt` `.kts` | `Main.kt` `Application.kt` | `import com.example.Foo` / `import com.example.*` sharing the JVM workspace index with Java (cross-language resolution, `.kt` under `src/main/java` recognised) |
+| **JavaScript** | `.js` `.jsx` `.mjs` `.cjs` | `index.js` `main.js` `app.js` `server.js` | `import` / `require()` incl. CommonJS re-export shapes (`module.exports = require('./x')`, `exports.foo = require('./y')`, `Object.assign(module.exports, require('./z'), …)` — flagged as re-export hubs like ESM barrels) and member picks (`var x = require('./m').member`) |
+| **Java** | `.java` | `Main.java` `Application.java` | `import pkg.Class` / `import pkg.*` / `import static pkg.Class.*` with Maven `pom.xml` reactor + Gradle `settings.gradle(.kts)` source-sets + `gradle/libs.versions.toml` discovery, JPMS `module-info.java` / `package-info.java` recognition, fan-out to every file in the imported package (siblings share importers), same-package implicit identifier resolution; JDK namespaces (`java.` / `javax.` / `jdk.`) are filtered with no node, `jakarta.` classifies as an external dependency |
+| **Kotlin** | `.kt` `.kts` | `Main.kt` `Application.kt` | `import com.example.Foo` / `import com.example.*` sharing the JVM workspace index with Java (cross-language resolution, `.kt` under `src/main/java` recognised); `kotlin.` stdlib filtered with no node, `kotlinx.` classifies as an external dependency; same-package implicit identifier resolution |
| **Go** | `.go` | `main.go` `cmd/main.go` | `import "path"` with multi-module `go.mod` discovery (longest-prefix match); a package import fans out to **all** `.go` files in the package directory |
| **Rust** | `.rs` | `main.rs` `lib.rs` | `use crate::` / `use super::` / `use self::` with `Cargo.toml` |
-| **C++** | `.cpp` `.cc` `.cxx` `.h` `.hpp` `.hxx` | `main.cpp` `main.cc` `WinMain` `wWinMain` `LLVMFuzzerTestOneInput` `DllMain` | `#include` with `compile_commands.json` resolution + CMake / Bazel workspace public-header maps + per-target include-dir search + sibling-TU fan-out |
-| **C#** | `.cs` | `Program.cs` `Startup.cs` | `using Acme.Domain` / `global using` / `using static` / `using Alias = X.Y.Z` with `.csproj` / `.sln` / `Directory.Build.props` resolution |
+| **C++** | `.cpp` `.cc` `.cxx` `.h` `.hpp` `.hxx` | `main.cpp` `main.cc` `WinMain` `wWinMain` `LLVMFuzzerTestOneInput` `DllMain` | `#include` with `compile_commands.json` resolution + CMake / Bazel workspace public-header maps + per-target include-dir search + sibling-TU fan-out (header-only targets fan out across their headers) + same-stem same-dir header ↔ implementation pairing edges |
+| **C#** | `.cs` | `Program.cs` `Startup.cs` | `using Acme.Domain` / `global using` / `using static` / `using Alias = X.Y.Z` with `.csproj` / `.sln` / `Directory.Build.props` resolution; `partial` class co-fragments linked bidirectionally; nested types resolve one level (`Outer.Inner`) |
All nine languages support:
- Tree-sitter AST parsing with dedicated `.scm` query files
@@ -118,9 +118,9 @@ resolvers for each language.
| Language | Extensions | Entry Points | Import Style |
|----------|-----------|-------------|-------------|
| **C** | `.c` | `main.c` | `#include` with `compile_commands.json` (shares C++ grammar) |
-| **Ruby** | `.rb` | `main.rb` `app.rb` `config.ru` | `require 'mod'` / `require_relative './mod'` plus Rails / Zeitwerk autoloading (gated on `config/application.rb`) |
-| **Swift** | `.swift` | `main.swift` `App.swift` | `import Foundation` with SPM `Package.swift` `targets:` → directory mapping |
-| **Scala** | `.scala` | `Main.scala` `App.scala` | `import pkg.{A, B => C}` with SBT `build.sbt` / Mill `build.sc` multi-project parsing |
+| **Ruby** | `.rb` | `main.rb` `app.rb` `config.ru` | `require 'mod'` / `require_relative './mod'` with `$LOAD_PATH` convention probing (`require 'sinatra/base'` → `lib/sinatra/base.rb`, including every sub-gem's `lib/` in monorepos), Ruby-stdlib requires filtered with no node, Gemfile/gemspec dependencies labelled as gem externals, rspec directory-mirror edges (`spec/lib/x_spec.rb` → `lib/x.rb`), plus Rails / Zeitwerk autoloading (gated on `config/application.rb`) |
+| **Swift** | `.swift` | `main.swift` `App.swift` | `import Foundation` with SPM `Package.swift` `targets:` → directory mapping; intra-module type references link same-target files (Swift has no intra-module imports by design); `@main` / `@UIApplicationMain` / `@NSApplicationMain` flag entry points; `@_exported import` marks re-exports |
+| **Scala** | `.scala` | `Main.scala` `App.scala` | `import pkg.Foo`, brace imports `{A, B => C}` (expanded per selected name, hidden imports skipped), wildcards (`pkg._` / Scala 3 `pkg.*`), and package imports — resolved through the shared JVM workspace index (chained package clauses, Scala ↔ Java cross-language, same-package implicit identifiers) with SBT `build.sbt` / Mill `build.sc` multi-project parsing as fallback; `scala.` and JDK namespaces filtered |
| **PHP** | `.php` | `index.php` `public/index.php` | `use Foo\Bar\Baz` with composer.json `autoload.psr-4` longest-prefix resolution |
### Config / Data
@@ -139,7 +139,8 @@ endpoints or targets where applicable.
| **YAML** | `.yaml` `.yml` | -- |
| **JSON** | `.json` | -- |
| **TOML** | `.toml` | -- |
-| **Markdown** | `.md` `.mdx` | -- |
+| **Markdown** | `.md` `.mdx` `.markdown` `.mdown` | -- |
+| **AsciiDoc** | `.adoc` `.asciidoc` | -- |
| **SQL** | `.sql` | -- |
| **Shell** | `.sh` `.bash` `.zsh` | -- |
@@ -151,19 +152,42 @@ endpoints or targets where applicable.
AST parsing, symbol extraction (functions, Luau type aliases), and
`require(...)` call capture are wired. Import resolution handles string
-literals and `script`/`script.Parent` relative instance paths. Absolute
-Roblox instance paths (`game.<Service>...`) currently register as external
-nodes and are the target of a follow-up that reads Rojo's
-`default.project.json` tree mapping — see issue #52.
-
-### Git-Blame-Only
+literals, `script`/`script.Parent` relative instance paths (including the
+`:WaitForChild("X")` / `:FindFirstChild("X")` idioms), absolute Roblox
+instance paths (`game.<Service>...`, plus the `game:GetService("X")` idiom)
+through Rojo's `default.project.json` tree mapping, and `@alias` requires
+through `.luaurc` `aliases` maps (nearest declaration wins, child overrides
+parent). Repos without a Rojo project file / `.luaurc` keep the conservative
+external-node fallback (issue #52 is closed by both halves).
+
+### Lightweight (regex-tier import graphs)
+
+These languages have no AST parsing (no symbols, calls, or heritage) but
+get a real file-level import graph from a regex tier: import statements
+are extracted with per-language regexes and resolved against a declared
+module-name index (declaration scan + path-convention inverse). The
+knowledge graph runs in flow/sparse mode on the resulting density —
+honest file-to-file dependencies, no symbol-level claims.
+
+| Language | Extensions | Import Forms Resolved |
+|----------|-----------|----------------------|
+| **Elixir** | `.ex` `.exs` | `alias` / `import` / `use` / `require` (incl. `Foo.{Bar, Baz}` brace groups) → `defmodule` index + Mix `lib/` path convention (umbrella `apps/*/lib` included); Elixir/OTP stdlib filtered after local-miss |
+| **Dart** | `.dart` | `import` / `export` (re-export) / `part` / `part of` URIs; `package:` URIs via every `pubspec.yaml` `name:` (monorepos included); `dart:` SDK URIs filtered; foreign packages → `external:pub:<name>` |
+| **Clojure** | `.clj` `.cljc` `.cljs` | `(:require …)` / `(:use …)` vectors and bare specs (string/comment-safe) → `(ns …)` index + classpath convention (dashes ↔ underscores); `clojure.*`/`cljs.*` filtered |
+| **Haskell** | `.hs` `.lhs` | `import [safe] [qualified] ["pkg"] Foo.Bar` → `module` declaration index + trailing-PascalCase path inverse (handles any hs-source-dirs without parsing `.cabal`); base-ish namespaces filtered after local-miss |
+| **Erlang** | `.erl` `.hrl` | `-include` / `-include_lib` / `-behaviour` + module-qualified calls (`mod:fun(`) → `-module()` index; qualified calls are strict local-hit-or-drop (never mint externals) |
+| **F#** | `.fs` `.fsi` `.fsx` | `open` → file-level `namespace`/`module` index (unambiguous single-file declarations only), plus the fsproj `<Compile Include>` compile-order dependency spine (a real F# constraint: files may only reference earlier files) |
+
+### Structural (git + file tree only)
These languages are tracked in git history (blame, hotspot analysis,
-co-change detection) but have no AST parsing or dedicated support. Files
-appear in the wiki as traversal-level entries.
+co-change detection) but have no AST parsing or import resolution. Files
+appear in the wiki as traversal-level entries, and the knowledge graph
+runs in **structural mode** for repos dominated by them: the tour
+orients by directory structure, naming conventions, and git evidence —
+it never claims an execution flow it cannot see.
-Objective-C, Elixir, Erlang, R, Dart, Zig, Julia, Clojure, Elm,
-Haskell, OCaml, F#, Crystal, Nim, D
+Objective-C, R, Zig, Julia, Elm, OCaml, Crystal, Nim, D
---
@@ -202,6 +226,8 @@ Extension/filename -> LanguageTag (via LanguageRegistry)
Go: go.mod module path stripping
Rust: crate::/self::/super::, mod.rs probing
C/C++: compile_commands.json include directories
+ Lightweight tier (Elixir/Dart/Clojure/Haskell/Erlang/F#):
+ regex-extracted imports vs a declared-module-name index
Other: stem-map fallback (filename matching)
|
v
@@ -479,6 +505,6 @@ relevant `__init__.py` dispatcher / dict.
| Language | Target Tier | Status |
|----------|------------|--------|
-| Dart | Good | Planned — `tree-sitter-dart` available |
-| Elixir | Good | Planned — `tree-sitter-elixir` available |
-| F# | Good | Planned — `tree-sitter-f-sharp` available |
+| Dart | Good | Lightweight tier shipped; AST upgrade planned — `tree-sitter-dart` available |
+| Elixir | Good | Lightweight tier shipped; AST upgrade planned — `tree-sitter-elixir` available |
+| F# | Good | Lightweight tier shipped; AST upgrade planned — `tree-sitter-f-sharp` available |
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd.py b/packages/cli/src/repowise/cli/commands/doctor_cmd.py
index 6361dcadf..c1701558a 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd.py
@@ -23,6 +23,26 @@ def _check(name: str, ok: bool, detail: str = "") -> tuple[str, str, str]:
return (name, status, detail)
+async def _decision_vector_ids(session, repository_id: str) -> set[str]:
+ """Vector-store ids for this repo's decision records.
+
+ Decisions are co-located in the *page* vector store under the
+ ``decision:<record_id>`` namespace (no separate table). The store therefore
+ legitimately holds page vectors *and* decision vectors, so any SQL↔vector
+ reconciliation must count decisions on the SQL side — otherwise every
+ decision embedding reads as an orphan.
+ """
+ from sqlalchemy import text as _sql_text
+
+ from repowise.core.analysis.decisions.semantic_match import DECISION_VECTOR_PREFIX
+
+ rows = await session.execute(
+ _sql_text("SELECT id FROM decision_records WHERE repository_id = :rid"),
+ {"rid": repository_id},
+ )
+ return {f"{DECISION_VECTOR_PREFIX}{r[0]}" for r in rows}
+
+
def _print_cli_version_status() -> None:
"""Print a best-effort CLI update-check line.
@@ -228,6 +248,14 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:
return set(), set(), set(), set()
pages = await list_pages(session, repo.id, limit=10000)
sql_ids = {p.page_id for p in pages}
+ # The page vector store also holds decision embeddings under
+ # the "decision:<id>" namespace, so they belong on the SQL
+ # side of the ORPHAN check (but NOT FTS, which only indexes
+ # pages). They are deliberately excluded from the MISSING
+ # check: a decision can legitimately have no vector (empty
+ # match text, swallowed embed failure) and repair cannot
+ # re-embed it, so flagging it would be permanent noise.
+ vector_sql_ids = sql_ids | await _decision_vector_ids(session, repo.id)
# Check vector store
vs_ids: set[str] = set()
@@ -242,7 +270,7 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:
pass # LanceDB not available
m_vec = sql_ids - vs_ids if vs_ids else set()
- o_vec = vs_ids - sql_ids if vs_ids else set()
+ o_vec = vs_ids - vector_sql_ids if vs_ids else set()
# Check FTS
fts = FullTextSearch(engine)
@@ -289,6 +317,7 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:
from repowise.core.persistence import (
create_engine,
create_session_factory,
+ get_repository_by_path,
get_session,
)
from repowise.core.persistence.coordinator import AtomicStorageCoordinator
@@ -314,6 +343,33 @@ def _run_repo_checks(repo_path: _DoctorPath, repair: bool) -> bool:
)
result = await coord.health_check()
+ # The coordinator's drift compares wiki_pages count against
+ # the vector count, but the vector store also holds decision
+ # embeddings ("decision:<id>" namespace). Without counting
+ # decisions on the SQL side, every decision reads as drift.
+ # Recompute drift with a decision-aware SQL count so a
+ # consistent store reports ~0% rather than a false FAIL.
+ # Count only decisions that actually have a vector: a
+ # decision can legitimately be unembedded (empty match
+ # text, swallowed embed failure), and counting it would
+ # bias drift positive (SQL > Vector) forever.
+ repo = await get_repository_by_path(session, str(repo_path))
+ if repo is not None:
+ dec_ids = await _decision_vector_ids(session, repo.id)
+ decision_count = len(dec_ids)
+ if vector_store is not None:
+ with contextlib.suppress(Exception):
+ store_ids = await vector_store.list_page_ids()
+ decision_count = len(dec_ids & store_ids)
+ sql_pages = result.get("sql_pages")
+ vector_count = result.get("vector_count")
+ if sql_pages is not None:
+ adjusted_sql = sql_pages + decision_count
+ result["sql_pages"] = adjusted_sql
+ if vector_count is not None and vector_count != -1:
+ denom = max(adjusted_sql, 1)
+ result["drift"] = abs(adjusted_sql - vector_count) / denom
+
if vector_store is not None:
with contextlib.suppress(Exception):
await vector_store.close()
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
index ca41107e4..5ec914b91 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/generation.py
@@ -109,6 +109,13 @@ def select_coverage(
)
from repowise.cli.coverage_select import interactive_coverage_select
+ # Curated modules from the in-memory index result, so the plan/cost
+ # estimate selects the same module set generation will (the artifact
+ # file is not on disk yet during a fresh init).
+ kg_modules = (
+ getattr(getattr(result, "knowledge_graph_result", None), "modules", None) or None
+ )
+
if sys.stdin.isatty() and coverage_pct is None and not yes:
options = compute_coverage_options(
parsed_files=result.parsed_files,
@@ -119,6 +126,7 @@ def select_coverage(
repo_path=repo_path,
skip_tests=skip_tests,
skip_infra=skip_infra,
+ kg_modules=kg_modules,
)
chosen = interactive_coverage_select(console, options)
chosen_pct = chosen.pct
@@ -135,6 +143,7 @@ def select_coverage(
gen_config_for_plan,
skip_tests,
skip_infra,
+ kg_modules=kg_modules,
)
est = estimate_cost(
plans,
@@ -263,6 +272,22 @@ def run_repo_generation(
resume=resume,
cost_tracker=cost_tracker,
generation_config=gen_config,
+ # In-memory curated modules: on a fresh init the
+ # knowledge-graph.json artifact is only written during
+ # persistence, AFTER this generation pass — without this the
+ # kg_ctx file fallback is empty and module selection silently
+ # degrades to community grouping.
+ kg_modules=(
+ getattr(
+ getattr(result, "knowledge_graph_result", None), "modules", None
+ )
+ or None
+ ),
+ kg_data=(
+ result.knowledge_graph_result.to_dict()
+ if getattr(result, "knowledge_graph_result", None) is not None
+ else None
+ ),
)
)
diff --git a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
index 8d9f4ec1a..d909a6e84 100644
--- a/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
+++ b/packages/cli/src/repowise/cli/commands/init_cmd/persistence.py
@@ -51,6 +51,7 @@ async def persist_result(result: Any, repo_path: Path) -> None:
persist_analysis,
persist_generation,
persist_pipeline_result,
+ sweep_stale_generated_pages,
)
engine, sf, _repo_id = await open_repo_db(repo_path, repo_name=result.repo_name)
@@ -88,11 +89,26 @@ async def persist_result(result: Any, repo_path: Path) -> None:
existing = {}
existing["tech_stack"] = result.tech_stack
repo.settings_json = _json.dumps(existing)
+ swept_page_ids: list[str] = []
if index_done:
await persist_analysis(result, session, repo.id)
await persist_generation(result, session, repo.id)
+ # persist_generation has already upserted the current pages, so the
+ # sweep only retires structurally-keyed pages this run did not
+ # reproduce. Without it the incremental-index path (every normal
+ # single-repo init) strands stale community-N / scc / layer pages
+ # forever. A type is swept when the run produced pages of it OR
+ # declared authority over it (curated runs are authoritative for
+ # module/layer pages even when every module page was skipped as
+ # 1:1 with a layer); types that are neither stay protected.
+ swept_page_ids = await sweep_stale_generated_pages(
+ session,
+ repo.id,
+ result.generated_pages,
+ getattr(result, "authoritative_page_types", None),
+ )
else:
- await persist_pipeline_result(result, session, repo.id)
+ swept_page_ids = await persist_pipeline_result(result, session, repo.id)
# Record a completed GenerationJob so the web UI can show
# "last synced" / "last re-indexed" timestamps.
@@ -109,7 +125,24 @@ async def persist_result(result: Any, repo_path: Path) -> None:
job.started_at = now
job.finished_at = now
- # FTS indexing is done outside the session to avoid SQLite write conflicts
+ # Drop swept pages from the vector store *before* the SQL session
+ # commits. The vector store is a separate engine/file (pgvector DB,
+ # LanceDB dir, or in-memory) so there is no SQLite write-lock conflict,
+ # and the delete is idempotent. Keeping the SQL commit last as the
+ # durable source of truth means an interrupted run self-heals: the
+ # vector embedding is already gone, the SQL rows follow on commit.
+ if swept_page_ids:
+ store = getattr(result, "vector_store", None)
+ if store is not None:
+ await store.delete_many(swept_page_ids)
+
+ # FTS deletes/indexing run outside the session: the FTS index lives in the
+ # *same* SQLite file as the session, so touching it while the session still
+ # holds a write lock raises "database is locked". The swept-id delete must
+ # therefore stay here (it cannot move ahead of the SQL commit like the
+ # vector delete can); it is idempotent and narrow (orphan FTS rows only).
+ if fts is not None and swept_page_ids:
+ await fts.delete_many(swept_page_ids)
if fts is not None and result.generated_pages:
for page in result.generated_pages:
await fts.index(page.page_id, page.title, page.content)
diff --git a/packages/cli/src/repowise/cli/commands/update_cmd.py b/packages/cli/src/repowise/cli/commands/update_cmd.py
index a3570a4a3..359842439 100644
--- a/packages/cli/src/repowise/cli/commands/update_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/update_cmd.py
@@ -1180,6 +1180,7 @@ def update_command(
repo_structure,
repo_name,
git_meta_map=git_meta_map,
+ repo_path=repo_path,
)
)
diff --git a/packages/cli/src/repowise/cli/commands/workspace_cmd.py b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
index 7277271b0..98b2b7941 100644
--- a/packages/cli/src/repowise/cli/commands/workspace_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/workspace_cmd.py
@@ -545,6 +545,17 @@ def _run_index_for_repo(
await persist_pipeline_result(result, session, repo.id)
await engine.dispose()
+
+ # Save the curated KG artifact so doc generation can load curated
+ # module grouping (matches the `repowise init` idiom in
+ # init_cmd/command.py). Without it, generation falls back to raw
+ # community grouping and emits wrong module pages.
+ from repowise.cli.state_persistence import save_knowledge_graph_json
+
+ kg = getattr(result, "knowledge_graph_result", None)
+ if kg is not None:
+ save_knowledge_graph_json(repo_path, kg)
+
return result.file_count, result.symbol_count, page_count
try:
@@ -697,6 +708,7 @@ def _generate_docs_for_added_repo(
graph_builder,
repo_structure,
repo_path.name,
+ repo_path=repo_path,
)
url = get_db_url_for_repo(repo_path)
diff --git a/packages/cli/src/repowise/cli/cost_estimator/coverage.py b/packages/cli/src/repowise/cli/cost_estimator/coverage.py
index fa046ab1b..a6e503464 100644
--- a/packages/cli/src/repowise/cli/cost_estimator/coverage.py
+++ b/packages/cli/src/repowise/cli/cost_estimator/coverage.py
@@ -52,6 +52,7 @@ def compute_coverage_options(
repo_path: Path | str | None = None,
skip_tests: bool = False,
skip_infra: bool = False,
+ kg_modules: list[dict] | None = None,
percentages: tuple[float, ...] = DEFAULT_COVERAGE_OPTIONS,
recommended: float = RECOMMENDED_COVERAGE,
) -> list[CoverageOption]:
@@ -66,7 +67,8 @@ def compute_coverage_options(
for pct in percentages:
cfg = replace(base_config, coverage_pct=pct, max_pages_pct=pct)
plans = build_generation_plan(
- parsed_files, graph_builder, cfg, skip_tests, skip_infra
+ parsed_files, graph_builder, cfg, skip_tests, skip_infra,
+ kg_modules=kg_modules,
)
est = estimate_cost(
plans,
diff --git a/packages/cli/src/repowise/cli/cost_estimator/plans.py b/packages/cli/src/repowise/cli/cost_estimator/plans.py
index 8e74aeeee..f6afc65b0 100644
--- a/packages/cli/src/repowise/cli/cost_estimator/plans.py
+++ b/packages/cli/src/repowise/cli/cost_estimator/plans.py
@@ -22,6 +22,7 @@ def build_generation_plan(
config: Any,
skip_tests: bool = False,
skip_infra: bool = False,
+ kg_modules: list[dict] | None = None,
) -> list[PageTypePlan]:
"""Return the per-page-type plan that ``generate_all`` will execute.
@@ -35,6 +36,11 @@ def build_generation_plan(
Finalized GraphBuilder (build() already called).
config:
GenerationConfig — its ``coverage_pct`` drives the budget.
+ kg_modules:
+ Curated wiki modules from the KG artifact, when available. Must be
+ passed for ``module_grouping="curated"`` estimates to match the
+ actual run — without it the selector falls back to community
+ grouping, exactly as generation itself would without an artifact.
"""
files = parsed_files
if skip_tests:
@@ -63,6 +69,7 @@ def build_generation_plan(
sccs=sccs,
git_meta_map=None,
config=config,
+ kg_modules=kg_modules,
)
)
diff --git a/packages/cli/src/repowise/cli/state_persistence.py b/packages/cli/src/repowise/cli/state_persistence.py
index 0c8d6fe61..3b487311d 100644
--- a/packages/cli/src/repowise/cli/state_persistence.py
+++ b/packages/cli/src/repowise/cli/state_persistence.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import logging
from pathlib import Path
from typing import Any
@@ -22,16 +23,33 @@ def build_kg_state(kg: Any) -> dict[str, Any]:
}
-def save_knowledge_graph_json(repo_path: Path, kg: Any) -> None:
+def save_knowledge_graph_json(repo_path: Path, kg: Any, *, portable: bool = False) -> None:
"""Write ``.repowise/knowledge-graph.json`` for a KG result.
No-op when the result can't serialize itself (``to_dict`` missing), so
callers only need to guard against a ``None`` knowledge graph.
+
+ When ``portable`` is set, write the self-contained, self-validated artifact
+ (curated layers + tour + entry points + summaries + a ``meta``/``validation``
+ block) instead of the bare ``to_dict`` output. Hard invariant violations are
+ logged but the artifact is still emitted, with the failures recorded under
+ ``meta.validation`` so a consumer can see them ("repaired, not rejected").
"""
if not hasattr(kg, "to_dict"):
return
import json
+ if portable:
+ from repowise.core.analysis.kg_curation import build_portable_kg
+
+ data, validation = build_portable_kg(kg)
+ if not validation.ok:
+ logging.getLogger(__name__).warning(
+ "portable KG failed invariants: %s", "; ".join(validation.errors)
+ )
+ else:
+ data = kg.to_dict()
+
kg_json_path = repo_path / ".repowise" / "knowledge-graph.json"
kg_json_path.parent.mkdir(parents=True, exist_ok=True)
- kg_json_path.write_text(json.dumps(kg.to_dict(), indent=2), encoding="utf-8")
+ kg_json_path.write_text(json.dumps(data, indent=2), encoding="utf-8")
diff --git a/packages/core/alembic/versions/0031_kg_curated_fields.py b/packages/core/alembic/versions/0031_kg_curated_fields.py
new file mode 100644
index 000000000..17e4e1b22
--- /dev/null
+++ b/packages/core/alembic/versions/0031_kg_curated_fields.py
@@ -0,0 +1,106 @@
+"""Carry curated knowledge-graph fields to the database.
+
+The KG curation pass (kg_curation.py) exports layer ``subGroups``, enriched
+tour steps (``target_path``/``layer_id``/``reason``/``depth``/``kind``/
+``page_type``), ranked project entry points, and per-node curated metadata
+(type/summary/tags) — all of which were dropped at the JSON → DB boundary.
+This revision adds the missing columns plus two new tables so the
+architecture view can serve curated data without re-reading workspace files.
+
+Revision ID: 0031
+Revises: 0030
+Create Date: 2026-06-04
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0031"
+down_revision: str | None = "0030"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ # -- Layers: curated sub-groups ([{id, name, nodeIds}]) -----------------
+ op.add_column(
+ "knowledge_graph_layers",
+ sa.Column("sub_groups_json", sa.Text, nullable=False, server_default="[]"),
+ )
+
+ # -- Tour steps: curated, layer-aware fields ----------------------------
+ op.add_column("knowledge_graph_tour_steps", sa.Column("target_path", sa.Text, nullable=True))
+ op.add_column("knowledge_graph_tour_steps", sa.Column("layer_id", sa.Text, nullable=True))
+ op.add_column(
+ "knowledge_graph_tour_steps",
+ sa.Column("reason", sa.Text, nullable=False, server_default=""),
+ )
+ op.add_column("knowledge_graph_tour_steps", sa.Column("depth", sa.Integer, nullable=True))
+ op.add_column(
+ "knowledge_graph_tour_steps",
+ sa.Column("kind", sa.Text, nullable=False, server_default=""),
+ )
+ op.add_column("knowledge_graph_tour_steps", sa.Column("page_type", sa.Text, nullable=True))
+
+ # -- Project-level curated metadata (one row per repo) -------------------
+ op.create_table(
+ "kg_project_meta",
+ sa.Column("id", sa.String(32), primary_key=True),
+ sa.Column(
+ "repository_id",
+ sa.String(32),
+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("entry_points_json", sa.Text, nullable=False, server_default="[]"),
+ sa.Column("entry_candidates_json", sa.Text, nullable=False, server_default="[]"),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ nullable=False,
+ server_default=sa.func.now(),
+ ),
+ sa.UniqueConstraint("repository_id", name="uq_kg_project_meta"),
+ )
+
+ # -- Per-node curated metadata (presentation view: type/summary/tags) ----
+ op.create_table(
+ "kg_node_meta",
+ sa.Column("id", sa.String(32), primary_key=True),
+ sa.Column(
+ "repository_id",
+ sa.String(32),
+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("node_id", sa.Text, nullable=False),
+ sa.Column("node_type", sa.Text, nullable=False, server_default="file"),
+ sa.Column("summary", sa.Text, nullable=False, server_default=""),
+ sa.Column("tags_json", sa.Text, nullable=False, server_default="[]"),
+ sa.Column(
+ "created_at",
+ sa.DateTime(timezone=True),
+ nullable=False,
+ server_default=sa.func.now(),
+ ),
+ sa.UniqueConstraint("repository_id", "node_id", name="uq_kg_node_meta"),
+ )
+ op.create_index("ix_kg_node_meta_repository_id", "kg_node_meta", ["repository_id"])
+
+
+def downgrade() -> None:
+ op.drop_index("ix_kg_node_meta_repository_id", table_name="kg_node_meta")
+ op.drop_table("kg_node_meta")
+ op.drop_table("kg_project_meta")
+ op.drop_column("knowledge_graph_tour_steps", "page_type")
+ op.drop_column("knowledge_graph_tour_steps", "kind")
+ op.drop_column("knowledge_graph_tour_steps", "depth")
+ op.drop_column("knowledge_graph_tour_steps", "reason")
+ op.drop_column("knowledge_graph_tour_steps", "layer_id")
+ op.drop_column("knowledge_graph_tour_steps", "target_path")
+ op.drop_column("knowledge_graph_layers", "sub_groups_json")
diff --git a/packages/core/src/repowise/core/analysis/communities.py b/packages/core/src/repowise/core/analysis/communities.py
index b9c3852f9..499847baf 100644
--- a/packages/core/src/repowise/core/analysis/communities.py
+++ b/packages/core/src/repowise/core/analysis/communities.py
@@ -21,6 +21,8 @@ from pathlib import PurePosixPath
import networkx as nx
import structlog
+from repowise.core.analysis.kg_curation import GENERIC_ORG_SEGMENTS, dominant_segments
+
log = structlog.get_logger(__name__)
# ---------------------------------------------------------------------------
@@ -40,15 +42,10 @@ _SYMBOL_COMMUNITY_EDGE_TYPES = frozenset({
"calls", "extends", "implements", "has_method",
})
-# Generic directory segments excluded from heuristic labeling.
-# These are organisational containers, not meaningful domain labels.
-_GENERIC_SEGMENTS = frozenset({
- "src", "lib", "core", "common", "shared", "internal", "pkg",
- "main", "app", "utils", "helpers", "index", "mod",
- # Monorepo organisational directories
- "packages", "modules", "workspace", "workspaces", "libs",
- "projects", "services", "apps",
-})
+# Generic directory segments excluded from heuristic labeling — the shared
+# organisational-container vocabulary lives in kg_curation next to its
+# data-driven complement (dominant_segments).
+_GENERIC_SEGMENTS = GENERIC_ORG_SEGMENTS
# Keywords checked in filename stems for fallback labeling
_LABEL_KEYWORDS = (
@@ -125,8 +122,11 @@ def _partition(G: nx.Graph) -> tuple[dict, str]:
try:
from graspologic.partition import leiden
+ leiden_kwargs: dict = {}
+ if "random_seed" in inspect.signature(leiden).parameters:
+ leiden_kwargs["random_seed"] = 42 # determinism (matches louvain's seed)
with _suppress_graspologic_output():
- result = leiden(G)
+ result = leiden(G, **leiden_kwargs)
return result, "leiden"
except ImportError:
pass
@@ -211,7 +211,9 @@ def _cohesion_score(G: nx.Graph, community_nodes: list[str]) -> float:
# ---------------------------------------------------------------------------
-def _collect_path_segments(member_paths: list[str]) -> Counter[str]:
+def _collect_path_segments(
+ member_paths: list[str], extra_generic: frozenset[str] = frozenset()
+) -> Counter[str]:
"""Count non-generic directory segments across all member paths.
Each path contributes at most once per segment to avoid
@@ -223,14 +225,21 @@ def _collect_path_segments(member_paths: list[str]) -> Counter[str]:
seen: set[str] = set()
for part in parts[:-1]: # exclude filename
lower = part.lower()
- if lower not in _GENERIC_SEGMENTS and len(lower) > 1 and not lower.startswith("."):
+ if (
+ lower not in _GENERIC_SEGMENTS
+ and lower not in extra_generic
+ and len(lower) > 1
+ and not lower.startswith(".")
+ ):
if lower not in seen:
counter[lower] += 1
seen.add(lower)
return counter
-def _best_sub_label(member_paths: list[str], primary: str) -> str:
+def _best_sub_label(
+ member_paths: list[str], primary: str, extra_generic: frozenset[str] = frozenset()
+) -> str:
"""Find the best distinguishing sub-segment within paths that contain *primary*.
Given a community labeled "web", looks at paths containing "web" and
@@ -252,6 +261,7 @@ def _best_sub_label(member_paths: list[str], primary: str) -> str:
if (
lower != primary_lower
and lower not in _GENERIC_SEGMENTS
+ and lower not in extra_generic
and len(lower) > 1
and not lower.startswith(".")
and lower not in seen
@@ -267,24 +277,30 @@ def _best_sub_label(member_paths: list[str], primary: str) -> str:
return ""
-def _heuristic_label(member_paths: list[str], community_id: int) -> str:
+def _heuristic_label(
+ member_paths: list[str],
+ community_id: int,
+ extra_generic: frozenset[str] = frozenset(),
+) -> str:
"""Derive a human-readable label from member file paths.
- Produces labels like ``"web/components"`` or ``"repowise/ingestion"``.
+ Produces labels like ``"web/components"`` or ``"core/ingestion"``.
When multiple communities share the same top-level segment, the
- sub-label differentiates them.
+ sub-label differentiates them. *extra_generic* carries repo-dominant
+ namespace segments (the repo's own name, ``src``…) that must never
+ become labels.
"""
if not member_paths:
return f"cluster_{community_id}"
# Strategy 1: most common non-generic directory segment
- seg_counter = _collect_path_segments(member_paths)
+ seg_counter = _collect_path_segments(member_paths, extra_generic)
if seg_counter:
best_seg, best_count = seg_counter.most_common(1)[0]
if best_count / len(member_paths) >= 0.4:
# Try to find a distinguishing sub-segment
- sub = _best_sub_label(member_paths, best_seg)
+ sub = _best_sub_label(member_paths, best_seg, extra_generic)
return f"{best_seg}/{sub}" if sub else best_seg
# Strategy 2: keyword frequency in filenames
@@ -304,7 +320,7 @@ def _heuristic_label(member_paths: list[str], community_id: int) -> str:
stem_counter2: Counter[str] = Counter()
for path in member_paths:
stem = PurePosixPath(path).stem.lower()
- if stem not in _GENERIC_SEGMENTS and len(stem) > 1:
+ if stem not in _GENERIC_SEGMENTS and stem not in extra_generic and len(stem) > 1:
stem_counter2[stem] += 1
if stem_counter2:
return stem_counter2.most_common(1)[0][0]
@@ -312,7 +328,10 @@ def _heuristic_label(member_paths: list[str], community_id: int) -> str:
return f"cluster_{community_id}"
-def _deduplicate_labels(communities_info: dict[int, "CommunityInfo"]) -> None:
+def _deduplicate_labels(
+ communities_info: dict[int, "CommunityInfo"],
+ extra_generic: frozenset[str] = frozenset(),
+) -> None:
"""Add sub-labels to disambiguate communities that share the same label.
Mutates *communities_info* in place. Only touches communities whose
@@ -334,7 +353,7 @@ def _deduplicate_labels(communities_info: dict[int, "CommunityInfo"]) -> None:
if "/" in ci.label:
continue # already has a sub-label
- sub = _best_sub_label(ci.members, base)
+ sub = _best_sub_label(ci.members, base, extra_generic)
if sub:
ci.label = f"{base}/{sub}"
@@ -430,10 +449,12 @@ def detect_file_communities(
- algorithm_used: "leiden" or "louvain"
"""
# Extract file nodes (exclude external nodes — they're structural noise)
- file_nodes = [
+ # Sorted: node order seeds the undirected graph's insertion order, and
+ # Louvain/Leiden partitions depend on iteration order even when seeded.
+ file_nodes = sorted(
n for n, d in graph.nodes(data=True)
if d.get("node_type", "file") == "file"
- ]
+ )
if not file_nodes:
return {}, {}, "none"
@@ -449,11 +470,16 @@ def detect_file_communities(
undirected = nx.Graph()
undirected.add_nodes_from(prod_nodes)
- for u, v, d in graph.edges(data=True):
- edge_type = d.get("edge_type", "imports")
- if edge_type in _FILE_COMMUNITY_EDGE_TYPES and u in undirected and v in undirected:
- if not undirected.has_edge(u, v):
- undirected.add_edge(u, v)
+ # Sorted for the same reason: edge insertion order shifts the partition
+ # (co-change edges arrive in git-indexer thread-completion order).
+ community_edges = sorted(
+ (u, v)
+ for u, v, d in graph.edges(data=True)
+ if d.get("edge_type", "imports") in _FILE_COMMUNITY_EDGE_TYPES
+ and u in undirected
+ and v in undirected
+ )
+ undirected.add_edges_from(community_edges)
# Separate isolates
isolates = [n for n in undirected.nodes() if undirected.degree(n) == 0]
@@ -506,11 +532,15 @@ def detect_file_communities(
if not full_undirected.has_edge(u, v):
full_undirected.add_edge(u, v)
+ # Repo-dominant namespace segments (the repo's own package name, ``src``…)
+ # are noise, not labels — same data-driven stripping as module naming.
+ extra_generic = frozenset(s.lower() for s in dominant_segments(sorted(file_nodes)))
+
for cid, members in community_members.items():
sorted_members = sorted(members)
communities_info[cid] = CommunityInfo(
community_id=cid,
- label=_heuristic_label(sorted_members, cid),
+ label=_heuristic_label(sorted_members, cid, extra_generic),
members=sorted_members,
size=len(sorted_members),
cohesion=_cohesion_score(full_undirected, sorted_members),
@@ -519,7 +549,7 @@ def detect_file_communities(
# Deduplicate labels — add sub-labels when multiple communities
# share the same base (e.g. "web" → "web/components", "web/api")
- _deduplicate_labels(communities_info)
+ _deduplicate_labels(communities_info, extra_generic)
log.info(
"file_communities_detected",
diff --git a/packages/core/src/repowise/core/analysis/kg_curation.py b/packages/core/src/repowise/core/analysis/kg_curation.py
new file mode 100644
index 000000000..15c7a5162
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/kg_curation.py
@@ -0,0 +1,1770 @@
+"""Curation/presentation pass over the deterministic KG skeleton.
+
+The exported knowledge graph is a *presentation* artifact, distinct from the
+AST/dependency graph that powers queries. This module is the single seam where
+the skeleton produced by :func:`build_knowledge_graph_skeleton` is reshaped into
+something a human (or an AI reading the graph cold) can navigate: bounded,
+dependency-ordered layers; a capped, ranked set of real entry points; one
+canonical execution-flow tour; typed infra/CI/data nodes; and never-empty
+summaries.
+
+**Hard invariant.** Curation reads the NetworkX graph, communities, and
+centrality, but it *only ever writes the returned* :class:`KnowledgeGraphResult`.
+It never mutates ``graph_builder``'s graph, ``graph_edges``, centrality caches,
+community detection, or any DB table. There is a regression test that asserts the
+graph's node/edge counts are identical before and after this pass.
+
+Curation is feature-flagged (``REPOWISE_KG_CURATION``) and defaults **on**;
+the 38-repo cross-language validation matrix is the acceptance gate that
+flipped it. Setting the flag to ``0``/``false``/``no``/``off`` makes
+:func:`curate_knowledge_graph` a no-op that returns its input unchanged
+(the raw uncurated export).
+"""
+
+from __future__ import annotations
+
+import logging
+import os
+import re
+from collections import Counter, defaultdict
+from dataclasses import dataclass, field
+from pathlib import PurePosixPath
+from typing import Any
+
+from repowise.core.analysis.knowledge_graph import KnowledgeGraphResult, _slugify
+from repowise.core.generation.layers import (
+ ADJACENT_LAYERS,
+ compute_layer_order,
+ infer_layer,
+ is_support_path,
+ layer_order_basis,
+)
+from repowise.core.generation.tour import (
+ DEFAULT_MAX_STOPS,
+ build_tour,
+ score_entry_points,
+)
+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
+
+# Closing-stop anchors (conftest, spec_helper, test_helper, …) and
+# declaration descriptors (module-info.java) — both registry-declared.
+_SUITE_ANCHOR_STEMS: frozenset[str] = _LANG_REGISTRY.suite_anchor_stems()
+_DESCRIPTOR_FILENAMES: frozenset[str] = _LANG_REGISTRY.descriptor_filenames()
+# Test-fixture filename shapes (FooFixtures.java) — case-sensitive,
+# per-extension; fixture files hold test data, they never face the suite.
+_FIXTURE_CAMEL_RES = _LANG_REGISTRY.camel_fixture_res_by_extension()
+# Test-project dir suffixes (.Tests/.Specs) — when present, the suite's
+# face must come from inside one.
+_TEST_PROJECT_DIR_SUFFIXES: tuple[str, ...] = _LANG_REGISTRY.test_dir_suffixes()
+
+# Honest-degradation thresholds. Density = (imports + tested_by)
+# edges per dominant-language file — the same definition the validation
+# harness uses, calibrated on the 13-repo matrix: express (1.89, broken CJS
+# resolution) and sinatra (1.48, broken require resolution) land in
+# "sparse"; every healthy repo sits at ≥ 2.2. Repos below the file floor
+# skip the density check — density on a 7-file repo is noise, not evidence.
+# Low density alone stops indicting the resolver once the resolution rate
+# (internal targets / all targets) is strong: stdlib filtering makes an
+# honestly-resolved Ruby gem land at ~1.3 edges/file with 0.77 resolution —
+# that graph isn't lying, it's just require-light.
+_FLOW_DENSITY_FLOOR = 2.0
+_FLOW_RESOLUTION_FLOOR = 0.7
+_STRUCTURAL_DENSITY_FLOOR = 0.3
+_MODE_MIN_FILES = 25
+
+
+def _is_fixture_shaped(path: str) -> bool:
+ """True when the filename matches its language's fixture convention."""
+ pp = PurePosixPath(path)
+ fixture_re = _FIXTURE_CAMEL_RES.get(pp.suffix.lower())
+ return fixture_re is not None and fixture_re.search(pp.stem) is not None
+
+
+def _graph_mode(dominant_lang: str, lang_by_path: dict[str, str], graph_builder: Any) -> str:
+ """Classify how much the import graph can honestly claim.
+
+ ``flow`` — full resolver support and healthy density: the tour may
+ narrate execution flow.
+ ``sparse`` — partial support, or full support with suspiciously low
+ density: BFS still walks, but reasons must not blame
+ files for the resolver's gaps.
+ ``structural`` — no resolver (or a near-edgeless graph): no execution
+ claims at all; the tour walks the repo's structure.
+ """
+ support = _LANG_REGISTRY.import_support_for(dominant_lang)
+ if support == "none":
+ return "structural"
+ dom_files = {p for p, lang in lang_by_path.items() if lang == dominant_lang}
+ if not dom_files:
+ return "structural"
+ edge_count = 0
+ internal_targets = 0
+ external_targets = 0
+ try:
+ for src, dst, data in graph_builder.graph().edges(data=True):
+ if (data or {}).get("edge_type") in ("imports", "tested_by") and src in dom_files:
+ edge_count += 1
+ if isinstance(dst, str) and dst.startswith("external:"):
+ external_targets += 1
+ else:
+ internal_targets += 1
+ except Exception: # pragma: no cover - defensive
+ return "flow" if support == "full" else "sparse"
+ total = internal_targets + external_targets
+ resolution = (internal_targets / total) if total else 0.0
+ if len(dom_files) < _MODE_MIN_FILES:
+ # Density is unmeasurable on tiny repos, but resolution is not: a
+ # partial-tier repo whose imports resolve cleanly must not have its
+ # tour blame "incomplete import resolution" just for being small.
+ if support == "full" or (total and resolution >= _FLOW_RESOLUTION_FLOOR):
+ return "flow"
+ return "sparse"
+ density = edge_count / len(dom_files)
+ if density < _STRUCTURAL_DENSITY_FLOOR:
+ return "structural"
+ # Partial-tier languages run in flow or sparse per their REAL density
+ # and resolution, exactly like full-tier ones: a regex-tier resolver
+ # that resolves 0.95+ of an Elixir repo's aliases must not have its
+ # tour blame "incomplete import resolution" — that would be the lie
+ # this mode exists to prevent, inverted.
+ # Low density indicts the resolver only when resolution is ALSO
+ # weak — a require-light but well-resolved graph narrates honestly.
+ if density < _FLOW_DENSITY_FLOOR and resolution < _FLOW_RESOLUTION_FLOOR:
+ return "sparse"
+ return "flow"
+
+__all__ = [
+ "KGValidation",
+ "apply_summary_floor",
+ "build_portable_kg",
+ "curate_knowledge_graph",
+ "curation_enabled",
+ "derive_modules",
+ "validate_kg",
+]
+
+logger = logging.getLogger(__name__)
+
+
+_FLAG_ENV = "REPOWISE_KG_CURATION"
+
+# A primary layer larger than this many files, or spanning more than this many
+# distinct sub-directories, is given a two-level structure (primary → named
+# sub-groups) so a mega-layer like core/* or ui/* stays drill-down legible
+# instead of becoming one opaque bucket (plan §Phase 1, edge case B).
+_SUBSPLIT_FILE_THRESHOLD = 60
+_SUBSPLIT_DIR_THRESHOLD = 8
+
+# Hard bound on the curated primary-layer count. The spine is bounded ≤~11 by
+# construction; if a future change ever blows past this we degrade to the
+# uncurated layers rather than ship an unreadable list.
+_MAX_LAYERS = 15
+
+# Entry-point precision (plan §Phase 2). A re-export *barrel* (typically an
+# ``index.ts``) carries the ``index`` stem heuristic's ``entry_point`` flag but
+# teaches a reader nothing, so it is demoted in the presentation view. Runtime
+# entries that survive are ranked by ``pagerank + betweenness`` and the surfaced
+# set is capped — the full ranked list is kept as ``entry_candidates``.
+_BARREL_STEMS = frozenset({"index"})
+_SUBSTANTIVE_KINDS = frozenset(
+ {"function", "method", "class", "struct", "interface", "enum", "trait", "impl", "macro"}
+)
+_MAX_ENTRY_POINTS = 8
+
+
+def curation_enabled() -> bool:
+ """Whether KG curation is enabled via the ``REPOWISE_KG_CURATION`` env flag.
+
+ Defaults to **on** — the cross-language validation matrix (38 pinned
+ repos, enforced density/orphan/catch-all thresholds, honest degradation
+ modes) is the acceptance gate that flipped it. Set ``0``/``false``/``no``/
+ ``off`` (case-insensitive) to fall back to the raw uncurated export.
+ Resolved at the call site so :func:`curate_knowledge_graph` itself stays
+ pure and trivially testable with an explicit ``enabled=``.
+ """
+ return os.environ.get(_FLAG_ENV, "").strip().lower() not in {"0", "false", "no", "off"}
+
+
+def curate_knowledge_graph(
+ kg: KnowledgeGraphResult,
+ *,
+ parsed_files: list[Any],
+ graph_builder: Any,
+ repo_structure: Any,
+ community_info: Any,
+ enabled: bool = False,
+ defer_summary_floor: bool = False,
+) -> KnowledgeGraphResult:
+ """Reshape the KG skeleton into an intuitive presentation artifact.
+
+ Pure with respect to the AST graph: reads ``graph_builder`` /
+ ``community_info`` but writes only the returned result. When ``enabled`` is
+ ``False`` this is a strict no-op returning ``kg`` unchanged (the default, so
+ the exported KG is unaffected until the flag flips).
+
+ ``defer_summary_floor`` skips the never-empty summary floor here so it can
+ run *after* the wiki-page backfill in generate mode (where richer summaries
+ exist); FAST mode leaves it ``False`` so the floor still lands at this seam.
+
+ Each curation step is guarded so that a failure degrades to the prior
+ (uncurated) field rather than aborting the export.
+ """
+ if not enabled:
+ return kg
+
+ # Each step mutates only ``kg`` (the presentation result) and is guarded so
+ # a failure degrades to the prior, uncurated field rather than aborting the
+ # export. Steps are layered in by subsequent phases:
+ # _curate_layers -> _curate_entry_points -> _curate_tour
+ # -> _curate_node_types -> _curate_summaries
+ layers_curated = False
+ try:
+ curated = _curate_layers(kg, graph_builder)
+ if curated is not None:
+ kg.layers = curated
+ layers_curated = True
+ except Exception: # pragma: no cover - defensive; keep uncurated layers
+ logger.exception("kg_curation._curate_layers failed; keeping community layers")
+
+ # Wiki modules are a *sibling* artifact of the curated layers (same
+ # splitting machinery, module-sized granularity). Only derived when the
+ # spine landed — community layers would make the dir-split meaningless,
+ # and downstream consumers fall back to community grouping when this
+ # stays empty (the fallback matrix's "degraded" row).
+ if layers_curated:
+ try:
+ modules = _curate_modules(kg)
+ if modules is not None:
+ kg.modules = modules
+ except Exception: # pragma: no cover - defensive; ship no modules
+ logger.exception("kg_curation._curate_modules failed; exporting no modules")
+
+ try:
+ _curate_entry_points(kg, parsed_files, graph_builder)
+ except Exception: # pragma: no cover - defensive; keep skeleton entry points
+ logger.exception("kg_curation._curate_entry_points failed; keeping raw entry points")
+
+ try:
+ tour = _curate_tour(kg, parsed_files, graph_builder)
+ if tour is not None:
+ kg.tour = tour
+ except Exception: # pragma: no cover - defensive; keep skeleton/LLM tour
+ logger.exception("kg_curation._curate_tour failed; keeping existing tour")
+
+ try:
+ _curate_node_types(kg)
+ except Exception: # pragma: no cover - defensive; keep skeleton types
+ logger.exception("kg_curation._curate_node_types failed; keeping coarse types")
+
+ if not defer_summary_floor:
+ try:
+ apply_summary_floor(kg, parsed_files)
+ except Exception: # pragma: no cover - defensive; leave summaries as-is
+ logger.exception("kg_curation summary floor failed; leaving summaries empty")
+
+ return kg
+
+
+# ---------------------------------------------------------------------------
+# Phase 1 — curated layers (replace raw-community layers with the spine)
+# ---------------------------------------------------------------------------
+
+
+def _file_nodes(kg: KnowledgeGraphResult) -> list[dict]:
+ """Return the file-typed nodes of *kg* (ids prefixed ``file:``)."""
+ return [
+ n
+ for n in kg.nodes
+ if isinstance(n.get("id"), str)
+ and n["id"].startswith("file:")
+ and isinstance(n.get("filePath"), str)
+ ]
+
+
+def _file_import_edges(graph_builder: Any) -> list[tuple[str, str]]:
+ """``(src, dst)`` string edges from the AST graph (src imports dst).
+
+ ``imports`` edges only (hint-sourced ones included — they are import
+ semantics). The raw graph also carries ``contains`` (file → symbol),
+ ``co_change``, ``calls``, and heritage edges; letting those through made
+ "execution flow" claims ride on symbol counts and change-history
+ coupling — a giant declarations header would out-rank every real entry
+ as the walk's widest-fan-out anchor. Externals are naturally ignored
+ downstream by :func:`compute_layer_order`, which only counts edges whose
+ endpoints are both in ``file_layers``.
+ """
+ edges: list[tuple[str, str]] = []
+ try:
+ g = graph_builder.graph()
+ for src, dst, data in g.edges(data=True):
+ if not (isinstance(src, str) and isinstance(dst, str)):
+ continue
+ if data.get("edge_type", "imports") != "imports":
+ continue
+ edges.append((src, dst))
+ except Exception: # pragma: no cover - defensive
+ pass
+ return edges
+
+
+def _common_dir_prefix(seg_lists: list[tuple[str, ...]]) -> tuple[str, ...]:
+ """Longest common leading directory-segment prefix across *seg_lists*."""
+ if not seg_lists:
+ return ()
+ common = list(seg_lists[0])
+ for segs in seg_lists[1:]:
+ i = 0
+ while i < len(common) and i < len(segs) and common[i] == segs[i]:
+ i += 1
+ del common[i:]
+ if not common:
+ break
+ return tuple(common)
+
+
+def _sub_split(layer_id: str, node_ids: list[str], id_to_path: dict[str, str]) -> list[dict] | None:
+ """Two-level sub-groups for an oversized/wide primary layer, else ``None``.
+
+ Groups files by the first path segment that distinguishes them (the segment
+ after the layer's common directory prefix), so e.g. ``core/ingestion`` /
+ ``core/analysis`` / ``core/generation`` become named sub-groups. Only kicks
+ in past the size/width thresholds and only when it yields ≥2 groups.
+ """
+ if len(node_ids) < 2:
+ return None
+
+ dir_segs = {nid: PurePosixPath(id_to_path[nid]).parts[:-1] for nid in node_ids}
+ common = _common_dir_prefix(list(dir_segs.values()))
+
+ groups: dict[str, list[str]] = defaultdict(list)
+ for nid in node_ids:
+ segs = dir_segs[nid]
+ key = segs[len(common)] if len(segs) > len(common) else "(root)"
+ groups[key].append(nid)
+
+ oversized = len(node_ids) > _SUBSPLIT_FILE_THRESHOLD
+ wide = len(groups) > _SUBSPLIT_DIR_THRESHOLD
+ if not (oversized or wide) or len(groups) < 2:
+ return None
+
+ return [
+ {"id": f"{layer_id}:{_slugify(name)}", "name": name, "nodeIds": groups[name]}
+ for name in sorted(groups)
+ ]
+
+
+def _curate_layers(kg: KnowledgeGraphResult, graph_builder: Any) -> list[dict] | None:
+ """Build bounded, dependency-ordered layers from the ``infer_layer`` spine.
+
+ Returns the curated layer list, or ``None`` to keep the existing
+ (community) layers when the result would be degenerate or violate the
+ partition / bound invariants. Every file lands in exactly one layer, so the
+ partition (Σ nodeIds == file-node count) and singleton-elimination hold by
+ construction.
+ """
+ file_nodes = _file_nodes(kg)
+ if not file_nodes:
+ return None
+
+ id_to_path = {n["id"]: n["filePath"] for n in file_nodes}
+ file_layers = {
+ n["filePath"]: infer_layer(n["filePath"], (n.get("language") or "").lower())
+ for n in file_nodes
+ }
+ import_edges = _file_import_edges(graph_builder)
+ order = compute_layer_order(file_layers, import_edges)
+ # Honesty label (additive export field): "imports" when inter-layer edges
+ # informed the order, "canonical" when it is pure convention — consumers
+ # must not claim "X sits above Y" for a canonical order.
+ order_basis = layer_order_basis(file_layers, import_edges)
+
+ by_layer: dict[str, list[str]] = defaultdict(list)
+ for n in file_nodes:
+ by_layer[file_layers[n["filePath"]]].append(n["id"])
+
+ layers: list[dict] = []
+ for display_order, layer_name in enumerate(order):
+ node_ids = by_layer[layer_name]
+ layer_id = f"layer:{_slugify(layer_name)}"
+ layer: dict[str, Any] = {
+ "id": layer_id,
+ "name": layer_name,
+ "description": "",
+ "nodeIds": node_ids,
+ "display_order": display_order,
+ "order_basis": order_basis,
+ }
+ sub_groups = _sub_split(layer_id, node_ids, id_to_path)
+ if sub_groups:
+ layer["subGroups"] = sub_groups
+ layers.append(layer)
+
+ # Degrade rather than ship a broken artifact: enforce bound + partition.
+ total = sum(len(layer["nodeIds"]) for layer in layers)
+ if not layers or len(layers) > _MAX_LAYERS or total != len(file_nodes):
+ logger.warning(
+ "kg_curation: curated layers failed invariant "
+ "(count=%d, partition=%d/%d); keeping community layers",
+ len(layers),
+ total,
+ len(file_nodes),
+ )
+ return None
+ return layers
+
+
+# ---------------------------------------------------------------------------
+# Wiki modules — right-sized directory groups derived from the curated layers
+# ---------------------------------------------------------------------------
+
+# Granularity window for derived wiki modules. Sub-groups verbatim are NOT
+# module-sized (a 452-file ``core`` sub-group would make one vague mush of a
+# doc; a 1-file ``examples`` group would mint a confetti page), so the layer
+# node sets are split *recursively* by directory until every group fits the
+# window — bottoming out honestly on flat directories. ``target_max`` keeps
+# the 10 key-file template slots representative; ``target_min`` is the
+# merge-up floor below which a group folds into its nearest sibling.
+_MODULE_TARGET_MIN = 8
+_MODULE_TARGET_MAX = 120
+# A layer smaller than this yields no module at all (matches the selection
+# layer's ``min_module_size`` floor that kills singleton pages).
+_MODULE_MIN_FILES = 3
+# A directory segment present in more than this fraction of all repo paths is
+# *generic* (namespace dirs: ``src``, ``packages``, the repo's own name) and
+# never appears in a module name. Data-driven — no hardcoded segment list.
+_GENERIC_SEGMENT_FRACTION = 0.60
+# The legacy community labels' size-suffix dedupe ("ingestion (32)") is the
+# exact failure mode module names must never reproduce.
+_SIZE_SUFFIX_RE = re.compile(r"\(\d+\)\s*$")
+
+
+# Universal organizational directory names — containers, not domain labels.
+# Shared with community labeling; the data-driven ``dominant_segments`` set
+# complements this with per-repo namespace noise (the repo's own name).
+GENERIC_ORG_SEGMENTS = frozenset({
+ "src", "lib", "core", "common", "shared", "internal", "pkg",
+ "main", "app", "utils", "helpers", "index", "mod",
+ # Monorepo organisational directories
+ "packages", "modules", "workspace", "workspaces", "libs",
+ "projects", "services", "apps",
+})
+
+
+def dominant_segments(paths: list[str]) -> set[str]:
+ """Directory segments appearing in > 60% of *paths* (namespace noise).
+
+ Shared with community labeling (``analysis/communities.py``) so both
+ vocabularies strip the same namespace dirs (``src``, ``packages``, the
+ repo's own name) without depending on a hardcoded list.
+ """
+ n = len(paths)
+ if not n:
+ return set()
+ counts: Counter[str] = Counter()
+ for p in paths:
+ for seg in set(PurePosixPath(p).parts[:-1]):
+ counts[seg] += 1
+ return {s for s, c in counts.items() if c / n > _GENERIC_SEGMENT_FRACTION}
+
+
+def _split_to_granularity(
+ node_ids: list[str], id_to_path: dict[str, str], target_max: int
+) -> list[tuple[tuple[str, ...], list[str]]]:
+ """Recursively split *node_ids* by directory until groups fit *target_max*.
+
+ Returns ``[(dir_segments, sorted_node_ids), ...]``. Reuses ``_sub_split``'s
+ prefix logic (group by the first segment that distinguishes members after
+ the common directory prefix) but, unlike sub-groups, recurses into any
+ group still above ``target_max``. Recursion bottoms out when a directory
+ has no distinguishing subdirs — a 200-file flat dir stays one module
+ (honest), never an artificial split.
+ """
+ dir_segs = {nid: PurePosixPath(id_to_path[nid]).parts[:-1] for nid in node_ids}
+
+ def rec(ids: list[str]) -> list[tuple[tuple[str, ...], list[str]]]:
+ common = _common_dir_prefix([dir_segs[i] for i in ids])
+ if len(ids) <= target_max:
+ return [(common, ids)]
+ groups: dict[str, list[str]] = defaultdict(list)
+ for nid in ids:
+ segs = dir_segs[nid]
+ key = segs[len(common)] if len(segs) > len(common) else ""
+ groups[key].append(nid)
+ if len(groups) < 2:
+ return [(common, ids)] # flat directory — no honest split exists
+ out: list[tuple[tuple[str, ...], list[str]]] = []
+ for key in sorted(groups):
+ if key == "":
+ # Files sitting directly in the common dir (the "(root)"
+ # group). Usually below target_min → folded by merge-up.
+ out.append((common, groups[key]))
+ else:
+ out.extend(rec(groups[key]))
+ return out
+
+ return [(d, sorted(ids)) for d, ids in rec(sorted(node_ids))]
+
+
+def _merge_small_groups(
+ groups: list[tuple[tuple[str, ...], list[str]]], target_min: int
+) -> list[tuple[tuple[str, ...], list[str]]]:
+ """Fold groups below *target_min* into their nearest sibling.
+
+ "Nearest" = the group sharing the longest directory prefix (the parent
+ subtree), largest first as the tie-break — so a 2-file "(root)" remnant
+ folds into its own subtree's biggest module, and an isolated small dir
+ folds into the layer's dominant module rather than minting a confetti
+ page. Never merges across layers (callers pass one layer at a time). A
+ layer that is itself below ``target_min`` stays one whole group.
+
+ A pre-pass fuses *small sibling* groups into one group at their common
+ parent when that collection is itself module-sized — ninety tiny locale
+ dirs become one ``conf/locale`` module instead of folding into whichever
+ sibling sorts first and misnaming it. The fold-in loop then never renames
+ a survivor: a healthy ``core/providers`` absorbing a 2-file sibling keeps
+ its identity.
+ """
+ merged = [(d, list(ids)) for d, ids in groups]
+
+ by_parent: dict[tuple[str, ...], list[tuple[tuple[str, ...], list[str]]]] = {}
+ for g in merged:
+ if len(g[1]) < target_min and len(g[0]) > 0:
+ by_parent.setdefault(g[0][:-1], []).append(g)
+ for parent, sibs in sorted(by_parent.items()):
+ if len(sibs) < 2 or sum(len(g[1]) for g in sibs) < target_min:
+ continue
+ fused = sorted(nid for g in sibs for nid in g[1])
+ for g in sibs:
+ merged.remove(g)
+ existing = next((g for g in merged if g[0] == parent), None)
+ if existing is not None:
+ existing[1].extend(fused)
+ existing[1].sort()
+ else:
+ merged.append((parent, fused))
+ merged.sort(key=lambda g: g[0])
+
+ def shared(a: tuple[str, ...], b: tuple[str, ...]) -> int:
+ return len(_common_dir_prefix([a, b]))
+
+ while len(merged) > 1:
+ small = min(
+ (g for g in merged if len(g[1]) < target_min),
+ key=lambda g: (len(g[1]), g[0]),
+ default=None,
+ )
+ if small is None:
+ break
+ merged.remove(small)
+ target = min(
+ merged,
+ key=lambda g: (-shared(g[0], small[0]), -len(g[1]), g[0]),
+ )
+ target[1].extend(small[1])
+ target[1].sort()
+ return [(d, ids) for d, ids in merged]
+
+
+def _name_modules(mods: list[dict], generic: set[str]) -> None:
+ """Assign unique, human module names in place.
+
+ Initial name = the last one or two *informative* directory segments
+ (generic namespace segments stripped; when stripping consumes every
+ segment, the raw tail is used instead). Collisions extend leftward by
+ one more parent segment — NEVER a size suffix. Single-module layers
+ take the layer's name; the root group (empty dir) becomes
+ "<Layer> (top-level)". The absolute fallback (identical informative
+ paths across layers) appends the layer name, which is unique by
+ construction.
+ """
+ per_layer: Counter[str] = Counter(m["layerId"] for m in mods)
+ info_by: dict[int, list[str]] = {}
+ used: dict[int, int | None] = {} # informative segments consumed; None = fixed
+ for m in mods:
+ # Data-driven stripping can consume EVERY segment on fixture-dominated
+ # repos (aeson: tests/JSONTestSuite/test_parsing is >60% of all
+ # paths). The raw dir tail is still the honest name there —
+ # "(top-level)" would mislabel a real directory and collide across
+ # sibling groups (which trips the export degradation guard and ships
+ # no modules). Universal organizational dirs (pkg, src, packages…)
+ # stay excluded even in the fallback: "(top-level)" reads better than
+ # a container name, so it remains the name for true root groups.
+ info = [s for s in m["_dir"] if s not in generic] or [
+ s for s in m["_dir"] if s.lower() not in GENERIC_ORG_SEGMENTS
+ ]
+ info_by[id(m)] = info
+ if per_layer[m["layerId"]] == 1:
+ m["name"] = m["_layerName"]
+ used[id(m)] = None
+ elif not info:
+ m["name"] = f"{m['_layerName']} (top-level)"
+ used[id(m)] = None
+ else:
+ k = min(2, len(info))
+ m["name"] = "/".join(info[-k:])
+ used[id(m)] = k
+
+ for _ in range(16): # bounded: each round consumes ≥1 segment somewhere
+ names = Counter(m["name"] for m in mods)
+ colliding = [m for m in mods if names[m["name"]] > 1]
+ if not colliding:
+ return
+ progressed = False
+ for m in colliding:
+ k = used.get(id(m))
+ info = info_by[id(m)]
+ if k is not None and k < len(info):
+ used[id(m)] = k + 1
+ m["name"] = "/".join(info[-(k + 1) :])
+ progressed = True
+ if not progressed:
+ break
+
+ # Two all-organizational groups in one layer (a root remnant plus a
+ # "packages"-style container) would both read "<Layer> (top-level)" —
+ # the container's raw tail is the honest tiebreak.
+ names = Counter(m["name"] for m in mods)
+ for m in mods:
+ if names[m["name"]] > 1 and not info_by[id(m)] and m["_dir"]:
+ m["name"] = "/".join(m["_dir"][-min(2, len(m["_dir"])) :])
+
+ # Same informative dir in two layers (or no segments left): the layer
+ # name disambiguates — (dir, layer) is unique by construction.
+ names = Counter(m["name"] for m in mods)
+ for m in mods:
+ if names[m["name"]] > 1:
+ m["name"] = f"{m['name']} ({m['_layerName']})"
+
+ # Absolute backstop (two all-org dirs in one layer sharing a tail): the
+ # full dir path is unique per layer.
+ names = Counter(m["name"] for m in mods)
+ for m in mods:
+ if names[m["name"]] > 1 and m["_dir"]:
+ m["name"] = "/".join(m["_dir"])
+
+
+def derive_modules(
+ layers: list[dict],
+ id_to_path: dict[str, str],
+ *,
+ target_min: int = _MODULE_TARGET_MIN,
+ target_max: int = _MODULE_TARGET_MAX,
+ min_module_size: int = _MODULE_MIN_FILES,
+ lang_by_id: dict[str, str] | None = None,
+) -> list[dict]:
+ """Derive right-sized, stably-identified wiki modules from curated layers.
+
+ ``Module = {"id": "module:<dir-slug>", "name": <human>, "path": <dir or "">,
+ "layerId": ..., "nodeIds": [...], "language": ...}``
+
+ Properties (each one an edge case from the research pass):
+
+ - **Partition per layer**: every node of every layer ≥ ``min_module_size``
+ lands in exactly one module; layers below the floor yield none. Never
+ merges across layers.
+ - **Granularity**: recursive directory splitting to the
+ [``target_min``, ``target_max``] window; flat dirs stay one honest
+ module; sub-``target_min`` remnants merge up into their subtree.
+ - **Names**: informative path segments only (data-driven generic-segment
+ stripping kills ``src``/``packages``/repo-name automatically); collision
+ resolution extends the path leftward — never a size suffix.
+ - **Ids**: ``module:`` + slug of the real directory path — stable across
+ runs and under file adds/renames inside the dir; changes only when the
+ directory itself moves. ``path`` is the actual dir (not the slug) so
+ path-prefix child lookups (``target_path LIKE 'dir/%'``) work.
+ - **Files only**: operates on ids present in ``id_to_path`` — external
+ nodes never pollute a module.
+ - **Determinism**: sorted iteration throughout; same inputs → same bytes.
+ """
+ generic = dominant_segments(sorted(set(id_to_path.values())))
+
+ mods: list[dict] = []
+ for layer in layers:
+ node_ids = [nid for nid in layer.get("nodeIds", []) if nid in id_to_path]
+ if len(node_ids) < min_module_size:
+ continue
+ groups = _merge_small_groups(
+ _split_to_granularity(node_ids, id_to_path, target_max), target_min
+ )
+ for dir_parts, ids in sorted(groups):
+ mods.append(
+ {
+ "_dir": dir_parts,
+ "_layerName": layer.get("name", ""),
+ "path": "/".join(dir_parts),
+ "layerId": layer.get("id", ""),
+ "nodeIds": sorted(ids),
+ }
+ )
+
+ _name_modules(mods, generic)
+
+ # Ids: path-derived slugs; the bigger module keeps the plain id on the
+ # rare cross-layer dir collision (a dir whose files split across layers).
+ used_ids: set[str] = set()
+ for m in sorted(mods, key=lambda m: (-len(m["nodeIds"]), m["path"], m["layerId"])):
+ base = "module:" + _slugify(m["path"] or m["_layerName"])
+ mid = base
+ n = 1
+ while mid in used_ids:
+ mid = f"{base}--{_slugify(m['_layerName'])}" + ("" if n == 1 else f"-{n}")
+ n += 1
+ used_ids.add(mid)
+ m["id"] = mid
+
+ # A single-module layer is 1:1 with its layer page — mark it so page
+ # generation can skip the duplicate doc (the module stays in the
+ # artifact: canvas containers and the coverage invariant need it).
+ per_layer_count: Counter[str] = Counter(m["layerId"] for m in mods)
+
+ out: list[dict] = []
+ for m in mods:
+ module = {
+ "id": m["id"],
+ "name": m["name"],
+ "path": m["path"],
+ "layerId": m["layerId"],
+ "nodeIds": m["nodeIds"],
+ }
+ if per_layer_count[m["layerId"]] == 1:
+ module["wholeLayer"] = True
+ if lang_by_id is not None:
+ langs = Counter(
+ lang for nid in m["nodeIds"] if (lang := lang_by_id.get(nid, ""))
+ )
+ module["language"] = (
+ min(langs, key=lambda tag: (-langs[tag], tag)) if langs else ""
+ )
+ out.append(module)
+ return out
+
+
+def _curate_modules(kg: KnowledgeGraphResult) -> list[dict] | None:
+ """Derive wiki modules from the curated layers, or ``None`` on degradation.
+
+ Mirrors ``_curate_layers``' honest-degradation guard: a partition or
+ uniqueness violation ships *no* modules (consumers fall back to community
+ grouping) rather than a broken artifact.
+ """
+ file_nodes = _file_nodes(kg)
+ if not file_nodes:
+ return None
+ id_to_path = {n["id"]: n["filePath"] for n in file_nodes}
+ lang_by_id = {n["id"]: (n.get("language") or "").lower() for n in file_nodes}
+
+ modules = derive_modules(kg.layers, id_to_path, lang_by_id=lang_by_id)
+ if not modules:
+ return None
+
+ seen: set[str] = set()
+ for m in modules:
+ for nid in m["nodeIds"]:
+ if nid in seen or nid not in id_to_path:
+ logger.warning(
+ "kg_curation: derived modules failed partition invariant; "
+ "exporting no modules"
+ )
+ return None
+ seen.add(nid)
+ names = [m["name"] for m in modules]
+ ids = [m["id"] for m in modules]
+ if len(set(names)) != len(names) or len(set(ids)) != len(ids):
+ logger.warning(
+ "kg_curation: derived module names/ids not unique; exporting no modules"
+ )
+ return None
+ return modules
+
+
+# ---------------------------------------------------------------------------
+# Phase 2 — entry-point precision (demote barrels, rank + cap survivors)
+# ---------------------------------------------------------------------------
+
+
+def _is_barrel(parsed_file: Any) -> bool:
+ """True if *parsed_file* is a re-export barrel (``index`` shell, no runtime).
+
+ Conservative by design: a file is a barrel only when its stem is ``index``
+ and it defines no runtime-bearing symbol (function/class/method/…) — purely
+ re-exporting or empty. Anything that defines executable behaviour, even if
+ named ``index``, is kept as a genuine entry candidate.
+ """
+ fi = getattr(parsed_file, "file_info", None)
+ path = getattr(fi, "path", "")
+ if PurePosixPath(path).stem.lower() not in _BARREL_STEMS:
+ return False
+
+ symbols = getattr(parsed_file, "symbols", []) or []
+ if any(getattr(s, "kind", "") in _SUBSTANTIVE_KINDS for s in symbols):
+ return False
+
+ has_reexports = any(
+ getattr(imp, "is_reexport", False) for imp in getattr(parsed_file, "imports", []) or []
+ )
+ exports_only = bool(getattr(parsed_file, "exports", []))
+ return has_reexports or exports_only or not symbols
+
+
+def _dominant_language(code_langs: list[str]) -> str:
+ """Most common language, ties broken deterministically.
+
+ ``Counter.most_common`` breaks count ties by insertion order, which is
+ thread-completion-order nondeterministic here — and the result reaches
+ persisted output (``project.graph_mode`` plus tour prose). Tie-break by
+ count descending, then language name ascending, so the same KG always
+ yields the same dominant language regardless of ingestion ordering.
+ """
+ if not code_langs:
+ return ""
+ return min(Counter(code_langs).items(), key=lambda kv: (-kv[1], kv[0]))[0]
+
+
+def _curate_entry_points(
+ kg: KnowledgeGraphResult, parsed_files: list[Any], graph_builder: Any
+) -> None:
+ """Demote re-export barrels and surface a capped, ranked entry-point set.
+
+ Mutates only the presentation view: drops the ``entry_point`` *tag* from
+ barrel nodes (and adds a ``barrel`` tag) without touching the AST graph's
+ ``is_entry_point`` flag (the dead-code pass relies on it). Survivors are
+ ranked by ``pagerank + betweenness``; ``project.entry_points`` holds the top
+ few, ``project.entry_candidates`` the full ranked list. When ingestion
+ flagged no entries at all, the strong :func:`score_entry_points` scorers
+ (entry-style filenames) fill in, so the orientation panel never opens empty
+ on repos without a detectable main.
+ """
+ pf_by_path = {pf.file_info.path: pf for pf in parsed_files if getattr(pf, "file_info", None)}
+ lang_by_path = {n["filePath"]: (n.get("language") or "").lower() for n in _file_nodes(kg)}
+ pagerank = graph_builder.pagerank() or {}
+ try:
+ betweenness = graph_builder.betweenness_centrality() or {}
+ except Exception: # pragma: no cover - defensive
+ betweenness = {}
+
+ survivors: list[tuple[float, str]] = []
+ for node in kg.nodes:
+ nid = node.get("id", "")
+ if not (isinstance(nid, str) and nid.startswith("file:")):
+ continue
+ tags = node.get("tags") or []
+ if "entry_point" not in tags:
+ continue
+ path = node.get("filePath", "")
+ if infer_layer(path, node.get("language")) in ADJACENT_LAYERS or is_support_path(path):
+ # Test fixtures (a wsgi.py inside tests/) and sample programs
+ # (examples/*/main.go) may carry the ingestion flag, but they are
+ # not where a reader enters the system.
+ continue
+ pf = pf_by_path.get(path)
+ if pf is not None and _is_barrel(pf):
+ new_tags = [t for t in tags if t != "entry_point"]
+ if "barrel" not in new_tags:
+ new_tags.append("barrel")
+ node["tags"] = new_tags
+ continue
+ score = pagerank.get(path, 0.0) + betweenness.get(path, 0.0)
+ survivors.append((score, path))
+
+ if not survivors:
+ # No ingestion-flagged entries (or all were barrels): fall back to the
+ # strong filename scorers the tour seeds from (score >= 3 means an
+ # entry-style name or flag, never just shallow/high-PageRank).
+ for s, path in score_entry_points(parsed_files, pagerank):
+ if s < 3.0:
+ continue
+ if infer_layer(path, lang_by_path.get(path)) in ADJACENT_LAYERS or is_support_path(path):
+ continue
+ pf = pf_by_path.get(path)
+ if pf is not None and _is_barrel(pf):
+ continue
+ score = pagerank.get(path, 0.0) + betweenness.get(path, 0.0)
+ survivors.append((score, path))
+
+ # Highest score first; path as a stable, deterministic tie-break.
+ survivors.sort(key=lambda sp: (-sp[0], sp[1]))
+ ranked = [path for _, path in survivors]
+ kg.project["entry_points"] = ranked[:_MAX_ENTRY_POINTS]
+ kg.project["entry_candidates"] = ranked
+
+
+# ---------------------------------------------------------------------------
+# Phase 3 — canonical execution-flow tour
+# ---------------------------------------------------------------------------
+
+
+def _readme_overview_node(kg: KnowledgeGraphResult) -> dict | None:
+ """The best root-level README/overview file node, if one exists."""
+ best: dict | None = None
+ for n in _file_nodes(kg):
+ path = n["filePath"]
+ name = PurePosixPath(path).name.lower()
+ depth = len(PurePosixPath(path).parts) - 1
+ if not (name.startswith("readme") and depth <= 1):
+ continue
+ # Prefer the shallowest README (the repo-root one).
+ if best is None or depth < (len(PurePosixPath(best["filePath"]).parts) - 1):
+ best = n
+ return best
+
+
+def _best_in_layer(paths: list[str], rank: dict[str, float], pagerank: dict[str, float]) -> str:
+ """Highest-ranked path in a layer (entry score, then PageRank, then name)."""
+ return sorted(paths, key=lambda p: (-rank.get(p, 0.0), -pagerank.get(p, 0.0), p))[0]
+
+
+def _structural_walk(
+ universe: list[str],
+ type_by_path: dict[str, str],
+ dominant_lang: str,
+ pagerank: dict[str, float],
+ graph_builder: Any,
+ project_name: str = "",
+) -> tuple[list[str], dict[str, str]]:
+ """Anchor + directory faces for repos with no usable import graph.
+
+ No execution-flow claims: the anchor is ranked by whatever evidence
+ exists (PageRank over the full graph — co-change/dynamic edges included
+ — then fan-in, shallowness, path), never alphabetically-first-by-luck;
+ the walk visits the largest top-level code areas, one face each. Every
+ reason says what the evidence is and what is missing.
+ """
+ # Manifests (mix.exs, setup.py) are code-shaped but describe the
+ # project rather than implement it — never the place to start reading.
+ manifests = _LANG_REGISTRY.manifest_filenames()
+ code = [
+ p
+ for p in universe
+ if type_by_path.get(p) not in {"config", "document"}
+ and PurePosixPath(p).name not in manifests
+ ]
+ if not code:
+ return [], {}
+
+ fan_in: Counter[str] = Counter()
+ for _src, dst in _file_import_edges(graph_builder):
+ fan_in[dst] += 1
+
+ spec = _LANG_REGISTRY.get(dominant_lang)
+ display = spec.display_name if spec else (dominant_lang or "this language")
+
+ # Conventional names trump raw connectivity: an entry-named file
+ # (application.ex, Main.hs) or the project-named module (lib/jason.ex in
+ # jason — the library-main convention) is where a reader starts.
+ entry_names = _LANG_REGISTRY.entry_point_names()
+ project_stem = (project_name or "").lower()
+
+ def conventional(p: str) -> bool:
+ pp = PurePosixPath(p)
+ return pp.name in entry_names or (
+ bool(project_stem) and pp.stem.lower() == project_stem
+ )
+
+ anchor = min(
+ code,
+ key=lambda p: (
+ not conventional(p),
+ -pagerank.get(p, 0.0),
+ -fan_in.get(p, 0),
+ len(PurePosixPath(p).parts),
+ p,
+ ),
+ )
+ if PurePosixPath(anchor).name in entry_names:
+ anchor_reason = (
+ f"Named like an entry file — the conventional place {display} "
+ "execution starts. Import analysis isn't supported for "
+ f"{display} yet, so the walk follows the repo's structure."
+ )
+ elif conventional(anchor):
+ anchor_reason = (
+ "Named after the project — by convention the library's main "
+ f"module. Import analysis isn't supported for {display} yet, "
+ "so the walk follows the repo's structure."
+ )
+ else:
+ anchor_reason = (
+ "The best-connected file by the evidence available (change "
+ f"history and references). Import analysis isn't supported for "
+ f"{display} yet, so the walk follows the repo's structure."
+ )
+
+ groups: dict[str, list[str]] = defaultdict(list)
+ for p in code:
+ if p == anchor:
+ continue
+ parts = PurePosixPath(p).parts
+ groups[parts[0] if len(parts) > 1 else "."].append(p)
+
+ walk = [anchor]
+ reasons = {anchor: anchor_reason}
+ for d in sorted(groups, key=lambda d: (-len(groups[d]), d)):
+ face = min(
+ groups[d],
+ key=lambda p: (-pagerank.get(p, 0.0), len(PurePosixPath(p).parts), p),
+ )
+ n = len(groups[d])
+ label = "the repository root" if d == "." else f"{d}/"
+ count = f"{n} code files live here" if n != 1 else "1 code file lives here"
+ reasons[face] = f"The face of {label} — {count}."
+ walk.append(face)
+ return walk, reasons
+
+
+_FANOUT_GROUP_MIN = 3
+
+
+def _import_groups(
+ graph_builder: Any, edge_types: frozenset[str] = frozenset({"imports"})
+) -> dict[str, list[list[str]]]:
+ """Imports edges grouped per source by originating import statement.
+
+ A resolver fan-out (Go/JVM package import → every file in the package)
+ emits many edges that share one source and identical ``imported_names``
+ — semantically ONE import relationship. Groups of
+ ``>= _FANOUT_GROUP_MIN`` targets are treated as fan-outs; smaller
+ groups stay one-edge-one-relationship (multi-ext probes, pairs).
+ """
+ keyed: dict[tuple[str, tuple[str, ...]], list[str]] = defaultdict(list)
+ try:
+ for src, dst, data in graph_builder.graph().edges(data=True):
+ if not (isinstance(src, str) and isinstance(dst, str)):
+ continue
+ if data.get("edge_type", "imports") not in edge_types:
+ continue
+ # Stdlib/external imports say nothing about where a walk can
+ # go — only repo-internal relationships count.
+ if src.startswith("external:") or dst.startswith("external:"):
+ continue
+ names = tuple(sorted(data.get("imported_names") or ())) or (dst,)
+ keyed[(src, names)].append(dst)
+ except Exception: # pragma: no cover - defensive
+ return {}
+ groups: dict[str, list[list[str]]] = defaultdict(list)
+ for (src, _names), targets in keyed.items():
+ groups[src].append(targets)
+ return groups
+
+
+# The harness signal is "this test file *depends on* that one" — type
+# references and inheritance (a base test class) are exactly that evidence;
+# raw-graph type_use/heritage edges surface as plain imports in the export.
+_DEPENDENCY_EDGE_TYPES = frozenset({"imports", "type_use", "heritage"})
+
+
+def _import_pairs_excluding_fanout(graph_builder: Any) -> list[tuple[str, str]]:
+ """``(src, dst)`` dependency pairs with fan-out groups dropped."""
+ pairs: list[tuple[str, str]] = []
+ for src, target_groups in _import_groups(
+ graph_builder, edge_types=_DEPENDENCY_EDGE_TYPES
+ ).items():
+ for targets in target_groups:
+ if len(targets) >= _FANOUT_GROUP_MIN:
+ continue
+ pairs.extend((src, dst) for dst in targets)
+ return pairs
+
+
+def _anchor_fanout_rank(graph_builder: Any) -> dict[str, int]:
+ """Per-file count of distinct import *relationships* (fan-outs = 1).
+
+ The walk's anchor claims "its imports fan out the widest" — that must
+ mean import statements, not resolver edge multiplicity, or one Go
+ package import (15 sibling edges) out-ranks a file with a dozen real
+ dependencies and the anchor lands alphabetically-by-luck.
+ """
+ return {
+ src: len(target_groups)
+ for src, target_groups in _import_groups(graph_builder).items()
+ }
+
+
+def _curate_tour(
+ kg: KnowledgeGraphResult, parsed_files: list[Any], graph_builder: Any
+) -> list[dict] | None:
+ """Build one canonical, execution-flow tour over the curated layers.
+
+ Keeps the deterministic :func:`build_tour` ordering — README/overview
+ first, then the entry points and their import neighbourhood walking inward
+ (BFS depth) — so the tour follows how the program actually runs, not an
+ abstract stack walk. Layer coverage is preserved by *swapping* redundant
+ same-layer stops for representatives of uncovered runtime layers, never by
+ re-sorting the walk. Adjacent layers (tests) take no walk slots: the suite
+ gets a single closing stop before infrastructure. Step reasons state
+ evidence (entry point, import depth, layer anchor), not stack position.
+ Every step carries a ``layer_id`` mapping it to a curated layer; the LLM
+ may later rewrite step *prose* only.
+ """
+ file_nodes = _file_nodes(kg)
+ if not file_nodes:
+ return None
+
+ paths = [n["filePath"] for n in file_nodes]
+ type_by_path = {n["filePath"]: n.get("type", "file") for n in file_nodes}
+ lang_by_path = {n["filePath"]: (n.get("language") or "").lower() for n in file_nodes}
+ code_langs = [
+ lang
+ for p, lang in lang_by_path.items()
+ if lang and type_by_path.get(p) not in {"config", "document"}
+ ]
+ dominant_lang = _dominant_language(code_langs)
+ # How much may the tour honestly claim? Exported additively so
+ # consumers (UI, harness) can see the degradation level.
+ graph_mode = _graph_mode(dominant_lang, lang_by_path, graph_builder)
+ kg.project["graph_mode"] = graph_mode
+ file_layers = {p: infer_layer(p, lang_by_path.get(p)) for p in paths}
+ order = compute_layer_order(file_layers, _file_import_edges(graph_builder))
+
+ pagerank = graph_builder.pagerank() or {}
+ rank = {path: s for s, path in score_entry_points(parsed_files, pagerank)}
+ barrels = {
+ pf.file_info.path
+ for pf in parsed_files
+ if getattr(pf, "file_info", None) and _is_barrel(pf)
+ }
+
+ # Infra files (Docker/CI/etc.) close the tour; everything else is code.
+ infra_paths = [p for p in paths if type_by_path.get(p) in {"service", "pipeline"}]
+
+ # The overview step retargets to the root README — keep that file out of
+ # the walk so the tour never visits it twice. Tests and example programs
+ # are excluded from the walk universe *before* build_tour spends its step
+ # budget; otherwise a samples-heavy repo (express) fills the budget with
+ # stops that get filtered away afterwards.
+ readme = _readme_overview_node(kg)
+ overview_target = readme["filePath"] if readme is not None else None
+ walk_universe = [
+ p
+ for p in paths
+ if p != overview_target
+ and file_layers.get(p) not in ADJACENT_LAYERS
+ and not is_support_path(p)
+ and not PurePosixPath(p).parts[0].startswith(".") # dot-dir tooling
+ ]
+
+ project_name = kg.project.get("name") or "repository"
+ # In structural mode the BFS walk is withheld entirely (a fake flow over
+ # a near-edgeless graph is a lie); build_tour still selects the overview
+ # and infra stops.
+ base = build_tour(
+ parsed_files,
+ pagerank,
+ _file_import_edges(graph_builder),
+ file_page_paths=[] if graph_mode == "structural" else walk_universe,
+ infra_paths=infra_paths,
+ repo_name=project_name,
+ max_stops=DEFAULT_MAX_STOPS,
+ graph_mode=graph_mode,
+ anchor_rank=_anchor_fanout_rank(graph_builder),
+ )
+
+ overview = [s for s in base if s.kind == "overview"]
+ infra = [s for s in base if s.kind == "infra"]
+ base_code = {s.target_path: s for s in base if s.kind == "code"}
+ if not overview:
+ overview_target = None
+
+ by_layer: dict[str, list[str]] = defaultdict(list)
+ for p in paths:
+ by_layer[file_layers[p]].append(p)
+
+ # One closing stop per adjacent layer present (the test suite) — tests
+ # verify the system, they don't start it, so they never lead the walk.
+ # Face = the shallowest suite anchor when present (conftest /
+ # spec_helper / test_helper — registry-declared suite roots), else the
+ # best code file, else anything (never a stray Cargo.toml if avoidable).
+ #
+ # Shared test harness files — base classes and helpers imported by two
+ # or more other test files (AbstractFileSystemTest, BaseTestCase,
+ # SpecUtil) — are what the suite runs ON, not where tests start. Their
+ # heavy in-degree otherwise wins the pagerank tie-break on every repo
+ # with shared fixtures.
+ adjacent_paths = {
+ p for layer in ADJACENT_LAYERS for p in by_layer.get(layer, [])
+ }
+ # Fan-out groups (one import statement expanded to many sibling targets
+ # — Go/JVM package imports) are *not* evidence that a specific file is
+ # referenced: a chi root test "imports" every sibling test through the
+ # package fan-out. Only single-target import evidence counts here.
+ harness_in: Counter[str] = Counter()
+ for src, dst in _import_pairs_excluding_fanout(graph_builder):
+ if src != dst and src in adjacent_paths and dst in adjacent_paths:
+ harness_in[dst] += 1
+ closing_paths: list[str] = []
+ for layer in order:
+ cands = by_layer.get(layer)
+ if layer not in ADJACENT_LAYERS or not cands:
+ continue
+ anchors = sorted(
+ (p for p in cands if PurePosixPath(p).stem.lower() in _SUITE_ANCHOR_STEMS),
+ key=lambda p: (len(PurePosixPath(p).parts), p),
+ )
+ if anchors:
+ closing_paths.append(anchors[0])
+ continue
+ code_cands = [
+ p
+ for p in cands
+ if type_by_path.get(p) not in {"config", "document"}
+ # Declaration descriptors (module-info.java) are source files
+ # that describe a module, not tests — gson's shallow JPMS
+ # descriptor must never face the suite.
+ and PurePosixPath(p).name not in _DESCRIPTOR_FILENAMES
+ # Fixture-shaped files (FooFixtures.java) hold test data; the
+ # suite's face must be something that verifies behavior.
+ and not _is_fixture_shaped(p)
+ ]
+ # Drop harness files unless that would leave nothing. One
+ # single-target import from another test file is already harness
+ # evidence — leaf tests have zero (okio's CipherFactory.kt had
+ # exactly one cipher-test importer and still faced the suite).
+ non_harness = [p for p in code_cands if harness_in.get(p, 0) < 1]
+ if non_harness:
+ code_cands = non_harness
+ # When the repo declares test *projects* (.NET's Foo.Tests/ or
+ # Foo.Specs/ sibling-project convention), the suite lives there —
+ # a test/Shared/ helper dir next to them is auxiliary compile-time
+ # plumbing, not where a maintainer says tests start.
+ in_test_project = [
+ p
+ for p in code_cands
+ if any(
+ seg.endswith(_TEST_PROJECT_DIR_SUFFIXES) and len(seg) > 1
+ for seg in PurePosixPath(p).parts[:-1]
+ )
+ ]
+ if in_test_project:
+ code_cands = in_test_project
+ if code_cands:
+ # No suite anchor (non-pytest/rspec suites): prefer the repo's
+ # dominant language (gson's suite face is a .java, not a stray
+ # .proto), then the shallowest test-root file (django's
+ # tests/runtests.py), most-imported as the tie-break.
+ code_cands.sort(
+ key=lambda p: (
+ lang_by_path.get(p, "") != dominant_lang,
+ len(PurePosixPath(p).parts),
+ -pagerank.get(p, 0.0),
+ p,
+ )
+ )
+ closing_paths.append(code_cands[0])
+ else:
+ closing_paths.append(_best_in_layer(cands, rank, pagerank))
+
+ budget = max(0, DEFAULT_MAX_STOPS - len(overview) - len(closing_paths) - len(infra))
+ swapped_depth: dict[str, int] = {} # rep path -> depth of the slot it fills
+ structural_reasons: dict[str, str] = {}
+
+ if graph_mode == "structural":
+ # Structure, not flow: evidence-ranked anchor + one face per
+ # top-level code area. No layer-coverage swaps — the directory walk
+ # IS the diversity, and "most depended-on" claims need edges.
+ walk, structural_reasons = _structural_walk(
+ walk_universe,
+ type_by_path,
+ dominant_lang,
+ pagerank,
+ graph_builder,
+ project_name=project_name,
+ )
+ walk = walk[:budget]
+ else:
+ # The walk = build_tour's execution order minus adjacent-layer stops
+ # and example programs (documentation-by-code, not the system),
+ # truncated up front so later swaps land inside the kept window.
+ walk = [
+ s.target_path
+ for s in base
+ if s.kind == "code"
+ and s.target_path != overview_target
+ and file_layers.get(s.target_path) not in ADJACENT_LAYERS
+ and not is_support_path(s.target_path)
+ ]
+ walk = walk[:budget]
+
+ # --- Diversify for layer coverage (swap slots, never re-sort) -----
+ seen_layers: set[str] = set()
+ redundant_positions: list[int] = []
+ for i, p in enumerate(walk):
+ layer = file_layers.get(p)
+ if layer in seen_layers:
+ redundant_positions.append(i)
+ else:
+ seen_layers.add(layer)
+
+ uncovered = [
+ name for name in order if name not in seen_layers and name not in ADJACENT_LAYERS
+ ]
+ for layer in uncovered:
+ if not redundant_positions:
+ break
+ # Manifests (mix.exs, project.clj, Setup.lhs) are code-shaped
+ # but describe the project rather than implement it — never a
+ # layer's face, same rule as the structural anchor.
+ manifest_names = _LANG_REGISTRY.manifest_filenames()
+ candidates = [
+ p
+ for p in by_layer.get(layer, [])
+ if p not in walk
+ and p != overview_target
+ and not is_support_path(p)
+ and not PurePosixPath(p).parts[0].startswith(".") # never a layer face
+ and PurePosixPath(p).name not in manifest_names
+ ]
+ if not candidates:
+ continue
+ # A layer's face must be code. A layer holding only configs/docs
+ # (a plugins/ dir of JSON manifests) gets no manufactured stop —
+ # except Config itself, where "this is where configuration
+ # lives" is the point.
+ # Infra-language scripts (run-hlint.sh, deploy.sh) wire the
+ # project, they don't implement a layer — never its face.
+ infra_langs = _LANG_REGISTRY.infra_languages()
+ code_candidates = [
+ p
+ for p in candidates
+ if type_by_path.get(p) not in {"config", "document"}
+ and lang_by_path.get(p) not in infra_langs
+ ]
+ if not code_candidates and layer != "Config":
+ continue
+ rep = _best_in_layer(code_candidates or candidates, rank, pagerank)
+ pos = redundant_positions.pop()
+ replaced = base_code.get(walk[pos])
+ swapped_depth[rep] = replaced.depth if replaced is not None else 0
+ walk[pos] = rep
+ seen_layers.add(layer)
+
+ # --- Assemble the exported tour --------------------------------------
+ tour: list[dict] = []
+ order_n = 0
+
+ if overview:
+ order_n += 1
+ ov = overview[0].as_dict()
+ ov["order"] = order_n
+ if readme is not None:
+ ov["target_path"] = readme["filePath"]
+ ov["title"] = PurePosixPath(readme["filePath"]).name
+ ov["layer_id"] = f"layer:{_slugify(file_layers[readme['filePath']])}"
+ else:
+ ov["layer_id"] = None
+ tour.append(ov)
+
+ max_depth = 0
+ for p in walk:
+ order_n += 1
+ layer = file_layers.get(p, "")
+ step = base_code.get(p)
+ if p in structural_reasons:
+ depth = 0 # import depth is meaningless without an import graph
+ reason = structural_reasons[p]
+ elif p in swapped_depth:
+ depth = swapped_depth[p]
+ reason = f"The {layer} layer's anchor — its most depended-on file."
+ elif step is not None:
+ depth = step.depth
+ reason = step.reason
+ else: # pragma: no cover - walk paths come from base or swaps
+ depth = 0
+ reason = f"A key {layer} file on the walk from the entry points."
+ if p in barrels:
+ # A re-export shell may seed the walk (imports genuinely fan out
+ # from it), but it must not claim to be an execution entry point.
+ reason = "A re-export hub — the package's public surface fans out from here."
+ max_depth = max(max_depth, depth)
+ tour.append(
+ {
+ "order": order_n,
+ "target_path": p,
+ "page_type": "file_page",
+ "title": PurePosixPath(p).name,
+ "depth": depth,
+ "kind": "code",
+ "reason": reason,
+ "layer_id": f"layer:{_slugify(layer)}",
+ }
+ )
+
+ # Polyglot fairness: languages holding ≥20% of the code with
+ # their own test files get named in the closing-stop reason — the stop
+ # faces the dominant suite, but the others must not vanish.
+ lang_counts = Counter(code_langs)
+ total_code = sum(lang_counts.values()) or 1
+ test_langs = {
+ lang_by_path.get(p, "")
+ for layer in ADJACENT_LAYERS
+ for p in by_layer.get(layer, [])
+ }
+ other_suites = sorted(
+ spec.display_name
+ for tag, n in lang_counts.items()
+ if tag != dominant_lang
+ and n / total_code >= 0.20
+ and tag in test_langs
+ and (spec := _LANG_REGISTRY.get(tag)) is not None
+ )
+ closing_reason = "The test suite — how the system's behavior is verified."
+ if other_suites:
+ closing_reason = (
+ "The test suite — how the system's behavior is verified "
+ f"(the {' and '.join(other_suites)} test suite"
+ f"{'s' if len(other_suites) > 1 else ''} live"
+ f"{'' if len(other_suites) > 1 else 's'} alongside it)."
+ )
+
+ for p in closing_paths:
+ order_n += 1
+ layer = file_layers.get(p, "Test")
+ max_depth += 1
+ tour.append(
+ {
+ "order": order_n,
+ "target_path": p,
+ "page_type": "file_page",
+ "title": PurePosixPath(p).name,
+ "depth": max_depth,
+ "kind": "code",
+ "reason": closing_reason,
+ "layer_id": f"layer:{_slugify(layer)}",
+ }
+ )
+
+ for s in infra:
+ order_n += 1
+ step = s.as_dict()
+ step["order"] = order_n
+ step["layer_id"] = f"layer:{_slugify(file_layers.get(s.target_path, 'Config'))}"
+ tour.append(step)
+
+ return tour
+
+
+# ---------------------------------------------------------------------------
+# Phase 4 — node typing & never-empty summaries
+# ---------------------------------------------------------------------------
+
+# Path signals for richer node typing than the skeleton's coarse
+# file/config/service/document. These run only in the presentation view; the
+# AST graph node_type used elsewhere is untouched.
+_CI_PATH_MARKERS = (
+ ".github/workflows/",
+ ".gitlab-ci",
+ ".circleci/",
+ "azure-pipelines",
+ "jenkinsfile",
+ "bitbucket-pipelines",
+)
+_INFRA_NAME_MARKERS = ("dockerfile", "docker-compose", "compose.yaml", "compose.yml")
+_INFRA_PATH_MARKERS = ("/k8s/", "/kubernetes/", "/helm/", "/terraform/")
+_INFRA_SUFFIXES = (".tf", ".hcl")
+_DATA_PATH_MARKERS = ("/migrations/", "/migration/")
+_DATA_SUFFIXES = (".sql", ".prisma")
+
+# Source-code extensions. A code file is never CI/infra config however its
+# name or directory reads — ``languages/specs/dockerfile.py`` *parses*
+# Dockerfiles, it isn't one. Registry-derived: every is_code,
+# non-infra language's extensions are protected — .dart/.hs/.clj included;
+# shell/terraform stay promotable (they ARE infra); the historical orphan
+# ``.pl`` (no perl spec) is gone.
+_CODE_SUFFIXES = _LANG_REGISTRY.non_infra_code_extensions()
+
+
+def _enrich_type(path: str, current_type: str) -> tuple[str, str | None]:
+ """Return a richer ``(type, extra_tag)`` for a file node, or keep current.
+
+ The tag (``ci``/``infra``/``data``) is additive; ``None`` means no new tag.
+ Name/path markers never fire for source-code files (``_CODE_SUFFIXES``);
+ only genuine config artifacts get promoted.
+ """
+ p = path.lower()
+ name = PurePosixPath(p).name
+ suffix = PurePosixPath(p).suffix
+ is_code = suffix in _CODE_SUFFIXES
+
+ if not is_code and (any(m in p for m in _CI_PATH_MARKERS) or name == "jenkinsfile"):
+ return "pipeline", "ci"
+ if (
+ not is_code
+ and (
+ name.startswith("dockerfile")
+ or any(m in name for m in _INFRA_NAME_MARKERS)
+ or any(m in p for m in _INFRA_PATH_MARKERS)
+ )
+ ) or suffix in _INFRA_SUFFIXES:
+ return "service", "infra"
+ if any(m in p for m in _DATA_PATH_MARKERS) or suffix in _DATA_SUFFIXES:
+ return "schema", "data"
+ return current_type, None
+
+
+def _curate_node_types(kg: KnowledgeGraphResult) -> None:
+ """Promote infra/CI/data file nodes to first-class presentation types."""
+ for node in _file_nodes(kg):
+ new_type, tag = _enrich_type(node["filePath"], node.get("type", "file"))
+ if new_type != node.get("type"):
+ node["type"] = new_type
+ if tag:
+ tags = node.setdefault("tags", [])
+ if tag not in tags:
+ tags.append(tag)
+
+
+def _infer_test_target(path: str) -> str:
+ """Best-effort name of what a test file covers (strip test markers)."""
+ stem = PurePosixPath(path).stem
+ for marker in (".test", ".spec", "_test", "test_", "_spec", "spec_"):
+ if marker in stem.lower():
+ cleaned = stem.lower().replace(marker, "")
+ return cleaned.strip("_.- ") or stem
+ return stem
+
+
+def _cheap_summary(node: dict, parsed_file: Any | None) -> str:
+ """A deterministic, honest fallback summary (zero LLM cost)."""
+ path = node["filePath"]
+ stem = PurePosixPath(path).stem
+ parent = PurePosixPath(path).parent.name or "root"
+ node_type = node.get("type", "file")
+ tags = node.get("tags") or []
+ layer = infer_layer(path, (node.get("language") or "").lower())
+
+ if "barrel" in tags:
+ return f"Re-export barrel for {parent}/."
+ if node_type == "pipeline" or "ci" in tags:
+ return f"CI / pipeline definition: {PurePosixPath(path).name}."
+ if node_type == "service" or "infra" in tags:
+ return f"Infrastructure definition: {PurePosixPath(path).name}."
+ if node_type == "schema" or "data" in tags:
+ return f"Data / schema definition: {PurePosixPath(path).name}."
+ if node_type == "config" or "config" in tags:
+ return f"Configuration file: {PurePosixPath(path).name}."
+ if node_type == "document":
+ return f"Documentation: {PurePosixPath(path).name}."
+ if "test" in tags:
+ return f"Tests for {_infer_test_target(path)}."
+
+ # Code file: name the layer and its most prominent symbols.
+ symbol_names: list[str] = []
+ if parsed_file is not None:
+ symbol_names = [
+ getattr(s, "name", "")
+ for s in (getattr(parsed_file, "symbols", []) or [])
+ if getattr(s, "kind", "") in _SUBSTANTIVE_KINDS and getattr(s, "name", "")
+ ][:3]
+ if symbol_names:
+ return f"{layer} module {stem} defining {', '.join(symbol_names)}."
+ count = node.get("symbolCount", 0)
+ if count:
+ return f"{layer} module {stem} ({count} symbols)."
+ return f"{layer} module {stem}."
+
+
+def apply_summary_floor(kg: KnowledgeGraphResult, parsed_files: list[Any] | None = None) -> None:
+ """Ensure every file node carries a summary (cheap deterministic floor).
+
+ Idempotent and never clobbering: only fills nodes whose summary is still
+ empty, so a richer wiki-page summary (backfilled before this runs in
+ generate mode) always wins. ``parsed_files`` is optional — when absent the
+ fallback uses the node's symbol count instead of naming top symbols.
+ """
+ pf_by_path = {
+ pf.file_info.path: pf for pf in (parsed_files or []) if getattr(pf, "file_info", None)
+ }
+ for node in _file_nodes(kg):
+ if node.get("summary"):
+ continue
+ node["summary"] = _cheap_summary(node, pf_by_path.get(node["filePath"]))
+
+
+# ---------------------------------------------------------------------------
+# Phase 7 — invariant validation (shared by tests and the portable writer)
+# ---------------------------------------------------------------------------
+
+# Quality thresholds. The lower layer bound and coverage targets are *soft*
+# (warnings) because they depend on repo size/shape; the partition, hard count
+# bound, capped entry set, never-empty summaries, and tour budget are *hard*.
+_MIN_LAYERS = 6
+_MAX_LAYER_FRACTION = 0.35
+_MAX_CATCHALL_FRACTION = 0.20
+_MAX_SINGLETON_FRACTION = 0.10
+_MIN_TOUR_COVERAGE = 0.90
+
+
+@dataclass
+class KGValidation:
+ """Outcome of :func:`validate_kg` — hard errors, soft warnings, metrics."""
+
+ ok: bool
+ errors: list[str] = field(default_factory=list)
+ warnings: list[str] = field(default_factory=list)
+ metrics: dict[str, Any] = field(default_factory=dict)
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "ok": self.ok,
+ "errors": self.errors,
+ "warnings": self.warnings,
+ "metrics": self.metrics,
+ }
+
+
+def validate_kg(kg: KnowledgeGraphResult) -> KGValidation:
+ """Validate a curated KG against the intuitiveness invariants (plan §5/§7).
+
+ Pure and side-effect free. Hard violations set ``ok=False`` and populate
+ ``errors``; size/shape-dependent shortfalls go to ``warnings``. The
+ ``metrics`` block is the per-repo intuitiveness scorecard.
+ """
+ errors: list[str] = []
+ warnings: list[str] = []
+
+ file_nodes = _file_nodes(kg)
+ file_count = len(file_nodes)
+ file_ids = {n["id"] for n in file_nodes}
+ tags_by_path = {n["filePath"]: (n.get("tags") or []) for n in file_nodes}
+ summary_by_id = {n["id"]: n.get("summary") for n in file_nodes}
+
+ layers = kg.layers or []
+ n_layers = len(layers)
+
+ # -- Layer count -------------------------------------------------------
+ if n_layers == 0:
+ errors.append("no layers")
+ elif n_layers > _MAX_LAYERS:
+ errors.append(f"too many layers: {n_layers} > {_MAX_LAYERS}")
+ elif n_layers < _MIN_LAYERS:
+ warnings.append(f"few layers: {n_layers} < {_MIN_LAYERS} (small/flat repo?)")
+
+ # -- Partition ---------------------------------------------------------
+ layered: list[str] = [nid for layer in layers for nid in layer.get("nodeIds", [])]
+ layered_set = set(layered)
+ if len(layered) != len(layered_set):
+ errors.append("partition: a file appears in more than one layer")
+ if file_count and layered_set != file_ids:
+ missing = len(file_ids - layered_set)
+ extra = len(layered_set - file_ids)
+ errors.append(f"partition: {missing} unlayered, {extra} unknown ids")
+
+ # -- Singleton spam & mega-layer balance -------------------------------
+ sizes = [len(layer.get("nodeIds", [])) for layer in layers]
+ singleton_frac = (sum(1 for s in sizes if s == 1) / n_layers) if n_layers else 0.0
+ if singleton_frac >= _MAX_SINGLETON_FRACTION:
+ warnings.append(f"singleton layers {singleton_frac:.0%} ≥ {_MAX_SINGLETON_FRACTION:.0%}")
+
+ largest_frac = (max(sizes) / file_count) if (sizes and file_count) else 0.0
+ if largest_frac > _MAX_LAYER_FRACTION:
+ warnings.append(f"largest layer {largest_frac:.0%} > {_MAX_LAYER_FRACTION:.0%}")
+
+ catchall = next((layer for layer in layers if layer.get("name") == "Application"), None)
+ catchall_frac = (
+ (len(catchall.get("nodeIds", [])) / file_count) if (catchall and file_count) else 0.0
+ )
+ if catchall_frac > _MAX_CATCHALL_FRACTION:
+ warnings.append(f"Application catch-all {catchall_frac:.0%} > {_MAX_CATCHALL_FRACTION:.0%}")
+
+ # -- Entry points ------------------------------------------------------
+ entry_points = kg.project.get("entry_points", []) if isinstance(kg.project, dict) else []
+ if len(entry_points) > _MAX_ENTRY_POINTS:
+ errors.append(f"too many entry points: {len(entry_points)} > {_MAX_ENTRY_POINTS}")
+ barrels_surfaced = [p for p in entry_points if "barrel" in tags_by_path.get(p, [])]
+ if barrels_surfaced:
+ errors.append(f"barrels surfaced as entry points: {barrels_surfaced}")
+
+ # -- Tour --------------------------------------------------------------
+ tour = kg.tour or []
+ tour_coverage = 0.0
+ if tour:
+ if len(tour) > DEFAULT_MAX_STOPS:
+ errors.append(f"tour too long: {len(tour)} > {DEFAULT_MAX_STOPS}")
+ if tour[0].get("kind") != "overview":
+ errors.append("tour does not open with an overview/README step")
+ layer_ids = {layer.get("id") for layer in layers}
+ covered = {
+ s.get("layer_id")
+ for s in tour
+ if s.get("kind") != "overview" and s.get("layer_id") in layer_ids
+ }
+ tour_coverage = (len(covered) / len(layer_ids)) if layer_ids else 0.0
+ if tour_coverage < _MIN_TOUR_COVERAGE:
+ warnings.append(f"tour covers {tour_coverage:.0%} of layers < {_MIN_TOUR_COVERAGE:.0%}")
+
+ # -- Modules (only when the curated artifact carries them) -------------
+ modules = getattr(kg, "modules", None) or []
+ module_covered: set[str] = set()
+ if modules:
+ module_member_lists = [m.get("nodeIds", []) for m in modules]
+ flat = [nid for ids in module_member_lists for nid in ids]
+ module_covered = set(flat)
+ if len(flat) != len(module_covered):
+ errors.append("modules: a file appears in more than one module")
+ if not module_covered <= file_ids:
+ errors.append(
+ f"modules: {len(module_covered - file_ids)} unknown ids in modules"
+ )
+ module_names = [m.get("name", "") for m in modules]
+ if len(set(module_names)) != len(module_names):
+ errors.append("modules: names not unique")
+ size_suffixed = [n for n in module_names if _SIZE_SUFFIX_RE.search(n)]
+ if size_suffixed:
+ errors.append(f"modules: size-suffixed names: {size_suffixed}")
+ oversized = sum(
+ 1 for ids in module_member_lists if len(ids) > _MODULE_TARGET_MAX
+ )
+ if oversized:
+ # Flat dirs may honestly exceed the window — soft signal only.
+ warnings.append(f"{oversized} modules above target_max (flat dirs?)")
+
+ # -- Summaries ---------------------------------------------------------
+ empty_summaries = [nid for nid, s in summary_by_id.items() if not s]
+ if empty_summaries:
+ errors.append(f"{len(empty_summaries)} file nodes have an empty summary")
+ summary_completeness = 1.0 - len(empty_summaries) / file_count if file_count else 1.0
+
+ metrics = {
+ "file_count": file_count,
+ "layer_count": n_layers,
+ "module_count": len(modules),
+ "module_coverage_pct": round(
+ (len(module_covered) / file_count * 100) if (modules and file_count) else 0.0, 1
+ ),
+ "singleton_layer_pct": round(singleton_frac * 100, 1),
+ "largest_layer_pct": round(largest_frac * 100, 1),
+ "application_pct": round(catchall_frac * 100, 1),
+ "entry_point_count": len(entry_points),
+ "tour_steps": len(tour),
+ "tour_coverage_pct": round(tour_coverage * 100, 1),
+ "summary_completeness_pct": round(summary_completeness * 100, 1),
+ }
+
+ return KGValidation(ok=not errors, errors=errors, warnings=warnings, metrics=metrics)
+
+
+# ---------------------------------------------------------------------------
+# Phase 6 — portable, self-validated export artifact
+# ---------------------------------------------------------------------------
+
+
+def build_portable_kg(kg: KnowledgeGraphResult) -> tuple[dict, KGValidation]:
+ """Assemble a self-contained, self-validated ``knowledge-graph.json`` dict.
+
+ Kept separate from :meth:`KnowledgeGraphResult.to_dict` so the *default*
+ export stays byte-identical (curation flag-off contract); the portable
+ artifact adds a ``meta`` block (counts, fingerprint) and an embedded
+ ``validation`` report so an external consumer can trust it without a server.
+ Returns ``(data, validation)`` so the writer can decide on hard violations.
+ """
+ data = kg.to_dict()
+ validation = validate_kg(kg)
+ data["meta"] = {
+ "schema_version": data.get("version", "1.0.0"),
+ "generator": "repowise-kg-curation",
+ "fingerprint": getattr(kg, "fingerprint", ""),
+ "file_count": validation.metrics.get("file_count", 0),
+ "layer_count": validation.metrics.get("layer_count", 0),
+ "module_count": validation.metrics.get("module_count", 0),
+ "entry_point_count": validation.metrics.get("entry_point_count", 0),
+ "tour_steps": validation.metrics.get("tour_steps", 0),
+ "validation": validation.as_dict(),
+ }
+ return data, validation
diff --git a/packages/core/src/repowise/core/analysis/knowledge_graph.py b/packages/core/src/repowise/core/analysis/knowledge_graph.py
index 4d7cba4b0..573412076 100644
--- a/packages/core/src/repowise/core/analysis/knowledge_graph.py
+++ b/packages/core/src/repowise/core/analysis/knowledge_graph.py
@@ -25,17 +25,54 @@ class KnowledgeGraphResult:
edges: list[dict] = field(default_factory=list)
layers: list[dict] = field(default_factory=list)
tour: list[dict] = field(default_factory=list)
+ # Curated wiki modules (``derive_modules`` in kg_curation): right-sized
+ # directory groups with stable path-derived ids. Only the curated export
+ # populates this; empty means the key is omitted from ``to_dict`` so the
+ # flag-off artifact stays byte-identical.
+ modules: list[dict] = field(default_factory=list)
fingerprint: str = ""
def to_dict(self) -> dict:
- return {
+ # Canonical ordering: node/edge/layer-member lists carry no semantic
+ # order, but file-traversal and graph-insertion order vary run to
+ # run. Sorting here makes the exported artifact byte-stable across
+ # identical runs (baseline diffs, fingerprint reuse, clean diffs).
+ nodes = sorted(self.nodes, key=lambda n: str(n.get("id", "")))
+ edges = sorted(
+ self.edges,
+ key=lambda e: (
+ str(e.get("source", "")),
+ str(e.get("target", "")),
+ str(e.get("type", "")),
+ ),
+ )
+ def _canonical_layer(layer: dict) -> dict:
+ out = {**layer, "nodeIds": sorted(layer.get("nodeIds", []))}
+ if isinstance(layer.get("subGroups"), list):
+ out["subGroups"] = [
+ {**sg, "nodeIds": sorted(sg.get("nodeIds", []))}
+ if isinstance(sg, dict)
+ else sg
+ for sg in layer["subGroups"]
+ ]
+ return out
+
+ layers = [_canonical_layer(layer) for layer in self.layers]
+ out = {
"version": "1.0.0",
"project": self.project,
- "nodes": self.nodes,
- "edges": self.edges,
- "layers": self.layers,
+ "nodes": nodes,
+ "edges": edges,
+ "layers": layers,
"tour": self.tour,
}
+ if self.modules:
+ # Additive key: present only when curation derived modules, so
+ # the uncurated export's byte shape is unchanged.
+ out["modules"] = [
+ {**m, "nodeIds": sorted(m.get("nodeIds", []))} for m in self.modules
+ ]
+ return out
@classmethod
def from_file(cls, path: Path) -> KnowledgeGraphResult | None:
@@ -50,6 +87,7 @@ class KnowledgeGraphResult:
edges=data.get("edges", []),
layers=data.get("layers", []),
tour=data.get("tour", []),
+ modules=data.get("modules", []),
)
@@ -71,6 +109,8 @@ _INFRA_NAMES = frozenset({
"vagrantfile", "procfile",
})
+_INFRA_LANGUAGES = frozenset({"dockerfile", "makefile"})
+
_DOC_EXTENSIONS = frozenset({
".md", ".rst", ".txt", ".adoc",
})
@@ -82,7 +122,14 @@ def _classify_file_type(path: str, language: str, is_config: bool) -> str:
if is_config or ext in _CONFIG_EXTENSIONS:
return "config"
- if ext in _INFRA_EXTENSIONS or stem in _INFRA_NAMES:
+ # Infra names only count for extension-less files (Dockerfile, Makefile)
+ # or when ingestion parsed the file as an infra language — a Python module
+ # *named* dockerfile.py is code, not infrastructure.
+ if (
+ ext in _INFRA_EXTENSIONS
+ or language in _INFRA_LANGUAGES
+ or (not ext and stem in _INFRA_NAMES)
+ ):
return "service"
if ext in _DOC_EXTENSIONS:
return "document"
@@ -250,13 +297,22 @@ def build_knowledge_graph_skeleton(
continue
seen_edges.add(edge_key)
- edges.append({
+ edge_dict = {
"source": source_id,
"target": target_id,
"type": kg_type,
"direction": "forward",
"weight": data.get("confidence", 1.0),
- })
+ }
+ # Additive provenance marker: edges synthesised from convention
+ # passes (e.g. JVM same-package references) carry their origin so
+ # density metrics can separate them from declared imports and any
+ # false positive is diagnosable at the source. Key absent for
+ # regular declared-import edges.
+ hint = data.get("hint_source")
+ if hint:
+ edge_dict["hint"] = hint
+ edges.append(edge_dict)
# ---- Layers (from communities) ---------------------------------------
layers_by_id: dict[str, dict] = {}
diff --git a/packages/core/src/repowise/core/generation/context/assembler.py b/packages/core/src/repowise/core/generation/context/assembler.py
index 75192e735..a1eb25225 100644
--- a/packages/core/src/repowise/core/generation/context/assembler.py
+++ b/packages/core/src/repowise/core/generation/context/assembler.py
@@ -201,6 +201,7 @@ class ContextAssembler:
community_cohesion=community_cohesion,
decision_records=decision_records or [],
kg_layer_name=kg_context.layer_name if kg_context else "",
+ kg_layer_id=kg_context.layer_id if kg_context else "",
kg_layer_description=kg_context.layer_description if kg_context else "",
kg_layer_role=kg_context.role if kg_context else "",
kg_neighbors=kg_context.neighbors if kg_context else [],
diff --git a/packages/core/src/repowise/core/generation/context/contexts.py b/packages/core/src/repowise/core/generation/context/contexts.py
index 44cf9f2f8..5ae2ebbf4 100644
--- a/packages/core/src/repowise/core/generation/context/contexts.py
+++ b/packages/core/src/repowise/core/generation/context/contexts.py
@@ -53,6 +53,9 @@ class FilePageContext:
decision_records: list[dict] = field(default_factory=list)
# KG layer context (populated when knowledge graph available)
kg_layer_name: str = ""
+ # Stable slug id of the layer (``layer:<slug>``) — used to join a file
+ # page to its layer page; ``kg_layer_name`` is the mutable display label.
+ kg_layer_id: str = ""
kg_layer_description: str = ""
kg_layer_role: str = ""
kg_neighbors: list[dict] = field(default_factory=list)
@@ -106,6 +109,9 @@ class LayerPageContext:
layer_name: str
layer_description: str
file_count: int
+ # Stable slug id (``layer:<slug>``) — the layer page's target_path and
+ # page_id derive from this, never from the mutable ``layer_name``.
+ layer_id: str = ""
key_files: list[dict] = field(default_factory=list)
deps_out: list[dict] = field(default_factory=list)
deps_in: list[dict] = field(default_factory=list)
diff --git a/packages/core/src/repowise/core/generation/kg_context.py b/packages/core/src/repowise/core/generation/kg_context.py
index 52c16fcc6..031870994 100644
--- a/packages/core/src/repowise/core/generation/kg_context.py
+++ b/packages/core/src/repowise/core/generation/kg_context.py
@@ -23,6 +23,10 @@ class KGFileContext:
layer_name: str
layer_description: str
role: str # "entry_point" | "internal" | "edge_connector"
+ # Stable slug identity of the layer (``layer:<slug>``), distinct from the
+ # mutable ``layer_name`` the LLM enrichment may rewrite. Page keys and
+ # joins use this so they survive layer renames.
+ layer_id: str = ""
neighbors: list[dict] = field(default_factory=list)
tour_step: dict | None = None
tags: list[str] = field(default_factory=list)
@@ -32,16 +36,32 @@ class KGFileContext:
class KnowledgeGraphContext:
"""Index a knowledge-graph.json for fast per-file lookups during generation."""
- def __init__(self, kg_path: Path | None, repo_root: Path | None = None):
+ def __init__(
+ self,
+ kg_path: Path | None,
+ repo_root: Path | None = None,
+ *,
+ data: dict | None = None,
+ ):
self._file_to_layer: dict[str, dict] = {}
self._file_to_tour: dict[str, dict] = {}
self._file_to_node: dict[str, dict] = {}
self._layers: list[dict] = []
+ self._modules: list[dict] = []
self._tour: list[dict] = []
+ self._project: dict = {}
self._edges_by_source: dict[str, list[dict]] = {}
self._edges_by_target: dict[str, list[dict]] = {}
self._loaded = False
- if kg_path and kg_path.exists():
+ if data is not None:
+ # In-memory KG (the pipeline result's export dict). The artifact
+ # file is only written during persistence — AFTER generation — so
+ # a fresh init has no file to read and silently lost every
+ # kg_ctx-derived page (layer pages, tour context, file layers).
+ if repo_root is None and kg_path is not None:
+ repo_root = kg_path.parent.parent
+ self._index(data, repo_root or Path())
+ elif kg_path and kg_path.exists():
self._load(kg_path, repo_root)
@property
@@ -58,7 +78,9 @@ class KnowledgeGraphContext:
if repo_root is None:
repo_root = path.parent.parent
+ self._index(kg, repo_root)
+ def _index(self, kg: dict, repo_root: Path) -> None:
for node in kg.get("nodes", []):
fp = node.get("filePath", "")
if fp:
@@ -72,13 +94,23 @@ class KnowledgeGraphContext:
if fp not in self._file_to_layer:
self._file_to_layer[fp] = layer
+ self._project = kg.get("project") or {}
+ # Curated wiki modules (additive key; absent on uncurated artifacts).
+ self._modules = kg.get("modules", [])
self._tour: list[dict] = kg.get("tour", [])
for step in self._tour:
- for node_id in step.get("nodeIds", []):
- if node_id.startswith("file:"):
- fp = node_id[5:]
- if (repo_root / fp).exists():
- self._file_to_tour[fp] = step
+ # Curated tour steps carry a single target_path; the older shape
+ # listed nodeIds. Accept both.
+ paths = [
+ node_id[5:]
+ for node_id in step.get("nodeIds", [])
+ if node_id.startswith("file:")
+ ]
+ if step.get("target_path"):
+ paths.append(step["target_path"])
+ for fp in paths:
+ if (repo_root / fp).exists():
+ self._file_to_tour[fp] = step
for edge in kg.get("edges", []):
src = edge.get("source", "")
@@ -132,11 +164,14 @@ class KnowledgeGraphContext:
return KGFileContext(
layer_name=layer.get("name", ""),
+ layer_id=layer.get("id", ""),
layer_description=layer.get("description", ""),
role=role,
neighbors=neighbors[:10],
tour_step={"order": tour["order"], "title": tour["title"],
- "description": tour["description"][:300]} if tour else None,
+ # Curated steps state their evidence in "reason".
+ "description": (tour.get("description") or tour.get("reason") or "")[:300]}
+ if tour else None,
tags=node.get("tags", []),
node_summary=node.get("summary", ""),
)
@@ -144,9 +179,21 @@ class KnowledgeGraphContext:
def get_layers(self) -> list[dict]:
return self._layers if self._loaded else []
+ def get_modules(self) -> list[dict]:
+ """Curated wiki modules from the KG artifact (empty when uncurated)."""
+ return self._modules if self._loaded else []
+
def get_tour(self) -> list[dict]:
return self._tour if self._loaded else []
+ def get_graph_mode(self) -> str | None:
+ """The curation pass's honesty mode (flow/sparse/structural).
+
+ Only the curated export writes ``project.graph_mode`` — its presence
+ is the marker that the KG (and its tour) went through curation.
+ """
+ return self._project.get("graph_mode") if self._loaded else None
+
def get_inter_layer_edges(self, layer: dict) -> tuple[list[dict], list[dict]]:
"""Return (deps_out, deps_in) aggregated by target/source layer."""
layer_node_ids = set(layer.get("nodeIds", []))
diff --git a/packages/core/src/repowise/core/generation/knowledge_graph.py b/packages/core/src/repowise/core/generation/knowledge_graph.py
index 2075b920e..a6ed626e0 100644
--- a/packages/core/src/repowise/core/generation/knowledge_graph.py
+++ b/packages/core/src/repowise/core/generation/knowledge_graph.py
@@ -58,14 +58,35 @@ async def enrich_knowledge_graph(
reasoning=reasoning,
)
- tour = await _generate_tour(
- enriched_layers, llm_client, graph_builder, repo_structure, kg_skeleton,
- reasoning=reasoning,
- )
+ # When curation is enabled it has already written the canonical,
+ # layer-aware tour (deterministic, one per layer top→bottom). The LLM must
+ # not reselect or reorder it — keep the curated tour as-is (prose narration
+ # can be layered on separately). Otherwise fall back to LLM tour generation.
+ from repowise.core.analysis.kg_curation import curation_enabled
+
+ if curation_enabled() and kg_skeleton.tour:
+ tour = kg_skeleton.tour
+ else:
+ tour = await _generate_tour(
+ enriched_layers, llm_client, graph_builder, repo_structure, kg_skeleton,
+ reasoning=reasoning,
+ )
if generated_pages:
_backfill_summaries(kg_skeleton, generated_pages)
+ # Deterministic summary floor, applied *after* the page backfill so rich
+ # page summaries always win and only never-paged files fall back. Gated by
+ # the curation flag (the seam already floored FAST-mode output; this covers
+ # the generate-mode path where the seam deferred to let backfill run first).
+ if curation_enabled():
+ from repowise.core.analysis.kg_curation import apply_summary_floor
+
+ try:
+ apply_summary_floor(kg_skeleton)
+ except Exception as exc: # pragma: no cover - defensive
+ logger.warning("kg_summary_floor_failed", error=str(exc))
+
kg_skeleton.layers = enriched_layers
kg_skeleton.tour = tour
return kg_skeleton
@@ -92,23 +113,28 @@ async def _enrich_layers(
pagerank = graph_builder.pagerank()
enriched = list(layers)
+ # Join LLM responses back onto layers by their stable id, never by list
+ # position: positional joins silently corrupt every name when a model
+ # returns batch-relative indices.
+ by_id = {layer["id"]: layer for layer in enriched if layer.get("id")}
for batch_start in range(0, len(layers), _LAYER_BATCH_SIZE):
batch = layers[batch_start : batch_start + _LAYER_BATCH_SIZE]
batch_context = []
- for i, layer in enumerate(batch):
+ for layer in batch:
node_ids = layer.get("nodeIds", [])
file_paths = [nid.removeprefix("file:") for nid in node_ids if nid.startswith("file:")]
top_files = sorted(file_paths, key=lambda p: pagerank.get(p, 0.0), reverse=True)[:20]
batch_context.append({
- "index": batch_start + i,
+ "id": layer.get("id", ""),
"heuristic_label": layer["name"],
"file_count": len(file_paths),
"top_files": top_files,
})
user_prompt = _build_layer_naming_prompt(batch_context, tech_stack, repo_structure)
+ batch_ids = {layer.get("id") for layer in batch}
try:
response = await llm_client.generate(
@@ -121,12 +147,19 @@ async def _enrich_layers(
parsed = _parse_json_response(response.content)
if parsed and "layers" in parsed:
for item in parsed["layers"]:
- idx = item.get("index")
- if idx is not None and 0 <= idx < len(enriched):
- if item.get("name"):
- enriched[idx]["name"] = item["name"]
- if item.get("description"):
- enriched[idx]["description"] = item["description"]
+ layer_id = item.get("id")
+ target = by_id.get(layer_id) if layer_id in batch_ids else None
+ if target is None:
+ logger.warning(
+ "kg_layer_naming_unknown_id",
+ layer_id=layer_id,
+ batch_ids=sorted(filter(None, batch_ids)),
+ )
+ continue
+ if item.get("name"):
+ target["name"] = item["name"]
+ if item.get("description"):
+ target["description"] = item["description"]
except Exception as exc:
logger.warning("kg_layer_naming_batch_failed", error=str(exc))
@@ -152,14 +185,15 @@ def _build_layer_naming_prompt(
]
for ctx in batch_context:
- lines.append(f"\n--- Community {ctx['index']} ---")
+ lines.append(f"\n--- Community \"{ctx['id']}\" ---")
lines.append(f"Heuristic label: {ctx['heuristic_label']}")
lines.append(f"File count: {ctx['file_count']}")
lines.append(f"Top files: {', '.join(ctx['top_files'][:10])}")
lines.append("")
lines.append(
- 'Respond with: {"layers": [{"index": 0, "name": "...", "description": "..."}]}'
+ "Respond with each community's id echoed verbatim: "
+ '{"layers": [{"id": "...", "name": "...", "description": "..."}]}'
)
return "\n".join(lines)
@@ -328,10 +362,15 @@ def _backfill_summaries(kg_result: Any, generated_pages: list[Any]) -> None:
page_summaries[target] = summary
for node in kg_result.nodes:
- if node["type"] in ("file", "config", "service", "document"):
- path = node.get("filePath", node["id"].removeprefix("file:"))
- if path in page_summaries and not node.get("summary"):
- node["summary"] = page_summaries[path]
+ # Any file-level node (any presentation type — file/config/service/
+ # pipeline/schema/document). Only fill empties: a page summary is the
+ # richest source, and the deterministic curation floor is applied
+ # *after* this backfill so it never blocks a real page summary.
+ if not str(node.get("id", "")).startswith("file:"):
+ continue
+ path = node.get("filePath", node["id"].removeprefix("file:"))
+ if path in page_summaries and not node.get("summary"):
+ node["summary"] = page_summaries[path]
# ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/generation/layers.py b/packages/core/src/repowise/core/generation/layers.py
index 3bc0f8c7e..5084b1be9 100644
--- a/packages/core/src/repowise/core/generation/layers.py
+++ b/packages/core/src/repowise/core/generation/layers.py
@@ -24,6 +24,8 @@ from collections import defaultdict
from collections.abc import Iterable, Mapping
from pathlib import PurePosixPath
+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
+
# ---------------------------------------------------------------------------
# Directory → layer hint table. Each canonical layer maps to the
# directory-name tokens that imply it. A
@@ -31,7 +33,10 @@ from pathlib import PurePosixPath
# from the deepest segment outward (the closest directory wins).
# ---------------------------------------------------------------------------
+_TEST_DIR_TOKENS = frozenset({"__tests__", "test", "tests", "spec", "specs", "e2e"})
+
_LAYER_HINTS: tuple[tuple[str, frozenset[str]], ...] = (
+ ("CLI", frozenset({"cli", "commands", "cmd", "cli_commands"})),
("API", frozenset({"routes", "api", "controllers", "endpoints", "handlers", "routers"})),
("Service", frozenset({"services", "core", "lib", "domain", "logic", "usecases"})),
("Data", frozenset({"models", "db", "data", "persistence", "repository", "repositories", "store", "stores", "entities"})),
@@ -39,10 +44,170 @@ _LAYER_HINTS: tuple[tuple[str, frozenset[str]], ...] = (
("Middleware", frozenset({"middleware", "plugins", "interceptors", "guards"})),
("Utility", frozenset({"utils", "helpers", "common", "shared", "tools", "util"})),
("Config", frozenset({"config", "constants", "env", "settings", "conf"})),
- ("Test", frozenset({"__tests__", "test", "tests", "spec", "specs", "e2e"})),
+ ("Test", _TEST_DIR_TOKENS),
("Types", frozenset({"types", "interfaces", "schemas", "contracts", "dtos", "typings"})),
)
+# Layers that observe or support the runtime stack rather than participate in
+# it. Tests import production code and are never imported back, so letting
+# them compete on import direction would crown them the top "consumer" in
+# every codebase that has tests. They are excluded from the dependency race
+# and pinned after the runtime layers instead.
+ADJACENT_LAYERS: frozenset[str] = frozenset({"Test"})
+
+# Test-dir tokens that also name non-test directories in the wild ("spec(s)" =
+# specifications, OpenAPI specs, language specs, …). These assign the Test
+# layer only when the *file* corroborates; otherwise the scan continues
+# outward to the next matching segment.
+_AMBIGUOUS_TEST_DIR_TOKENS: frozenset[str] = frozenset({"spec", "specs"})
+
+# Filename shapes that mark a test on their own (pytest, Go, Jest/Vitest,
+# RSpec/minitest fixtures, …). Derived from the language registry — each
+# language declares its own conventions on its spec; the union applies
+# globally here (parity with the historical hard-coded tuples is pinned by
+# tests/unit/ingestion/test_language_capabilities.py).
+_TEST_FILE_STEM_PREFIXES = _LANG_REGISTRY.test_stem_prefixes()
+_TEST_FILE_STEM_SUFFIXES = _LANG_REGISTRY.test_stem_suffixes()
+_TEST_FILE_INFIXES = _LANG_REGISTRY.test_infixes()
+_TEST_FIXTURE_STEMS = _LANG_REGISTRY.test_fixture_stems()
+
+# Case-sensitive camel-boundary suffix patterns (FooTest.java, BarSpec.scala),
+# keyed by extension so each language's convention applies only to its own
+# files (polyglot fairness). The lowercase-boundary lookbehind keeps
+# `latest.java`, `contest.cs`, and bare `Test.java` out — conventions match
+# with their own case sensitivity.
+_TEST_CAMEL_RES = _LANG_REGISTRY.camel_test_res_by_extension()
+
+# Multi-segment test roots (src/it/java) and case-sensitive test-project dir
+# suffixes (.NET sibling Foo.Tests/ projects). Both are unambiguous — like
+# tests/ and __tests__/, they mark any file beneath them.
+# A ``*``-segment form ("src/*Test") matches a Gradle source-set directory:
+# the literal segment(s) match lowercased, the ``*<Suffix>`` segment matches
+# the original-case dir name by proper suffix (src/jvmTest, src/commonTest,
+# src/integrationTest, …).
+_TEST_DIR_PATHS: tuple[tuple[str, ...], ...] = tuple(
+ tuple(p.split("/")) for p in _LANG_REGISTRY.test_dir_paths() if "*" not in p
+)
+_TEST_DIR_WILDCARDS: tuple[tuple[str, str], ...] = tuple(
+ (p.split("/")[0], p.split("/")[1].lstrip("*"))
+ for p in _LANG_REGISTRY.test_dir_paths()
+ if "*" in p
+)
+_TEST_DIR_SUFFIXES = _LANG_REGISTRY.test_dir_suffixes()
+# Per-language unambiguous test-dir tokens: ruby's spec/ needs no filename
+# corroboration — a Ruby file under spec/ is RSpec material whatever its
+# name (support helpers, vendored fixtures).
+_LANG_TEST_DIR_TOKENS = _LANG_REGISTRY.test_dir_tokens_by_language()
+
+
+def _is_test_file_name(filename: str) -> bool:
+ """Whether *filename* alone marks a test (test_x.py, x_test.go, x.spec.ts, …)."""
+ name = filename.lower()
+ stem = PurePosixPath(name).stem
+ if (
+ stem in _TEST_FIXTURE_STEMS
+ or stem.startswith(_TEST_FILE_STEM_PREFIXES)
+ or stem.endswith(_TEST_FILE_STEM_SUFFIXES)
+ or any(m in name for m in _TEST_FILE_INFIXES)
+ ):
+ return True
+ camel_re = _TEST_CAMEL_RES.get(PurePosixPath(filename).suffix.lower())
+ return camel_re is not None and camel_re.search(PurePosixPath(filename).stem) is not None
+
+
+def _is_test_dir_path(segments: list[str], original_segments: list[str]) -> bool:
+ """Whether the directory path itself is an unambiguous test root.
+
+ *segments* are lowercased dir names, *original_segments* preserve case
+ for the case-sensitive project-dir suffix rule (``Foo.Tests/``).
+ """
+ for needle in _TEST_DIR_PATHS:
+ span = len(needle)
+ if span <= len(segments) and any(
+ tuple(segments[i : i + span]) == needle
+ for i in range(len(segments) - span + 1)
+ ):
+ return True
+ for prefix_seg, camel_sfx in _TEST_DIR_WILDCARDS:
+ for i in range(len(segments) - 1):
+ nxt = original_segments[i + 1]
+ if (
+ segments[i] == prefix_seg
+ and nxt.endswith(camel_sfx)
+ and len(nxt) > len(camel_sfx)
+ ):
+ return True
+ return any(seg.endswith(_TEST_DIR_SUFFIXES) for seg in original_segments)
+
+
+# Per-language layer hints (they fire only for files of the
+# declaring language, never others'). Partitioned by hint shape at import time — exact
+# lowercase tokens, multi-segment paths ("src/bin"), and case-sensitive
+# dir-name suffixes (".Api", "-cli"). The generic table above wins at any
+# given depth; a deeper segment beats a shallower one across both tables.
+_LANG_TOKEN_HINTS: dict[str, dict[str, str]] = {}
+_LANG_PATH_HINTS: dict[str, tuple[tuple[tuple[str, ...], str], ...]] = {}
+_LANG_SUFFIX_HINTS: dict[str, tuple[tuple[str, str], ...]] = {}
+_LANG_ROOT_HINTS: dict[str, dict[str, str]] = {}
+for _tag, _hints in _LANG_REGISTRY.layer_dir_hints_by_language().items():
+ _tokens: dict[str, str] = {}
+ _paths: list[tuple[tuple[str, ...], str]] = []
+ _suffixes: list[tuple[str, str]] = []
+ _roots: dict[str, str] = {}
+ for _key, _layer in _hints:
+ if _key.startswith("/"):
+ # Root-anchored token ("/include"): the convention is a
+ # top-level dir — a vendored include/ buried deep in another
+ # language's tree must not mint the layer.
+ _roots[_key[1:]] = _layer
+ elif "/" in _key:
+ _paths.append((tuple(_key.split("/")), _layer))
+ elif _key.startswith((".", "-")):
+ _suffixes.append((_key, _layer))
+ else:
+ _tokens[_key] = _layer
+ if _tokens:
+ _LANG_TOKEN_HINTS[_tag] = _tokens
+ if _paths:
+ _LANG_PATH_HINTS[_tag] = tuple(_paths)
+ if _suffixes:
+ _LANG_SUFFIX_HINTS[_tag] = tuple(_suffixes)
+ if _roots:
+ _LANG_ROOT_HINTS[_tag] = _roots
+
+
+# Example/demo/benchmark directories: documentation-by-code and support
+# harnesses, not the system itself. Their files carry entry-style names
+# (main.go, index.js, decode.exs) by convention, so without demotion they
+# flood entry points and the tour on any repo that ships samples (express,
+# chi, …) or benchmarks (cargo's benches/, jason's bench/).
+_EXAMPLE_DIR_TOKENS = frozenset(
+ {
+ "examples", "_examples", "example", "samples", "sample", "demo", "demos",
+ "bench", "benches", "benchmarks",
+ }
+)
+
+
+# Documentation directories: sphinx/docusaurus/vitepress sites and runnable
+# doc snippets (libuv's docs/code/*/main.c, docfx template assets). Like the
+# example dirs above, their files carry entry-style names by convention but
+# document the system rather than being it.
+_DOC_DIR_TOKENS = frozenset({"docs", "doc", "website"})
+
+
+def is_support_path(path: str) -> bool:
+ """Whether *path* is support material (examples/benchmarks/docs sites).
+
+ Support files never seed or anchor a tour and never surface as entry
+ points — a reader orienting in the repo must land in the system itself,
+ not in its documentation or sample harnesses.
+ """
+ return any(
+ s.lower() in _EXAMPLE_DIR_TOKENS or s.lower() in _DOC_DIR_TOKENS
+ for s in PurePosixPath(path).parts[:-1]
+ )
+
# Fallback layer for files whose path matches no hint (root scripts, etc.).
DEFAULT_LAYER = "Application"
@@ -52,34 +217,128 @@ DEFAULT_LAYER = "Application"
# (foundational): top imports middle imports bottom.
_CANONICAL_RANK: dict[str, int] = {
"UI": 0,
- "API": 1,
- "Middleware": 2,
- "Service": 3,
- DEFAULT_LAYER: 4,
- "Data": 5,
- "Types": 6,
- "Config": 7,
- "Utility": 8,
- "Test": 9,
+ "CLI": 1,
+ "API": 2,
+ "Middleware": 3,
+ "Service": 4,
+ DEFAULT_LAYER: 5,
+ "Data": 6,
+ "Types": 7,
+ "Config": 8,
+ "Utility": 9,
+ "Test": 10,
}
-def infer_layer(path: str) -> str:
+def infer_layer(path: str, language: str | None = None) -> str:
"""Return the architectural layer name for *path*.
- Scans path segments from the deepest directory outward and returns the
- first layer whose hint set contains a segment. Falls back to
- :data:`DEFAULT_LAYER` when nothing matches.
+ A test-shaped filename wins outright — Go and Jest colocate tests beside
+ sources (``mux_test.go``, ``Button.test.tsx``), so without this check
+ repos with no ``tests/`` dir get no Test layer at all. A test root
+ anywhere on the path wins next: ``tests/models/x.py`` is a test fixture,
+ not Data, so unambiguous test dirs (``tests``/``__tests__``/…) mark the
+ file from any depth. Ambiguous test-dir tokens (``spec``/``specs``) count
+ only when the filename itself looks like a test — a ``specs/`` directory
+ full of ordinary modules is a specification folder, not a test suite.
+ Otherwise scans path segments from the deepest directory outward and
+ returns the first layer whose hint set contains a segment. When
+ *language* is given, that language's registry-declared hints (Go
+ ``internal/``, Rust ``src/bin/``, .NET ``Foo.Api/``…) are consulted at
+ each depth after the generic table — they never fire for other
+ languages' files. Falls back to :data:`DEFAULT_LAYER` when nothing
+ matches.
"""
- segments = [s.lower() for s in PurePosixPath(path).parts[:-1]] # drop filename
+ original_parts = list(PurePosixPath(path).parts)
+ parts = [s.lower() for s in original_parts]
+ # Original case is preserved for the case-sensitive rules (camel-suffix
+ # filenames, .NET ``Foo.Tests/`` project dirs).
+ filename = original_parts[-1] if original_parts else ""
+ segments = parts[:-1] # drop filename
+
+ if _is_test_file_name(filename):
+ return "Test"
+
+ lang_test_tokens = _LANG_TEST_DIR_TOKENS.get((language or "").lower(), frozenset())
+ for seg in segments:
+ if seg not in _TEST_DIR_TOKENS:
+ continue
+ if (
+ seg in _AMBIGUOUS_TEST_DIR_TOKENS
+ and seg not in lang_test_tokens
+ and not _is_test_file_name(filename)
+ ):
+ continue # "spec(s)/" without a test-shaped file: not a test root
+ return "Test"
+
+ if _is_test_dir_path(segments, original_parts[:-1]):
+ return "Test"
+
+ # Repo-root dot-directories (.github, .agents, .claude, .vscode, …) hold
+ # tooling, not architecture — their inner dir names (e.g. "plugins") must
+ # not mint phantom runtime layers.
+ if segments and segments[0].startswith("."):
+ return "Config"
+
+ lang = (language or "").lower()
+ token_hints = _LANG_TOKEN_HINTS.get(lang)
+ path_hints = _LANG_PATH_HINTS.get(lang)
+ suffix_hints = _LANG_SUFFIX_HINTS.get(lang)
+ root_hints = _LANG_ROOT_HINTS.get(lang)
+ original_segments = original_parts[:-1]
+
# Deepest directory first — the closest folder describes the file best.
- for seg in reversed(segments):
+ for i in range(len(segments) - 1, -1, -1):
+ seg = segments[i]
for layer_name, tokens in _LAYER_HINTS:
+ if layer_name == "Test":
+ continue # handled above
if seg in tokens:
return layer_name
+ if token_hints and seg in token_hints:
+ return token_hints[seg]
+ if path_hints:
+ for needle, layer_name in path_hints:
+ span = len(needle)
+ if span <= i + 1 and tuple(segments[i - span + 1 : i + 1]) == needle:
+ return layer_name
+ if suffix_hints:
+ orig = original_segments[i]
+ for sfx, layer_name in suffix_hints:
+ # Proper suffix only — a dir literally named ".Api" is not
+ # the convention.
+ if orig.endswith(sfx) and len(orig) > len(sfx):
+ return layer_name
+ if i == 0 and root_hints and seg in root_hints:
+ return root_hints[seg]
return DEFAULT_LAYER
+def layer_order_basis(
+ file_layers: Mapping[str, str],
+ import_edges: Iterable[tuple[str, str]],
+) -> str:
+ """Whether :func:`compute_layer_order`'s result is evidence or convention.
+
+ Returns ``"imports"`` when at least one inter-layer runtime edge
+ participated in the ordering race, ``"canonical"`` when the order is
+ purely the conventional rank (edgeless/sparse graphs, single-layer
+ repos). Consumers must not claim "X sits above Y" for a canonical
+ order — no edge supports it.
+ """
+ for src, dst in import_edges:
+ if src.startswith("external:") or dst.startswith("external:"):
+ continue
+ ls = file_layers.get(src)
+ ld = file_layers.get(dst)
+ if not ls or not ld or ls == ld:
+ continue
+ if ls in ADJACENT_LAYERS or ld in ADJACENT_LAYERS:
+ continue
+ return "imports"
+ return "canonical"
+
+
def compute_layer_order(
file_layers: Mapping[str, str],
import_edges: Iterable[tuple[str, str]],
@@ -100,11 +359,19 @@ def compute_layer_order(
imports many but is imported by few is a consumer (top). Ties fall back to
the canonical rank so the result is stable on graphs with no clear
direction.
+
+ :data:`ADJACENT_LAYERS` (tests) sit outside the runtime stack: their edges
+ are excluded from the race (a test importing a service says nothing about
+ where the service sits) and they are appended after the runtime layers in
+ canonical-rank order.
"""
layers = sorted(set(file_layers.values()))
if len(layers) <= 1:
return layers
+ runtime = [layer for layer in layers if layer not in ADJACENT_LAYERS]
+ adjacent = [layer for layer in layers if layer in ADJACENT_LAYERS]
+
out_deg: dict[str, int] = defaultdict(int) # edges leaving the layer
in_deg: dict[str, int] = defaultdict(int) # edges entering the layer
for src, dst in import_edges:
@@ -114,6 +381,8 @@ def compute_layer_order(
ld = file_layers.get(dst)
if not ls or not ld or ls == ld:
continue
+ if ls in ADJACENT_LAYERS or ld in ADJACENT_LAYERS:
+ continue
out_deg[ls] += 1
in_deg[ld] += 1
@@ -123,4 +392,6 @@ def compute_layer_order(
net = in_deg[layer] - out_deg[layer]
return (net, _CANONICAL_RANK.get(layer, len(_CANONICAL_RANK)))
- return sorted(layers, key=sort_key)
+ ordered = sorted(runtime, key=sort_key)
+ ordered += sorted(adjacent, key=lambda la: _CANONICAL_RANK.get(la, len(_CANONICAL_RANK)))
+ return ordered
diff --git a/packages/core/src/repowise/core/generation/models.py b/packages/core/src/repowise/core/generation/models.py
index 1ce75ce59..e72a04866 100644
--- a/packages/core/src/repowise/core/generation/models.py
+++ b/packages/core/src/repowise/core/generation/models.py
@@ -112,10 +112,16 @@ class GenerationConfig:
file_page_min_symbols: int = 1
skip_trivial_files: bool = True
dedupe_near_clones: bool = True
- # Phase 2: switch module_page grouping from top-directory to graph
- # communities. min_module_size is the floor below which a community
- # doesn't get its own page (its files still appear under file_page).
- module_grouping: Literal["community", "top_dir"] = "community"
+ # Module-page grouping source. "curated" (default) groups by the wiki
+ # modules the KG curation pass derives (stable path ids, human names,
+ # right-sized groups) and silently falls back to "community" when no
+ # curated modules are available (curation off, degraded, or no KG
+ # artifact), so it is always safe. "community" groups by raw graph
+ # communities (the pre-curation behavior, kept as the escape hatch),
+ # "top_dir" by top-level directory.
+ # min_module_size is the floor below which a group doesn't get its own
+ # page (its files still appear under file_page).
+ module_grouping: Literal["community", "top_dir", "curated"] = "curated"
min_module_size: int = 3
# Phase 3: emit the curated Onboarding collection at level 8. Each
# subkind defines its own gate; slots whose gates fail are silently
diff --git a/packages/core/src/repowise/core/generation/onboarding/subkinds/how_it_works.py b/packages/core/src/repowise/core/generation/onboarding/subkinds/how_it_works.py
index 74399c7a0..f50c69d24 100644
--- a/packages/core/src/repowise/core/generation/onboarding/subkinds/how_it_works.py
+++ b/packages/core/src/repowise/core/generation/onboarding/subkinds/how_it_works.py
@@ -139,11 +139,29 @@ def _collect_flows(signals: OnboardingSignals) -> list[FlowTrace]:
return flows
+def _normalize_tour_step(step: dict) -> dict:
+ """One template-facing shape for both tour-step generations.
+
+ Legacy steps carry ``nodeIds`` + ``description``; curated steps carry a
+ single ``target_path`` + evidence in ``reason``. The strict template
+ (``step.nodeIds`` / ``step.description``) must never see a missing key.
+ """
+ node_ids = list(step.get("nodeIds") or [])
+ if step.get("target_path"):
+ node_ids.append(f"file:{step['target_path']}")
+ return {
+ "order": step.get("order", 0),
+ "title": step.get("title", ""),
+ "description": step.get("description") or step.get("reason") or "",
+ "nodeIds": node_ids,
+ }
+
+
def _build(signals: OnboardingSignals) -> HowItWorksContext | None:
archetype, evidence = _classify_archetype(signals)
flows = _collect_flows(signals)
- kg_tour = list(signals.kg_tour_steps) if signals.kg_tour_steps else []
+ kg_tour = [_normalize_tour_step(s) for s in signals.kg_tour_steps or ()]
# Gate: need either a real trace, tour steps, or a non-trivial archetype.
if not flows and not kg_tour and archetype == "module":
diff --git a/packages/core/src/repowise/core/generation/page_generator/core.py b/packages/core/src/repowise/core/generation/page_generator/core.py
index 8a4f46f6e..bd1c41637 100644
--- a/packages/core/src/repowise/core/generation/page_generator/core.py
+++ b/packages/core/src/repowise/core/generation/page_generator/core.py
@@ -60,15 +60,23 @@ def _attach_file_provenance(page: GeneratedPage, ctx: FilePageContext) -> None:
"""
if ctx.kg_layer_name:
page.metadata["layer_name"] = ctx.kg_layer_name
+ # Stable slug id of the layer page this file links to. The layer page
+ # is keyed by slug (``layer:<slug>``) so the join survives the LLM
+ # layer-name enrichment that mutates ``layer_name`` after generation.
+ if ctx.kg_layer_id:
+ page.metadata["layer_id"] = ctx.kg_layer_id
if ctx.kg_layer_role:
page.metadata["layer_role"] = ctx.kg_layer_role
else:
# Guarantee every file page carries a layer so the Architecture tree
# can group it. When the knowledge graph has no layer, fall back to
# path-based inference.
+ from ...analysis.knowledge_graph import _slugify
from ..layers import infer_layer
- page.metadata["layer_name"] = infer_layer(ctx.file_path)
+ inferred = infer_layer(ctx.file_path, getattr(ctx, "language", None))
+ page.metadata["layer_name"] = inferred
+ page.metadata["layer_id"] = f"layer:{_slugify(inferred)}"
sources: list[dict[str, str]] = []
seen: set[str] = set()
@@ -171,6 +179,8 @@ class PageGenerator(PerTypeGenerationMixin):
decision_report: Any | None = None,
external_systems: list[dict] | None = None,
on_page_ready: Callable[[GeneratedPage], None] | None = None,
+ kg_modules: list[dict] | None = None,
+ kg_data: dict | None = None,
) -> list[GeneratedPage]:
"""Generate all wiki pages for a repository.
@@ -198,6 +208,8 @@ class PageGenerator(PerTypeGenerationMixin):
decision_report=decision_report,
external_systems=external_systems,
on_page_ready=on_page_ready,
+ kg_modules=kg_modules,
+ kg_data=kg_data,
)
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/generation/page_generator/levels.py b/packages/core/src/repowise/core/generation/page_generator/levels.py
index 80ea7ce83..71743a663 100644
--- a/packages/core/src/repowise/core/generation/page_generator/levels.py
+++ b/packages/core/src/repowise/core/generation/page_generator/levels.py
@@ -13,6 +13,7 @@ from typing import TYPE_CHECKING, Any
import structlog
+from ...analysis.knowledge_graph import _slugify
from .. import onboarding as _onboarding
from ..context_assembler import FilePageContext
from ..models import compute_page_id
@@ -317,7 +318,13 @@ def build_level5_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
continue
layer_name = layer.get("name", "")
- page_id = compute_page_id("layer_page", f"layer:{layer_name}")
+ # Key the page by the layer's STABLE slug id (``layer:<slug>``), not its
+ # display name: the LLM layer-name enrichment rewrites ``name`` after
+ # generation, so a name-keyed page would no longer join to its KG layer.
+ # ``id`` is derived from the deterministic heuristic name at curation
+ # time and never changes under enrichment.
+ layer_id = layer.get("id", "") or f"layer:{_slugify(layer_name)}"
+ page_id = compute_page_id("layer_page", layer_id)
if page_id in run.completed_ids:
continue
@@ -354,6 +361,7 @@ def build_level5_coros(run: _GenerationRun) -> list[tuple[str, Any]]:
ctx = LayerPageContext(
layer_name=layer_name,
+ layer_id=layer_id,
layer_description=layer.get("description", ""),
file_count=len(file_paths),
key_files=key_files,
diff --git a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
index 344bfda46..1ea45d192 100644
--- a/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
+++ b/packages/core/src/repowise/core/generation/page_generator/orchestrate.py
@@ -60,6 +60,8 @@ class _GenerationRun:
decision_report: Any | None,
external_systems: list[dict] | None,
on_page_ready: Callable[[GeneratedPage], None] | None = None,
+ kg_modules: list[dict] | None = None,
+ kg_data: dict | None = None,
) -> None:
self.gen = gen
self.config = gen._config
@@ -83,6 +85,11 @@ class _GenerationRun:
self.resume = resume
self.repo_path = repo_path
self.external_systems = external_systems or []
+ # Curated wiki modules from the IN-MEMORY pipeline result. The kg_ctx
+ # file fallback below is one run stale on update and absent on a
+ # fresh init (the artifact is written AFTER generation) — the live
+ # repowise run shipped community-grouped module pages because of it.
+ self.kg_modules = kg_modules or []
# ---- Graph metrics ----
self.graph = graph_builder.graph()
@@ -98,17 +105,27 @@ class _GenerationRun:
# ---- KG context (per-file knowledge graph lookups) ----
from repowise.core.generation.kg_context import KnowledgeGraphContext
- kg_path = None
+ # Prefer the in-memory KG (the pipeline result's export dict): the
+ # artifact file is only written during persistence — AFTER this
+ # generation pass — so on a fresh init the file path below finds
+ # nothing and every kg_ctx-derived page (layer pages, tour context,
+ # file layers) silently vanished from first-run wikis.
+ rp = None
if repo_path:
rp = Path(repo_path) if not isinstance(repo_path, Path) else repo_path
- for candidate in [
- rp / ".repowise" / "knowledge-graph.json",
- rp / ".understand-anything" / "knowledge-graph.json",
- ]:
- if candidate.exists():
- kg_path = candidate
- break
- self.kg_ctx = KnowledgeGraphContext(kg_path)
+ if kg_data is not None:
+ self.kg_ctx = KnowledgeGraphContext(None, rp, data=kg_data)
+ else:
+ kg_path = None
+ if rp:
+ for candidate in [
+ rp / ".repowise" / "knowledge-graph.json",
+ rp / ".understand-anything" / "knowledge-graph.json",
+ ]:
+ if candidate.exists():
+ kg_path = candidate
+ break
+ self.kg_ctx = KnowledgeGraphContext(kg_path)
# ---- Run bookkeeping ----
self.semaphore = asyncio.Semaphore(self.config.max_concurrency)
@@ -214,6 +231,11 @@ class _GenerationRun:
git_meta_map=self.git_meta_map,
config=self.config,
kg_file_scores=kg_scores or None,
+ # Curated wiki modules: prefer the in-memory pipeline
+ # result (fresh); the artifact file is absent on first init
+ # and one run stale on update. Inert unless
+ # module_grouping == "curated".
+ kg_modules=self.kg_modules or self.kg_ctx.get_modules() or None,
)
)
@@ -293,24 +315,40 @@ class _GenerationRun:
import_edges = self._file_import_edges()
- # Tour: ordered stops over the selected file/infra pages + overview.
- stops = build_tour(
- self.parsed_files,
- self.pagerank,
- import_edges,
- file_page_paths=self.sel_file_paths,
- infra_paths=self.sel_infra_paths,
- repo_name=self.repo_name,
- )
- self.tour_stops = [s.as_dict() for s in stops]
+ # When the indexed KG carries the curated tour (project.graph_mode is
+ # written only by the curation pass), adopt it wholesale instead of
+ # re-deriving a second, divergent tour from the raw graph: the curated
+ # tour knows the repo's honesty mode (flow/sparse/structural), walks
+ # imports-type edges only, and excludes support paths — and the wiki's
+ # file cards already cite its steps. One tour, every surface.
+ if self.kg_ctx.available and self.kg_ctx.get_graph_mode():
+ self.tour_stops = [dict(s) for s in self.kg_ctx.get_tour()]
+ if not self.tour_stops:
+ # Tour: ordered stops over the selected file/infra pages + overview.
+ stops = build_tour(
+ self.parsed_files,
+ self.pagerank,
+ import_edges,
+ file_page_paths=self.sel_file_paths,
+ infra_paths=self.sel_infra_paths,
+ repo_name=self.repo_name,
+ )
+ self.tour_stops = [s.as_dict() for s in stops]
# Layer spine: every documented file gets a layer (KG when present,
# path-based inference otherwise), then layers are ordered top→bottom
# by inter-layer dependency direction.
+ lang_by_path = {
+ p.file_info.path: (getattr(p.file_info, "language", "") or "").lower()
+ for p in self.parsed_files
+ if getattr(p, "file_info", None)
+ }
file_layers: dict[str, str] = {}
for path in self.sel_file_paths:
kg_fc = self.kg_ctx.get_file_context(path) if self.kg_ctx.available else None
- file_layers[path] = (kg_fc.layer_name if kg_fc and kg_fc.layer_name else "") or infer_layer(path)
+ file_layers[path] = (kg_fc.layer_name if kg_fc and kg_fc.layer_name else "") or infer_layer(
+ path, lang_by_path.get(path)
+ )
self.layer_order = compute_layer_order(file_layers, import_edges)
# ------------------------------------------------------------------
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 180173471..0211d1daf 100644
--- a/packages/core/src/repowise/core/generation/page_generator/pertype.py
+++ b/packages/core/src/repowise/core/generation/page_generator/pertype.py
@@ -310,7 +310,10 @@ class PerTypeGenerationMixin:
ctx: LayerPageContext,
) -> GeneratedPage:
user_prompt = self._render("layer_page.j2", ctx=ctx)
- target = f"layer:{ctx.layer_name}"
+ # target_path = the layer's STABLE slug id, so the page key survives
+ # the post-generation LLM rename of ``layer_name``. The title still
+ # uses the (heuristic) display name.
+ target = ctx.layer_id
response = await self._call_provider(
"layer_page", user_prompt, str(uuid.uuid4()), target_path=target
)
diff --git a/packages/core/src/repowise/core/generation/selection/selector.py b/packages/core/src/repowise/core/generation/selection/selector.py
index 42425e38e..dc9b07d75 100644
--- a/packages/core/src/repowise/core/generation/selection/selector.py
+++ b/packages/core/src/repowise/core/generation/selection/selector.py
@@ -45,8 +45,9 @@ class ModuleGroup:
"""One ``module_page`` worth of files.
``key`` is the stable identifier persisted as ``target_path``:
- ``community-<id>`` when grouping by community, the top-level
- directory when falling back to ``top_dir``.
+ the module's real directory path when grouping by curated KG modules
+ (so path-prefix child lookups work), ``community-<id>`` when grouping
+ by community, the top-level directory when falling back to ``top_dir``.
"""
key: str
@@ -108,6 +109,11 @@ class SelectionInputs:
git_meta_map: dict[str, dict] | None
config: Any # GenerationConfig — duck-typed to avoid the import cycle
kg_file_scores: dict[str, float] | None = None
+ # Curated wiki modules from the KG artifact (``modules`` top-level key),
+ # passed through — never re-derived here. Only read when
+ # ``config.module_grouping == "curated"``; ``None``/empty falls back to
+ # community grouping (the fallback-matrix "degraded" row).
+ kg_modules: list[dict] | None = None
# ---------------------------------------------------------------------------
@@ -184,11 +190,84 @@ def _build_symbol_candidates(
return scored
+def _build_curated_module_groups(
+ inputs: SelectionInputs, min_size: int
+) -> list[tuple[float, ModuleGroup]] | None:
+ """Scored groups from curated KG modules, or ``None`` when unavailable.
+
+ ``key`` = the module's real directory path (its ``target_path``, so the
+ MCP child lookup ``target_path LIKE 'dir/%'`` works), ``display``/``label``
+ = the curated human name, ``cohesion`` = None (the community block in the
+ template is conditional and has no meaning for directory groups). Ranked
+ by Σ PageRank of members — better than ``score_module``'s cohesion term,
+ which is meaningless here. Returns ``None`` only when no curated modules
+ were passed in (→ community fallback); an artifact whose modules all fall
+ below the floor yields an empty list, not a vocabulary mix.
+ """
+ if not inputs.kg_modules:
+ return None
+
+ code_by_path = {
+ p.file_info.path: p for p in inputs.parsed_files if _is_code_file(p)
+ }
+ scored: list[tuple[float, ModuleGroup]] = []
+ seen_keys: set[str] = set()
+ for module in inputs.kg_modules:
+ if module.get("wholeLayer"):
+ # 1:1 with a layer page (single-module layers, flat libs) — a
+ # module doc would re-document the layer. Skip the page; the
+ # module stays in the KG artifact for canvas/coverage.
+ continue
+ member_paths = sorted(
+ path
+ for nid in module.get("nodeIds", [])
+ if isinstance(nid, str)
+ and (path := nid.removeprefix("file:")) in code_by_path
+ )
+ if len(member_paths) < min_size:
+ continue
+ key = module.get("path") or (module.get("id") or "").removeprefix("module:")
+ if not key or key in seen_keys:
+ # Rare cross-layer dir collision: the slug id is still unique.
+ key = (module.get("id") or "").removeprefix("module:")
+ if not key or key in seen_keys:
+ continue
+ seen_keys.add(key)
+ name = module.get("name") or key
+ language = module.get("language") or code_by_path[
+ member_paths[0]
+ ].file_info.language
+ score = sum(inputs.pagerank.get(p, 0.0) for p in member_paths)
+ scored.append(
+ (
+ score,
+ ModuleGroup(
+ key=key,
+ display=name,
+ language=language,
+ file_paths=tuple(member_paths),
+ label=name,
+ cohesion=None,
+ ),
+ )
+ )
+ scored.sort(key=lambda x: (-x[0], x[1].key))
+ return scored
+
+
def _build_module_groups(inputs: SelectionInputs) -> list[tuple[float, ModuleGroup]]:
- """Return scored module groups — either community-based or top-dir."""
+ """Return scored module groups — curated, community-based, or top-dir."""
cfg = inputs.config
min_size = max(1, getattr(cfg, "min_module_size", 3))
- use_communities = getattr(cfg, "module_grouping", "community") == "community"
+ grouping = getattr(cfg, "module_grouping", "community")
+
+ if grouping == "curated":
+ curated = _build_curated_module_groups(inputs, min_size)
+ if curated is not None:
+ return curated
+ grouping = "community" # no curated artifact → today's path, unchanged
+
+ use_communities = grouping == "community"
# Bucket files into groups.
groups: dict[str, list[Any]] = {}
diff --git a/packages/core/src/repowise/core/generation/tour.py b/packages/core/src/repowise/core/generation/tour.py
index 618e57648..2d2bf3f61 100644
--- a/packages/core/src/repowise/core/generation/tour.py
+++ b/packages/core/src/repowise/core/generation/tour.py
@@ -35,22 +35,34 @@ from dataclasses import dataclass
from pathlib import PurePosixPath
from typing import Any
+from repowise.core.generation.layers import ADJACENT_LAYERS, infer_layer, is_support_path
+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
+
# Filenames that conventionally mark an executable / wiring entry point.
-_ENTRY_FILENAME_STEMS: frozenset[str] = frozenset(
- {
- "index",
- "main",
- "app",
- "server",
- "mod",
- "manage",
- "wsgi",
- "asgi",
- "cli",
- "__main__",
- "bootstrap",
- "entry",
- }
+# Derived from the language registry (generic stems + per-language stems);
+# parity with the historical hard-coded set is pinned by
+# tests/unit/ingestion/test_language_capabilities.py.
+_ENTRY_FILENAME_STEMS: frozenset[str] = _LANG_REGISTRY.entry_filename_stems()
+
+# A genuine entry whose forward BFS reaches no more than this many files is a
+# wiring stub (supervision/bootstrap); the widest-fanout file then co-anchors.
+_STUB_ENTRY_REACH = 3
+
+# Languages whose files can never be execution entry points, however
+# entry-like their stem is: docs/data/config (``is_code=False`` —
+# docs/index.md is not a program's front door, and neither is
+# schema.graphql or an openapi index) plus build/deploy wiring
+# (``is_infra`` — a Dockerfile or deploy.sh wires the system rather than
+# starting its control flow; infra pages close the tour instead). Both
+# sets derive from the registry; the lowercase aliases guard against
+# unnormalized language strings from older indexes (none is a spec tag).
+_NON_CODE_ALIASES: frozenset[str] = frozenset(
+ {"md", "yml", "txt", "html", "css", "csv", "xml", "svg", "rst", "text", "ini", "cmake"}
+)
+_NON_CODE_LANGUAGES: frozenset[str] = (
+ _LANG_REGISTRY.config_languages()
+ | _LANG_REGISTRY.infra_languages()
+ | _NON_CODE_ALIASES
)
# Upper bound on tour stops — long enough to teach the spine, short enough to
@@ -98,11 +110,17 @@ def score_entry_points(
"""Score code files as candidate tour entry points, descending.
Scoring (additive):
- * ``is_entry_point`` ingestion flag .............. +3
- * filename stem in the entry-name set ............ +3
+ * ``is_entry_point`` ingestion flag .............. +3 (code files only)
+ * filename stem in the entry-name set ............ +3 (code files only)
* file at repo root or one level deep ............ +1
* PageRank in the top 10% of all files ........... +1
+ Both entry bonuses are withheld from doc/data languages — ``docs/index.md``
+ must never outrank a real ``main.py``, even when ingestion's stem rule
+ flagged it — from test files (``tests/testserver/server.py`` is a fixture,
+ not where a reader enters the system), and from example/demo dirs (every
+ ``examples/*/main.go`` is an entry by *name*; none is the system).
+
Returns ``[(score, path), ...]`` sorted by score then path for stability.
Only files with a positive score are returned.
"""
@@ -117,9 +135,15 @@ def score_entry_points(
fi = p.file_info
path = fi.path
score = 0.0
- if getattr(fi, "is_entry_point", False):
+ language = (getattr(fi, "language", "") or "").lower()
+ entry_eligible = (
+ language not in _NON_CODE_LANGUAGES
+ and infer_layer(path, language) not in ADJACENT_LAYERS
+ and not is_support_path(path)
+ )
+ if entry_eligible and getattr(fi, "is_entry_point", False):
score += 3.0
- if PurePosixPath(path).stem.lower() in _ENTRY_FILENAME_STEMS:
+ if entry_eligible and PurePosixPath(path).stem.lower() in _ENTRY_FILENAME_STEMS:
score += 3.0
if _path_depth(path) <= 1:
score += 1.0
@@ -178,6 +202,8 @@ def build_tour(
infra_paths: Iterable[str] = (),
repo_name: str = "",
max_stops: int = DEFAULT_MAX_STOPS,
+ graph_mode: str = "flow",
+ anchor_rank: Mapping[str, int] | None = None,
) -> list[TourStop]:
"""Build the ordered tour over pages that already exist.
@@ -185,14 +211,24 @@ def build_tour(
tour never references undocumented files, so it is budget-safe by
construction. ``repo_overview`` (when *repo_name* is given) always opens
the tour; infrastructure pages close it.
+
+ ``graph_mode="sparse"`` keeps the BFS walk but softens the reasons that
+ interpret *absence* of edges: on a sparse graph (broken/partial import
+ resolution), "off the import path" would blame the file for the
+ resolver's gaps. Reasons grounded in edges that DO exist are unchanged.
+ Truly edgeless repos should not walk at all — the caller is expected to
+ build a structural tour instead (``graph_mode="structural"`` is handled
+ by the curation layer, not here).
"""
documented = set(file_page_paths)
infra = set(infra_paths)
adjacency: dict[str, list[str]] = defaultdict(list)
+ fan_in: dict[str, int] = defaultdict(int)
for src, dst in import_edges:
if src.startswith("external:") or dst.startswith("external:"):
continue
adjacency[src].append(dst)
+ fan_in[dst] += 1
# Seeds = the genuine entry points (the ``is_entry_point`` flag or an
# entry-style filename, both worth +3), restricted to documented files. A
@@ -200,18 +236,84 @@ def build_tour(
# otherwise every root file would seed the walk and flatten all depths.
scored = score_entry_points(parsed_files, pagerank)
seeds = [path for s, path in scored if s >= 3.0 and path in documented]
+ # Whether the seeds are genuine entry points (flag/filename evidence) or
+ # just the best-available anchor — the step reasons must not overclaim.
+ genuine_entries = bool(seeds)
+
+ # Docs, config, and test files can't anchor a walk.
+ ineligible = {
+ p.file_info.path
+ for p in parsed_files
+ if getattr(p, "file_info", None)
+ and (
+ (getattr(p.file_info, "language", "") or "").lower() in _NON_CODE_LANGUAGES
+ or infer_layer(p.file_info.path, p.file_info.language) in ADJACENT_LAYERS
+ or is_support_path(p.file_info.path)
+ )
+ }
+
+ # Rank by import *relationships* when the caller supplies the
+ # fan-out-collapsed counts (one package import = one relationship),
+ # else raw out-degree.
+ def _fanout(p: str) -> int:
+ if anchor_rank is not None:
+ return anchor_rank.get(p, 0)
+ return len(adjacency.get(p, []))
+
+ def _best_anchor(exclude: set[str]) -> str | None:
+ eligible = sorted(
+ (p for p in documented if p not in ineligible and p not in exclude),
+ key=lambda p: (-_fanout(p), -pagerank.get(p, 0.0), p),
+ )
+ return eligible[0] if eligible else None
+
+ anchor_seeds: set[str] = set()
if not seeds:
- # Fall back to the single highest-scored documented file so the walk
- # still has an anchor on repos with no obvious entry point.
- seeds = [path for _, path in scored if path in documented][:1]
+ # No genuine entry point anywhere (flat libraries like requests).
+ # Anchor the walk on the eligible code file whose imports fan out the
+ # widest — the closest thing to "execution starts here" the import
+ # graph offers.
+ best = _best_anchor(set())
+ seeds = [best] if best else [path for _, path in scored if path in documented][:1]
depths = _bfs_depths(seeds, adjacency, documented)
+ # Wiring-stub entries: an OTP application.ex or DI bootstrap starts
+ # supervisors, not the domain logic — its forward BFS dies at depth 1
+ # and every walk slot fills with unreached parking. When the genuine
+ # entries reach almost nothing and a non-seed file's imports fan out
+ # substantially, that file co-anchors the walk (its own steps use
+ # anchor wording, never "entry point").
+ if genuine_entries and len(depths) <= _STUB_ENTRY_REACH and len(documented) > _STUB_ENTRY_REACH * 2:
+ co_anchor = _best_anchor(set(seeds))
+ if co_anchor is not None and _fanout(co_anchor) >= 3:
+ anchor_seeds.add(co_anchor)
+ seeds = [*seeds, co_anchor]
+ depths = _bfs_depths(seeds, adjacency, documented)
+
# Documented files never reached from a seed still belong in the tour;
- # park them after the deepest reached file, ranked by PageRank.
+ # park them after the deepest reached file, ranked by PageRank. Remember
+ # which files were genuinely reached so their reasons stay truthful.
+ # Documents and config/data files are exempt from parking: they can
+ # never be on an import path, so an unreached CHANGELOG.md or
+ # wally.toml is expected — not worth a tour slot that displaces code.
+ non_code_paths = {
+ p.file_info.path
+ for p in parsed_files
+ if getattr(p, "file_info", None)
+ and (getattr(p.file_info, "language", "") or "").lower() in _NON_CODE_LANGUAGES
+ }
+ reached = set(depths)
max_reached = max(depths.values(), default=-1)
+ # Manifests (mix.exs, project.clj, Setup.lhs) are code-shaped but cannot
+ # be on an import path by design — like documents, an unreached manifest
+ # is expected and never worth a parked tour slot.
+ manifest_names = _LANG_REGISTRY.manifest_filenames()
for path in documented:
if path not in depths:
+ if path in non_code_paths or PurePosixPath(path).name in manifest_names:
+ continue
depths[path] = max_reached + 1
+ documented = {p for p in documented if p in depths}
pr_score = score_entry_points(parsed_files, pagerank)
ep_score = {path: s for s, path in pr_score}
@@ -252,9 +354,48 @@ def build_tour(
order += 1
d = depths[path]
if d <= 0:
- reason = "An entry point — execution and imports fan out from here."
+ if path in anchor_seeds:
+ reason = (
+ "The walk's anchor — the entry point above only wires the "
+ "app together, so the tour follows the file whose imports "
+ "fan out the widest."
+ )
+ elif genuine_entries:
+ reason = "An entry point — execution and imports fan out from here."
+ else:
+ # State the anchor's actual selection evidence (widest import
+ # fan-out), not a vague "best-connected" that implies fan-in.
+ reason = "The walk's anchor — its imports fan out the widest in a repo with no single entry point."
+ elif path not in reached:
+ if graph_mode == "sparse":
+ # The graph, not the file, is the likely cause here.
+ reason = (
+ "Not on the resolved import paths — import resolution is "
+ "incomplete for this repo, so links may be missing."
+ )
+ elif genuine_entries:
+ reason = (
+ "Off the import path from the entry points — a standalone "
+ "or supporting file."
+ )
+ elif fan_in.get(path, 0) >= 3:
+ reason = "A widely-imported module — much of the repo depends on it."
+ else:
+ # No fan-in evidence: a generated lookup table parked by
+ # PageRank must not claim the repo depends on it.
+ reason = (
+ "Off the import paths walked above — a standalone or "
+ "supporting file."
+ )
elif d == 1:
- reason = "Directly used by the entry points above; a core collaborator."
+ # Anchor-seeded walks have no entry points — the reason must not
+ # invent them. When a co-anchor rescued a wiring-stub entry, the
+ # depth-1 files were reached through the anchor, not the entry.
+ reason = (
+ "Directly used by the entry points above; a core collaborator."
+ if genuine_entries and not anchor_seeds
+ else "Directly imported by the anchor above; a core collaborator."
+ )
else:
reason = f"Reached {d} imports deep — a supporting building block."
stops.append(
diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.py
index 392c553a0..0bfcb4efd 100644
--- a/packages/core/src/repowise/core/ingestion/call_resolver.py
+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py
@@ -221,6 +221,7 @@ class CallResolver:
def __init__(self, rp: str, pf: dict[str, ParsedFile]) -> None:
self.repo_path = Path(rp)
self.path_set = set(pf.keys())
+ self.sorted_paths = tuple(sorted(self.path_set))
self.parsed_files = pf
self.go_modules: tuple[tuple[str, str], ...] = ()
self.go_module_path: str | None = None
@@ -255,6 +256,7 @@ class CallResolver:
def __init__(self, rp: str, pf: dict[str, ParsedFile]) -> None:
self.repo_path = Path(rp)
self.path_set = set(pf.keys())
+ self.sorted_paths = tuple(sorted(self.path_set))
self.parsed_files = pf
self.stem_map: dict[str, list[str]] = {}
@@ -299,6 +301,7 @@ class CallResolver:
def __init__(self, rp: str, pf: dict[str, ParsedFile]) -> None:
self.repo_path = Path(rp)
self.path_set = set(pf.keys())
+ self.sorted_paths = tuple(sorted(self.path_set))
self.parsed_files = pf
self._jvm_index = build_jvm_workspace_index(_Ctx(self._repo_path, self._parsed_files))
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
index d51d57f40..cad37b25d 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
@@ -83,7 +83,7 @@ class HintRegistry:
Extractors run in a thread pool — their work is I/O-bound and
releases the GIL during filesystem reads, so threads are the
right tool (no per-process startup overhead, no pickling).
- Order of edges in the returned list is not guaranteed.
+ The returned list is deterministically sorted.
"""
edges: list[DynamicEdge] = []
if not self._extractors:
@@ -100,6 +100,9 @@ class HintRegistry:
continue
edges.extend(got)
log.debug("dynamic_hints", extractor=ex.name, count=len(got))
+ # Thread-completion order varies run-to-run; sort so downstream graph
+ # construction (and therefore the exported KG) stays deterministic.
+ edges.sort(key=lambda e: (e.source, e.target, e.edge_type, e.hint_source, e.weight))
return edges
@staticmethod
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/scala.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/scala.py
index adca0d269..b95c4431a 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/scala.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/scala.py
@@ -1,4 +1,4 @@
-"""Scala import-binding extraction."""
+"""Scala import-binding extraction and import-clause expansion."""
from __future__ import annotations
@@ -8,6 +8,73 @@ from ...models import NamedBinding
from ..helpers import node_text
+def expand_scala_import_clauses(
+ stmt_node: Node, src: str
+) -> list[tuple[str, list[str]]]:
+ """Expand one Scala ``import_declaration`` into (module_path, names) pairs.
+
+ The grammar query captures only the first ``identifier`` child, so the
+ parser reconstructs full dotted paths here. One declaration can carry
+ several clauses; each yields one or more pairs:
+
+ - ``import com.foo.Bar`` → ``[("com.foo.Bar", ["Bar"])]``
+ - ``import com.foo._`` / ``.*`` → ``[("com.foo.*", ["*"])]``
+ (Scala 3 ``given`` imports normalise to the same package wildcard —
+ the file depends on that package's givens)
+ - ``import com.foo.{A, B}`` → one pair per selected name
+ - ``import com.foo.{A => B}`` → ``[("com.foo.A", ["B"])]``
+ - ``import com.foo.{A => _, _}`` → hidden ``A`` skipped, wildcard kept
+ - ``import a.B, c.D`` → one pair per clause
+ """
+ # Split the declaration's children into comma-separated clauses.
+ clauses: list[tuple[list[str], Node | None]] = []
+ segments: list[str] = []
+ trailer: Node | None = None # namespace_wildcard | namespace_selectors
+
+ def _flush() -> None:
+ nonlocal segments, trailer
+ if segments or trailer is not None:
+ clauses.append((segments, trailer))
+ segments, trailer = [], None
+
+ for child in stmt_node.children:
+ if child.type == "identifier":
+ segments.append(node_text(child, src))
+ elif child.type in ("namespace_wildcard", "namespace_selectors"):
+ trailer = child
+ elif child.type == ",":
+ _flush()
+ _flush()
+
+ results: list[tuple[str, list[str]]] = []
+ for segs, trail in clauses:
+ base = ".".join(segs)
+ if trail is None:
+ if base:
+ results.append((base, [segs[-1]]))
+ elif trail.type == "namespace_wildcard":
+ if base:
+ results.append((f"{base}.*", ["*"]))
+ else: # namespace_selectors: {A, B => C, _}
+ for sel in trail.children:
+ if sel.type == "identifier":
+ name = node_text(sel, src)
+ if base and name != "_":
+ results.append((f"{base}.{name}", [name]))
+ elif sel.type == "arrow_renamed_identifier":
+ parts = node_text(sel, src).split("=>")
+ if len(parts) != 2 or not base:
+ continue
+ source, local = parts[0].strip(), parts[1].strip()
+ if local == "_":
+ continue # hidden import: {A => _} excludes A
+ results.append((f"{base}.{source}", [local]))
+ elif sel.type == "namespace_wildcard":
+ if base:
+ results.append((f"{base}.*", ["*"]))
+ return results
+
+
def extract_scala_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
"""Extract bindings from Scala import declarations."""
names: list[str] = []
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
index 497b29e85..f06a02f19 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
@@ -170,3 +170,53 @@ def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[N
bindings.append(NamedBinding(local_name="*", exported_name=None, source_file=None))
return names, bindings
+
+
+def collect_cjs_requires(stmt_node: Node, src: str) -> list[str]:
+ """Collect every ``require('<literal>')`` module string inside *stmt_node*.
+
+ Used for the CommonJS assignment / ``Object.assign`` shapes
+ (``module.exports = require('./x')``,
+ ``Object.assign(module.exports, require('./a'), require('./b'))``)
+ where the query captures the outer statement once — the parser then
+ walks it for ALL contained requires so multi-require hubs survive
+ raw-statement dedup.
+ """
+ out: list[str] = []
+
+ def _walk(node: Node) -> None:
+ if node.type == "call_expression":
+ fn = node.child_by_field_name("function")
+ if fn is not None and fn.type == "identifier" and node_text(fn, src) == "require":
+ args = node.child_by_field_name("arguments")
+ if args is not None:
+ for child in args.named_children:
+ if child.type == "string":
+ module = node_text(child, src).strip("\"'`")
+ if module:
+ out.append(module)
+ break # first argument only
+ for child in node.children:
+ _walk(child)
+
+ _walk(stmt_node)
+ return out
+
+
+def cjs_statement_is_reexport(stmt_node: Node, src: str) -> bool:
+ """True when a CJS require statement re-exports through ``module.exports``.
+
+ Climbs to the enclosing statement and inspects the text *before* the
+ first ``require`` — ``module.exports = require(...)``,
+ ``exports.foo = require(...)`` and
+ ``Object.assign(module.exports, require(...))`` all qualify;
+ ``app.use(require('./mw'))`` does not.
+ """
+ ctx = stmt_node
+ parent = stmt_node.parent
+ while parent is not None and parent.type not in ("program", "statement_block"):
+ ctx = parent
+ parent = parent.parent
+ head = node_text(ctx, src).split("require", 1)[0]
+ stripped = head.lstrip()
+ return "module.exports" in head or stripped.startswith("exports.")
diff --git a/packages/core/src/repowise/core/ingestion/graph/_metrics.py b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
index 377c52f17..747e4a458 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_metrics.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_metrics.py
@@ -296,7 +296,11 @@ class MetricsMixin:
n = g.number_of_nodes()
if n > _LARGE_REPO_THRESHOLD:
k = min(500, n)
- values = nx.betweenness_centrality(g, k=k, normalized=True)
+ # Seeded: k-sampling is the one randomized kernel left in the
+ # pipeline — unseeded it made every large-repo index emit a
+ # different betweenness ranking (typst's entry-point order
+ # flapped between runs).
+ values = nx.betweenness_centrality(g, k=k, normalized=True, seed=42)
else:
from ._betweenness import betweenness_centrality_fast
diff --git a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
index 62c94ae56..5f8804b5e 100644
--- a/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
+++ b/packages/core/src/repowise/core/ingestion/graph/_resolvers.py
@@ -105,6 +105,334 @@ class ResolveMixin:
if callable(done):
done(phase)
+ def _resolve_jvm_same_package(self, ctx: Any, progress: Any | None = None) -> None:
+ """Emit same-package ``imports`` edges for JVM files.
+
+ JVM languages reference same-package types without an import
+ statement, so cohesive packages otherwise produce zero edges
+ between sibling files. Conservative text-level scan against the
+ JVM workspace index (already built — cached on *ctx* — by the
+ import resolution phase).
+ """
+ from ..languages.jvm_same_package import (
+ collect_jvm_source_texts,
+ resolve_jvm_same_package_refs,
+ )
+ from ..resolvers.jvm_workspace import get_or_build_jvm_index
+
+ has_jvm = any(
+ pf.file_info.language in ("java", "kotlin", "scala")
+ for pf in self._parsed_files.values()
+ )
+ if not has_jvm:
+ return
+
+ phase = "graph.same_package"
+ if progress:
+ progress.on_phase_start(phase, None)
+ try:
+ jvm_index = get_or_build_jvm_index(ctx)
+ texts = collect_jvm_source_texts(self._parsed_files)
+ added = resolve_jvm_same_package_refs(self._graph, jvm_index, texts)
+ log.info("same_package_edges", added=added)
+ except Exception as exc:
+ log.warning("jvm_same_package_failed", error=str(exc))
+ finally:
+ if progress:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase)
+
+ def _resolve_csharp_same_namespace(self, ctx: Any, progress: Any | None = None) -> None:
+ """Emit same-namespace / global-using ``imports`` edges for C# files.
+
+ C# references same-namespace types with no using directive, and
+ ``global using`` / csproj ``<Using>`` items make namespaces visible
+ project-wide — both leave cohesive code (and whole test suites)
+ looking like zero-edge orphans. Conservative text-level scan, same
+ shape as the JVM same-package pass.
+ """
+ from ..languages.csharp_member_reads import collect_csharp_source_texts
+ from ..languages.csharp_same_namespace import (
+ resolve_csharp_same_namespace_refs,
+ )
+ from ..resolvers.dotnet import get_or_build_index
+
+ has_csharp = any(
+ pf.file_info.language == "csharp" for pf in self._parsed_files.values()
+ )
+ if not has_csharp:
+ return
+
+ phase = "graph.same_namespace"
+ if progress:
+ progress.on_phase_start(phase, None)
+ try:
+ index = get_or_build_index(ctx)
+ cs_texts = collect_csharp_source_texts(self._parsed_files)
+ repo = getattr(index, "repo_path", None) if index is not None else None
+ added = resolve_csharp_same_namespace_refs(
+ self._graph, index, cs_texts, repo
+ )
+ log.info("same_namespace_edges", language="csharp", added=added)
+ except Exception as exc:
+ log.warning("csharp_same_namespace_failed", error=str(exc))
+ finally:
+ if progress:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase)
+
+ def _resolve_ruby_spec_mirrors(self, progress: Any | None = None) -> None:
+ """Link rspec files to their subjects by the directory-mirror convention.
+
+ RSpec loads ``spec_helper`` through ``.rspec`` and resolves the
+ subject constant at runtime, so a typical spec file contains *no*
+ require at all — every ``spec/lib/rack/protection/base_spec.rb``
+ reads as a zero-edge orphan. The rspec convention mirrors the
+ source tree: ``<root>/spec/<sub>/<name>_spec.rb`` tests
+ ``<root>/<sub>/<name>.rb`` (or ``<root>/lib/<sub>/<name>.rb``).
+ """
+ ruby_files = [
+ p
+ for p, pf in self._parsed_files.items()
+ if pf.file_info.language == "ruby"
+ ]
+ if not ruby_files:
+ return
+
+ phase = "graph.spec_mirrors"
+ if progress:
+ progress.on_phase_start(phase, None)
+ try:
+ added = 0
+ for p in sorted(ruby_files):
+ if not p.endswith("_spec.rb") or "/spec/" not in f"/{p}":
+ continue
+ prefix, _, sub = f"/{p}".rpartition("/spec/")
+ root = prefix.lstrip("/")
+ subject_rel = sub[: -len("_spec.rb")] + ".rb"
+ candidates = []
+ for mid in ("", "lib/"):
+ joined = "/".join(s for s in (root, mid.rstrip("/"), subject_rel) if s)
+ candidates.append(joined)
+ for cand in candidates:
+ if cand == p or cand not in self._parsed_files:
+ continue
+ if not self._graph.has_node(p) or not self._graph.has_node(cand):
+ continue
+ if self._graph.has_edge(p, cand):
+ break
+ self._graph.add_edge(
+ p,
+ cand,
+ edge_type="imports",
+ imported_names=[],
+ hint_source="spec_mirror",
+ )
+ added += 1
+ break
+ log.info("spec_mirror_edges", language="ruby", added=added)
+ except Exception as exc:
+ log.warning("ruby_spec_mirrors_failed", error=str(exc))
+ finally:
+ if progress:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase)
+
+ def _resolve_cpp_header_pairs(self, progress: Any | None = None) -> None:
+ """Pair C/C++ headers with their same-stem same-dir implementations.
+
+ ``foo.c`` → ``foo.h`` exists via the #include, but nothing ever
+ points ``foo.h`` → ``foo.c`` — so a consumer that includes the
+ header can never reach the implementation and every ``.c`` whose
+ only relationship is "implements its header" reads as orphaned.
+ The pairing edge makes BFS transit headers into implementations.
+ """
+ header_exts = (".h", ".hpp", ".hxx", ".hh", ".h++")
+ source_exts = (".c", ".cc", ".cpp", ".cxx", ".c++")
+
+ cpp_files = [
+ p
+ for p, pf in self._parsed_files.items()
+ if pf.file_info.language in ("c", "cpp")
+ ]
+ if not cpp_files:
+ return
+
+ phase = "graph.header_pairs"
+ if progress:
+ progress.on_phase_start(phase, None)
+ try:
+ from pathlib import PurePosixPath
+
+ by_dir_stem: dict[tuple[str, str], dict[str, list[str]]] = {}
+ for p in cpp_files:
+ pp = PurePosixPath(p)
+ suffix = pp.suffix.lower()
+ if suffix in header_exts:
+ kind = "header"
+ elif suffix in source_exts:
+ kind = "source"
+ else:
+ continue
+ key = (pp.parent.as_posix(), pp.stem.lower())
+ by_dir_stem.setdefault(key, {}).setdefault(kind, []).append(p)
+
+ added = 0
+ for _key, kinds in sorted(by_dir_stem.items()):
+ headers = sorted(kinds.get("header", []))
+ sources = sorted(kinds.get("source", []))
+ for h in headers:
+ for s in sources:
+ for a, b in ((h, s), (s, h)):
+ if not self._graph.has_node(a) or not self._graph.has_node(b):
+ continue
+ if self._graph.has_edge(a, b):
+ continue
+ self._graph.add_edge(
+ a,
+ b,
+ edge_type="imports",
+ imported_names=[],
+ hint_source="header_source_pair",
+ )
+ added += 1
+ log.info("header_pair_edges", added=added)
+ except Exception as exc:
+ log.warning("cpp_header_pairs_failed", error=str(exc))
+ finally:
+ if progress:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase)
+
+ def _resolve_csharp_partials(self, ctx: Any, progress: Any | None = None) -> None:
+ """Link C# ``partial`` co-fragments of one type bidirectionally.
+
+ Fragments of a partial class across files are literally one
+ class — without these edges the secondary fragment files read as
+ disconnected from their own type.
+ """
+ from ..resolvers.dotnet import get_or_build_index
+
+ has_csharp = any(
+ pf.file_info.language == "csharp" for pf in self._parsed_files.values()
+ )
+ if not has_csharp:
+ return
+
+ phase = "graph.partials"
+ if progress:
+ progress.on_phase_start(phase, None)
+ try:
+ index = get_or_build_index(ctx)
+ added = 0
+ if index is not None and index.partial_types:
+ repo = index.repo_path
+ for fqn, files in sorted(index.partial_types.items()):
+ rels = []
+ for f in files:
+ try:
+ rel = f.resolve().relative_to(repo).as_posix()
+ except (OSError, ValueError):
+ continue
+ if self._graph.has_node(rel):
+ rels.append(rel)
+ if len(rels) < 2:
+ continue
+ local_name = fqn.rsplit(".", 1)[-1]
+ for a in rels:
+ for b in rels:
+ if a == b or self._graph.has_edge(a, b):
+ continue
+ self._graph.add_edge(
+ a,
+ b,
+ edge_type="imports",
+ imported_names=[local_name],
+ hint_source="partial_class",
+ )
+ added += 1
+ log.info("partial_class_edges", language="csharp", added=added)
+ except Exception as exc:
+ log.warning("csharp_partials_failed", error=str(exc))
+ finally:
+ if progress:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase)
+
+ def _resolve_swift_same_module(self, ctx: Any, progress: Any | None = None) -> None:
+ """Emit same-module ``imports`` edges for Swift files.
+
+ Swift has no intra-module imports by design — every file in an
+ SPM target sees every sibling's top-level declarations — so
+ targets otherwise read as edge deserts. Conservative text-level
+ scan against the per-target declared-type map.
+ """
+ from ..languages.swift_same_module import (
+ collect_swift_source_texts,
+ resolve_swift_same_module_refs,
+ )
+ from ..resolvers.swift_spm import get_or_build_swift_targets
+
+ has_swift = any(
+ pf.file_info.language == "swift" for pf in self._parsed_files.values()
+ )
+ if not has_swift:
+ return
+
+ phase = "graph.same_module"
+ if progress:
+ progress.on_phase_start(phase, None)
+ try:
+ swift_targets = get_or_build_swift_targets(ctx)
+ texts = collect_swift_source_texts(self._parsed_files)
+ added = resolve_swift_same_module_refs(self._graph, swift_targets, texts)
+ log.info("same_module_edges", language="swift", added=added)
+ except Exception as exc:
+ log.warning("swift_same_module_failed", error=str(exc))
+ finally:
+ if progress:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase)
+
+ def _resolve_fsharp_compile_order(self, ctx: Any, progress: Any | None = None) -> None:
+ """Emit fsproj compile-order ``imports`` hint edges for F# files.
+
+ F# compiles project files in fsproj declaration order and a file
+ may only reference earlier files — the order is a real dependency
+ constraint. Adjacent pairs contribute ``later → earlier`` edges so
+ projects whose files rarely ``open`` their own namespaces don't
+ read as edge deserts.
+ """
+ from ..languages.fsharp_compile_order import add_fsharp_compile_order_edges
+
+ has_fsharp = any(
+ pf.file_info.language == "fsharp" for pf in self._parsed_files.values()
+ )
+ if not has_fsharp or ctx.repo_path is None:
+ return
+
+ phase = "graph.compile_order"
+ if progress:
+ progress.on_phase_start(phase, None)
+ try:
+ added = add_fsharp_compile_order_edges(
+ self._graph, ctx.repo_path, prune_nested_git=ctx.prune_nested_git
+ )
+ log.info("compile_order_edges", language="fsharp", added=added)
+ except Exception as exc:
+ log.warning("fsharp_compile_order_failed", error=str(exc))
+ finally:
+ if progress:
+ done = getattr(progress, "on_phase_done", None)
+ if callable(done):
+ done(phase)
+
def _resolve_go_interface_satisfaction(self, progress: Any | None = None) -> None:
"""Emit ``method_implements`` edges for Go structural interface
satisfaction.
diff --git a/packages/core/src/repowise/core/ingestion/graph/builder.py b/packages/core/src/repowise/core/ingestion/graph/builder.py
index f50922783..1515e12bc 100644
--- a/packages/core/src/repowise/core/ingestion/graph/builder.py
+++ b/packages/core/src/repowise/core/ingestion/graph/builder.py
@@ -302,6 +302,10 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
from ..resolvers.kotlin import resolve_kotlin_import_all
targets = resolve_kotlin_import_all(imp.module_path, path, ctx)
+ elif _lang == "scala":
+ from ..resolvers.scala import resolve_scala_import_all
+
+ targets = resolve_scala_import_all(imp.module_path, path, ctx)
elif _lang in ("cpp", "c"):
# Fan-out across sibling TUs in the same CMake/Bazel
# target so a public header reached by one ``.cc`` is
@@ -375,6 +379,44 @@ class GraphBuilder(MetricsMixin, ResolveMixin, EdgesMixin, SerializeMixin, Rehyd
# unused_export false positives (audit #23).
self._resolve_member_reads(progress=progress)
+ # --- Ruby rspec directory-mirror edges ---
+ # Spec files carry no requires (rspec wires the helper + subject
+ # at runtime); the spec/ <-> lib/ mirror convention links them.
+ self._resolve_ruby_spec_mirrors(progress=progress)
+
+ # --- C/C++ header ↔ implementation pairing ---
+ # foo.h -> foo.c (same stem, same dir): consumers including the
+ # header must be able to reach the implementation.
+ self._resolve_cpp_header_pairs(progress=progress)
+
+ # --- C# partial-class co-fragments ---
+ # Fragments of one partial type across files are literally one
+ # class; link them bidirectionally so neither reads as orphaned.
+ self._resolve_csharp_partials(ctx, progress=progress)
+
+ # --- JVM same-package implicit references ---
+ # Java/Kotlin (and Scala) reference same-package types without an
+ # import statement; emit conservative sibling edges so cohesive
+ # packages don't read as disconnected files.
+ self._resolve_jvm_same_package(ctx, progress=progress)
+
+ # --- C# same-namespace + global-using implicit references ---
+ # C# references same-namespace types with no using directive, and
+ # global usings make namespaces visible project-wide; emit
+ # conservative sibling edges so neither reads as orphaned.
+ self._resolve_csharp_same_namespace(ctx, progress=progress)
+
+ # --- Swift intra-module type references ---
+ # Swift files see same-target siblings with no import statement;
+ # emit conservative type-reference edges per SPM target.
+ self._resolve_swift_same_module(ctx, progress=progress)
+
+ # --- F# fsproj compile-order spine ---
+ # fsproj <Compile Include> order is a real dependency constraint
+ # (files may only reference earlier files); adjacent pairs keep
+ # open-light projects connected.
+ self._resolve_fsharp_compile_order(ctx, progress=progress)
+
# --- Phase 2: Resolve heritage (extends/implements) ---
self._resolve_heritage(import_targets, progress=progress)
diff --git a/packages/core/src/repowise/core/ingestion/graph_warmups.py b/packages/core/src/repowise/core/ingestion/graph_warmups.py
index 2620dab6b..5bcf1442e 100644
--- a/packages/core/src/repowise/core/ingestion/graph_warmups.py
+++ b/packages/core/src/repowise/core/ingestion/graph_warmups.py
@@ -34,7 +34,7 @@ if TYPE_CHECKING:
Warmup = Callable[["ResolverContext"], None]
-def _warmup_jvm(ctx: "ResolverContext") -> None:
+def _warmup_jvm(ctx: ResolverContext) -> None:
from .resolvers.jvm_workspace import get_or_build_jvm_index
index = get_or_build_jvm_index(ctx)
@@ -99,7 +99,7 @@ def _warmup_jvm(ctx: "ResolverContext") -> None:
nd["is_never_flag"] = True
-def _warmup_cpp(ctx: "ResolverContext") -> None:
+def _warmup_cpp(ctx: ResolverContext) -> None:
"""Build the C/C++ workspace index and propagate workspace-discovered
export macros back into the graph.
@@ -203,7 +203,7 @@ def _mark_cpp_entry_point_files(parsed_files: dict, graph: Any) -> None:
if not abs_path:
continue
try:
- with open(abs_path, "r", encoding="utf-8", errors="replace") as f:
+ with open(abs_path, encoding="utf-8", errors="replace") as f:
src = f.read()
except OSError:
continue
@@ -214,19 +214,79 @@ def _mark_cpp_entry_point_files(parsed_files: dict, graph: Any) -> None:
node["is_entry_point"] = True
-def _warmup_dotnet(ctx: "ResolverContext") -> None:
+_SWIFT_ENTRY_RE = None # compiled lazily inside _warmup_swift
+
+
+def _warmup_swift(ctx: ResolverContext) -> None:
+ """Stamp ``is_entry_point`` on Swift files carrying an entry attribute.
+
+ ``@main`` / ``@UIApplicationMain`` / ``@NSApplicationMain`` mark the
+ process entry type; no call edge ever points at it, so without the
+ flag the app's actual starting point reads as unreachable.
+ """
+ import re
+
+ global _SWIFT_ENTRY_RE
+ if _SWIFT_ENTRY_RE is None:
+ _SWIFT_ENTRY_RE = re.compile(
+ r"^\s*@(?:main|UIApplicationMain|NSApplicationMain)\b", re.MULTILINE
+ )
+
+ graph = getattr(ctx, "graph", None)
+ parsed_files = getattr(ctx, "parsed_files", None) or {}
+ if graph is None:
+ return
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "swift":
+ continue
+ abs_path = getattr(parsed.file_info, "abs_path", None)
+ if not abs_path:
+ continue
+ try:
+ with open(abs_path, encoding="utf-8", errors="replace") as f:
+ src = f.read()
+ except OSError:
+ continue
+ if not _SWIFT_ENTRY_RE.search(src):
+ continue
+ node = graph.nodes.get(path)
+ if node is not None:
+ node["is_entry_point"] = True
+
+
+def _warmup_dotnet(ctx: ResolverContext) -> None:
from .resolvers.dotnet import get_or_build_index
get_or_build_index(ctx)
-def _warmup_go(ctx: "ResolverContext") -> None:
+def _warmup_go(ctx: ResolverContext) -> None:
+ """Build the Go package index and stamp ``is_entry_point`` on every
+ ``package main`` file declaring ``func main()``. Go's entry convention
+ is semantic, not filename-based — ``cmd/task/task.go`` is as much a
+ binary entry as ``cmd/release/main.go``, so the traverser's stem
+ heuristic alone misses real binaries.
+ """
from .resolvers.go_workspace import get_or_build_go_index
- get_or_build_go_index(ctx)
-
-
-def _warmup_typescript(ctx: "ResolverContext") -> None:
+ index = get_or_build_go_index(ctx)
+ graph = getattr(ctx, "graph", None)
+ parsed = getattr(ctx, "parsed_files", None) or {}
+ for pkg in index.packages.values():
+ for path in pkg.main_files:
+ # The graph attribute feeds dead-code reachability; the parsed
+ # FileInfo flag feeds the exported KG's entry tags and the tour
+ # seeds — both surfaces must agree.
+ if graph is not None:
+ node = graph.nodes.get(path)
+ if node is not None:
+ node["is_entry_point"] = True
+ pf = parsed.get(path)
+ if pf is not None and getattr(pf, "file_info", None) is not None:
+ pf.file_info.is_entry_point = True
+
+
+def _warmup_typescript(ctx: ResolverContext) -> None:
"""Build the TS workspace index and stamp ``is_entry_point`` on every
source file the workspace's ``package.json`` ``exports`` map resolves
to. Without this, files reachable only through the package boundary
@@ -286,12 +346,13 @@ _WARMUPS: dict[str, tuple[str, Warmup]] = {
"javascript": ("graph.ts_index", _warmup_typescript),
"cpp": ("graph.cpp_index", _warmup_cpp),
"c": ("graph.cpp_index", _warmup_cpp),
+ "swift": ("graph.swift_entry", _warmup_swift),
}
def run_warmups(
- parsed_files: dict[str, "ParsedFile"],
- ctx: "ResolverContext",
+ parsed_files: dict[str, ParsedFile],
+ ctx: ResolverContext,
progress: Any | None = None,
) -> None:
"""Run every registered warmup whose language appears in ``parsed_files``.
diff --git a/packages/core/src/repowise/core/ingestion/language_configs.py b/packages/core/src/repowise/core/ingestion/language_configs.py
index 87da837e1..0f0065919 100644
--- a/packages/core/src/repowise/core/ingestion/language_configs.py
+++ b/packages/core/src/repowise/core/ingestion/language_configs.py
@@ -57,8 +57,6 @@ class LanguageConfig:
# Node types that indicate a class context (used with "nesting" mode)
parent_class_types: frozenset[str] = field(default_factory=frozenset)
- # Entry-point filename patterns for this language
- entry_point_patterns: list[str] = field(default_factory=list)
LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
@@ -72,7 +70,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=py_visibility,
parent_extraction="nesting",
parent_class_types=frozenset({"class_definition"}),
- entry_point_patterns=["main.py", "app.py", "__main__.py", "manage.py", "wsgi.py"],
),
"typescript": LanguageConfig(
symbol_node_types={
@@ -92,7 +89,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=ts_visibility,
parent_extraction="nesting",
parent_class_types=frozenset({"class_declaration", "abstract_class_declaration"}),
- entry_point_patterns=["index.ts", "main.ts", "app.ts", "server.ts"],
),
"javascript": LanguageConfig(
symbol_node_types={
@@ -108,7 +104,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=public_by_default,
parent_extraction="nesting",
parent_class_types=frozenset({"class_declaration"}),
- entry_point_patterns=["index.js", "main.js", "app.js", "server.js"],
),
"go": LanguageConfig(
symbol_node_types={
@@ -123,7 +118,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=go_visibility,
parent_extraction="receiver",
parent_class_types=frozenset(),
- entry_point_patterns=["main.go", "cmd/main.go"],
),
"rust": LanguageConfig(
symbol_node_types={
@@ -146,7 +140,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=rust_visibility,
parent_extraction="impl",
parent_class_types=frozenset({"impl_item", "mod_item"}),
- entry_point_patterns=["main.rs", "lib.rs"],
),
"java": LanguageConfig(
symbol_node_types={
@@ -164,7 +157,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
parent_class_types=frozenset(
{"class_declaration", "interface_declaration", "enum_declaration", "record_declaration"}
),
- entry_point_patterns=["Main.java", "Application.java"],
),
"cpp": LanguageConfig(
symbol_node_types={
@@ -185,7 +177,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=public_by_default,
parent_extraction="nesting",
parent_class_types=frozenset({"class_specifier", "struct_specifier"}),
- entry_point_patterns=["main.cpp", "main.cc"],
),
"c": LanguageConfig(
symbol_node_types={
@@ -202,7 +193,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=public_by_default,
parent_extraction="none",
parent_class_types=frozenset(),
- entry_point_patterns=["main.c"],
),
"kotlin": LanguageConfig(
symbol_node_types={
@@ -217,7 +207,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=kotlin_visibility,
parent_extraction="nesting",
parent_class_types=frozenset({"class_declaration", "object_declaration"}),
- entry_point_patterns=["Main.kt", "Application.kt"],
),
"ruby": LanguageConfig(
symbol_node_types={
@@ -232,7 +221,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=public_by_default,
parent_extraction="nesting",
parent_class_types=frozenset({"class", "module"}),
- entry_point_patterns=["main.rb", "app.rb", "config.ru"],
),
"csharp": LanguageConfig(
symbol_node_types={
@@ -267,7 +255,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"file_scoped_namespace_declaration",
}
),
- entry_point_patterns=["Program.cs", "Startup.cs"],
),
"swift": LanguageConfig(
symbol_node_types={
@@ -283,7 +270,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=swift_visibility,
parent_extraction="nesting",
parent_class_types=frozenset({"class_declaration", "protocol_declaration"}),
- entry_point_patterns=["main.swift", "App.swift"],
),
"scala": LanguageConfig(
symbol_node_types={
@@ -302,7 +288,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=scala_visibility,
parent_extraction="nesting",
parent_class_types=frozenset({"class_definition", "trait_definition", "object_definition"}),
- entry_point_patterns=["Main.scala", "App.scala"],
),
"php": LanguageConfig(
symbol_node_types={
@@ -322,7 +307,6 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
parent_class_types=frozenset(
{"class_declaration", "interface_declaration", "trait_declaration", "enum_declaration"}
),
- entry_point_patterns=["index.php", "public/index.php"],
),
"luau": LanguageConfig(
symbol_node_types={
@@ -334,6 +318,5 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=public_by_default,
parent_extraction="none",
parent_class_types=frozenset(),
- entry_point_patterns=["init.luau", "init.lua"],
),
}
diff --git a/packages/core/src/repowise/core/ingestion/languages/csharp_same_namespace.py b/packages/core/src/repowise/core/ingestion/languages/csharp_same_namespace.py
new file mode 100644
index 000000000..38b4dc2b0
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/csharp_same_namespace.py
@@ -0,0 +1,238 @@
+"""C# same-namespace + global-using implicit reference resolution.
+
+Background
+----------
+C# needs no ``using`` directive for types declared in the same namespace —
+``class RetryPolicy : PolicyBase`` compiles with zero usings when
+``PolicyBase`` lives in a sibling file of the same namespace. On top of
+that, C# 10 ``global using`` directives and MSBuild ``<Using Include>``
+items make whole namespaces visible to every file of a project, so test
+projects routinely contain *no* per-file usings at all. Both cases
+produce **no edge at all** under plain import resolution, which makes the
+most cohesive parts of a C# codebase (and entire xunit suites) read as
+disconnected orphans.
+
+This pass mirrors the JVM same-package prior art
+(:mod:`.jvm_same_package`): a self-contained, regex-driven scan over raw
+source text that emits conservative ``imports`` edges after the regular
+import-resolution phases ran.
+
+For each C# file A, every capitalized identifier in A's source is checked
+against the types declared in A's *candidate namespaces*: first A's own
+declared namespace(s) (closest scope wins, per C# lookup rules), then the
+project's global-using namespaces that exist locally in the repo. An edge
+A → B is emitted only when ALL of:
+
+- the identifier names a type declared in exactly **one** file of the
+ candidate namespace tier (ambiguous names — declared in two or more
+ files — produce no edge to anyone; a wrong edge is worse than a
+ missing one);
+- B is not A itself, and the type is not also declared in A;
+- the identifier is not a ubiquitous BCL type name (``String``,
+ ``Task``, … — overwhelmingly stdlib references);
+- the identifier is not the target of a ``using Alias = …`` directive
+ in A (the alias shadows it);
+- for the global-using tier only: the identifier is not declared in a
+ namespace A explicitly ``using``s (the explicit using already resolved
+ through the normal import path and wins);
+- no edge A → B already exists (a real import wins).
+
+C# members are PascalCase, so a method sharing a sibling type's name can
+match — accepted: the ambiguity guard plus locally-declared-types-only
+lookup keeps the false-positive surface small, and such name collisions
+usually indicate real coupling (``Policy.Retry()`` ↔ ``Retry``).
+
+Emitted edges are ``imports`` edges carrying
+``hint_source="same_namespace"`` (own namespace) or
+``hint_source="global_using"`` (project-wide usings) so density metrics
+count them separately and any false positive is diagnosable.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+ from ..resolvers.dotnet.index import DotNetProjectIndex
+
+# Capitalized identifier — candidate type reference.
+_TYPE_IDENT_RE = re.compile(r"\b[A-Z][A-Za-z0-9_]*\b")
+
+# ``using Foo.Bar;`` / ``global using Foo.Bar;`` — namespace usings.
+_USING_NS_RE = re.compile(
+ r"^\s*(?:global\s+)?using\s+(?:static\s+)?([A-Za-z_][\w.]*)\s*;", re.MULTILINE
+)
+
+# ``using Alias = Foo.Bar.Baz;`` — the alias name shadows bare identifiers.
+_USING_ALIAS_RE = re.compile(
+ r"^\s*(?:global\s+)?using\s+([A-Za-z_]\w*)\s*=", re.MULTILINE
+)
+
+# Ubiquitous BCL type names — references are overwhelmingly stdlib, so a
+# local type sharing the name never gets a same-namespace hint edge.
+_BCL_COMMON_TYPES = frozenset({
+ "String", "Object", "Boolean", "Byte", "SByte", "Char", "Decimal",
+ "Double", "Single", "Int16", "Int32", "Int64", "UInt16", "UInt32",
+ "UInt64", "IntPtr", "UIntPtr", "Void", "Type", "Array", "Enum",
+ "Delegate", "Attribute", "Exception", "ArgumentException",
+ "ArgumentNullException", "ArgumentOutOfRangeException",
+ "InvalidOperationException", "NotSupportedException",
+ "NotImplementedException", "NullReferenceException",
+ "OperationCanceledException", "TimeoutException", "AggregateException",
+ "ObjectDisposedException", "FormatException", "OverflowException",
+ "EventArgs", "EventHandler", "Action", "Func", "Predicate",
+ "Comparison", "Converter", "Tuple", "ValueTuple", "Nullable", "Lazy",
+ "WeakReference", "GC", "Console", "Convert", "Math", "Random",
+ "DateTime", "DateTimeOffset", "TimeSpan", "DateOnly", "TimeOnly",
+ "Guid", "Uri", "Version", "Environment", "Activator", "Buffer",
+ "BitConverter", "StringBuilder", "StringComparer", "StringComparison",
+ "Encoding", "Regex", "Match", "Group", "Capture",
+ "List", "Dictionary", "HashSet", "SortedSet", "SortedList",
+ "SortedDictionary", "Queue", "Stack", "LinkedList", "KeyValuePair",
+ "IEnumerable", "IEnumerator", "ICollection", "IList", "IDictionary",
+ "IReadOnlyList", "IReadOnlyCollection", "IReadOnlyDictionary",
+ "ISet", "IQueryable", "IGrouping", "ILookup", "IComparer",
+ "IEqualityComparer", "IComparable", "IEquatable", "IDisposable",
+ "IAsyncDisposable", "IFormattable", "ICloneable", "IServiceProvider",
+ "Task", "ValueTask", "CancellationToken", "CancellationTokenSource",
+ "Thread", "ThreadPool", "Monitor", "Mutex", "SemaphoreSlim",
+ "Interlocked", "Volatile", "SpinLock", "TaskCompletionSource",
+ "ConcurrentDictionary", "ConcurrentQueue", "ConcurrentStack",
+ "ConcurrentBag", "BlockingCollection",
+ "Stream", "MemoryStream", "FileStream", "StreamReader", "StreamWriter",
+ "TextReader", "TextWriter", "BinaryReader", "BinaryWriter", "File",
+ "Directory", "Path", "FileInfo", "DirectoryInfo",
+ "Span", "ReadOnlySpan", "Memory", "ReadOnlyMemory", "ArraySegment",
+ "Range", "Index", "Enumerable", "Linq",
+ "HttpClient", "HttpRequestMessage", "HttpResponseMessage",
+ "HttpMethod", "HttpStatusCode", "HttpContent", "StringContent",
+ "Debug", "Trace", "Debugger", "Stopwatch", "Process",
+ "CultureInfo", "Comparer", "EqualityComparer", "Expression",
+ "MethodInfo", "PropertyInfo", "FieldInfo", "ParameterInfo",
+ "Assembly", "AssemblyName", "BindingFlags",
+ "ObsoleteAttribute", "FlagsAttribute", "SerializableAttribute",
+ "ThreadStaticAttribute", "CallerMemberNameAttribute", "Obsolete",
+ "Flags", "Serializable", "CLSCompliant", "InternalsVisibleTo",
+})
+
+_SAME_NAMESPACE_HINT = "same_namespace"
+_GLOBAL_USING_HINT = "global_using"
+
+
+def build_namespace_type_index(
+ cs_texts: dict[str, str],
+) -> dict[str, dict[str, list[str]]]:
+ """Build ``namespace → {type_name: [declaring rel paths]}`` from source.
+
+ Reuses the dotnet resolver's declaration scanner so the type shapes
+ (file-scoped namespaces, modifier soup, records) match the namespace
+ map used by import resolution.
+ """
+ from ..resolvers.dotnet.namespace_map import scan_type_declarations
+
+ ns_types: dict[str, dict[str, list[str]]] = {}
+ for path in sorted(cs_texts):
+ for decl in scan_type_declarations(cs_texts[path]):
+ bucket = ns_types.setdefault(decl.namespace, {})
+ files = bucket.setdefault(decl.name, [])
+ if path not in files:
+ files.append(path)
+ return ns_types
+
+
+def resolve_csharp_same_namespace_refs(
+ graph: nx.DiGraph,
+ dotnet_index: DotNetProjectIndex | None,
+ cs_texts: dict[str, str],
+ repo_path: Path | None,
+) -> int:
+ """Emit same-namespace / global-using ``imports`` edges for C# files.
+
+ *cs_texts* maps repo-relative path → source text. Returns the number
+ of edges added.
+ """
+ from ..resolvers.dotnet.namespace_map import declared_namespaces
+
+ ns_types = build_namespace_type_index(cs_texts)
+
+ count = 0
+ for path in sorted(cs_texts):
+ text = cs_texts[path]
+ own_namespaces = list(dict.fromkeys(declared_namespaces(text)))
+ explicit_ns = [m.group(1) for m in _USING_NS_RE.finditer(text)]
+ alias_names = {m.group(1) for m in _USING_ALIAS_RE.finditer(text)}
+
+ # Project-wide usings (``global using`` files + csproj <Using>
+ # items + SDK implicit sets), restricted to namespaces that
+ # actually exist locally.
+ global_ns: list[str] = []
+ if dotnet_index is not None and repo_path is not None:
+ csproj = dotnet_index.file_to_project.get(
+ (repo_path / path).resolve()
+ )
+ if csproj is not None:
+ global_ns = sorted(
+ ns
+ for ns in dotnet_index.globals_for_project(csproj)
+ if ns in ns_types and ns not in own_namespaces
+ )
+
+ if not own_namespaces and not global_ns:
+ continue
+
+ # Types declared in namespaces this file explicitly ``using``s —
+ # those resolve through the normal import path and shadow the
+ # global-using tier.
+ explicit_types: set[str] = set()
+ for ns in explicit_ns:
+ explicit_types.update(ns_types.get(ns, ()))
+
+ # target file → (referenced names, hint source)
+ found: dict[str, tuple[list[str], str]] = {}
+ for ident in sorted(set(_TYPE_IDENT_RE.findall(text))):
+ if ident in _BCL_COMMON_TYPES or ident in alias_names:
+ continue
+ target: str | None = None
+ hint = _SAME_NAMESPACE_HINT
+ # Tier 1: the file's own namespace(s) — closest scope wins.
+ declaring: set[str] = set()
+ for ns in own_namespaces:
+ declaring.update(ns_types.get(ns, {}).get(ident, ()))
+ if declaring:
+ if len(declaring) != 1:
+ continue # ambiguous — no edge to anyone
+ target = next(iter(declaring))
+ elif global_ns:
+ if ident in explicit_types:
+ continue # explicit using already resolved it
+ hint = _GLOBAL_USING_HINT
+ declaring = set()
+ for ns in global_ns:
+ declaring.update(ns_types.get(ns, {}).get(ident, ()))
+ if len(declaring) != 1:
+ continue
+ target = next(iter(declaring))
+ if target is None or target == path:
+ continue
+ names, _ = found.setdefault(target, ([], hint))
+ names.append(ident)
+
+ for target, (names, hint) in sorted(found.items()):
+ if not graph.has_node(path) or not graph.has_node(target):
+ continue
+ if graph.has_edge(path, target):
+ continue # a real import (or stronger evidence) wins
+ graph.add_edge(
+ path,
+ target,
+ edge_type="imports",
+ imported_names=names,
+ hint_source=hint,
+ )
+ count += 1
+
+ return count
diff --git a/packages/core/src/repowise/core/ingestion/languages/fsharp_compile_order.py b/packages/core/src/repowise/core/ingestion/languages/fsharp_compile_order.py
new file mode 100644
index 000000000..56228ad2c
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/fsharp_compile_order.py
@@ -0,0 +1,72 @@
+"""F# compile-order dependency spine from fsproj ``<Compile Include>`` items.
+
+F# compiles a project's files in the declared order, and a file may only
+reference earlier files — the fsproj item order IS a real dependency
+constraint, not a heuristic. Each consecutive pair contributes one
+``imports`` hint edge (``later → earlier``); adjacent pairs keep the
+spine linear instead of quadratic, and the graph stays connected through
+the chain. ``hint_source="compile_order"`` marks the synthesis so density
+metrics can separate declared imports from project-file evidence.
+
+A real ``open``-resolved edge between the same pair wins (the pass never
+overwrites existing edges).
+"""
+
+from __future__ import annotations
+
+import itertools
+import posixpath
+import re
+from pathlib import Path
+
+import networkx as nx
+import structlog
+
+log = structlog.get_logger(__name__)
+
+_COMPILE_INCLUDE_RE = re.compile(r"<Compile\s+Include\s*=\s*\"([^\"]+)\"", re.I)
+
+_HINT = "compile_order"
+
+
+def _project_sources(fsproj: Path, repo_path: Path) -> list[str]:
+ """Repo-relative source paths in fsproj declaration order."""
+ try:
+ text = fsproj.read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ return []
+ project_dir = fsproj.parent
+ sources: list[str] = []
+ for raw in _COMPILE_INCLUDE_RE.findall(text):
+ rel = raw.replace("\\", "/")
+ if "*" in rel or "$(" in rel: # globs / MSBuild properties — skip
+ continue
+ try:
+ full = (project_dir / rel).resolve().relative_to(repo_path.resolve())
+ except (ValueError, OSError):
+ continue
+ sources.append(posixpath.normpath(full.as_posix()))
+ return sources
+
+
+def add_fsharp_compile_order_edges(
+ graph: nx.DiGraph, repo_path: Path, *, prune_nested_git: bool = True
+) -> int:
+ """Emit ``later → earlier`` hint edges per fsproj; return count added."""
+ from repowise.core.fs_walk import iter_glob
+
+ added = 0
+ for fsproj in sorted(iter_glob(repo_path, "*.fsproj", prune_nested_git=prune_nested_git)):
+ sources = [s for s in _project_sources(fsproj, repo_path) if graph.has_node(s)]
+ for earlier, later in itertools.pairwise(sources):
+ if graph.has_edge(later, earlier):
+ continue # a resolved open (or stronger evidence) wins
+ graph.add_edge(
+ later,
+ earlier,
+ edge_type="imports",
+ imported_names=[],
+ hint_source=_HINT,
+ )
+ added += 1
+ return added
diff --git a/packages/core/src/repowise/core/ingestion/languages/jvm_same_package.py b/packages/core/src/repowise/core/ingestion/languages/jvm_same_package.py
new file mode 100644
index 000000000..8ea252a75
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/jvm_same_package.py
@@ -0,0 +1,183 @@
+"""JVM same-package implicit reference resolution.
+
+Background
+----------
+JVM languages need no import statement for types declared in the same
+package — ``class OrderService { Order pending; }`` compiles with zero
+imports when ``Order`` lives in a sibling file of the same package. The
+import resolvers therefore produce **no edge at all** between the files
+of a tightly-coupled package, which makes exactly the most cohesive
+parts of a Java/Kotlin codebase look disconnected.
+
+This pass mirrors the C# member-reads prior art
+(:mod:`.csharp_member_reads`): a self-contained, regex-driven scan over
+raw source text that emits conservative graph edges after the regular
+import resolution phases ran.
+
+For each JVM file A in a multi-file package, every capitalized
+identifier in A's source is checked against the package's declared
+top-level types (from :class:`~..resolvers.jvm_workspace.JvmWorkspaceIndex`).
+An edge A → B is emitted only when ALL of:
+
+- the identifier names a top-level type declared in exactly **one**
+ package file B (ambiguous names — declared in two or more files —
+ produce no edge to anyone; a wrong edge is worse than a missing one);
+- B is not A itself, and the type is not also declared in A;
+- the identifier is not a ``java.lang`` / Kotlin default-import type
+ name (``String``, ``List``, ... — overwhelmingly stdlib references);
+- A does not explicitly import the same simple name from elsewhere
+ (an explicit import shadows the same-package type in JVM semantics);
+- no edge A → B already exists (a real import wins).
+
+Top-level **types only** — Kotlin top-level functions and properties
+are deliberately out of scope: lowercase callables collide with local
+identifiers far too often for a text-level scan.
+
+Emitted edges are ``imports`` edges carrying
+``hint_source="same_package"`` so density metrics can count them
+separately and any false positive is diagnosable at the source.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+ from ..resolvers.jvm_workspace import JvmWorkspaceIndex
+
+# Capitalized identifier — candidate type reference.
+_TYPE_IDENT_RE = re.compile(r"\b[A-Z][A-Za-z0-9_]*\b")
+
+# ``import a.b.C`` / ``import static a.b.C.d`` — collect the simple type
+# name so explicitly-imported names never produce a same-package edge.
+_IMPORT_LINE_RE = re.compile(r"^\s*import\s+(?:static\s+)?([\w.]+)", re.MULTILINE)
+
+# Scala brace imports: ``import a.b.{C, D => E}`` — every name inside the
+# braces (sources and rename targets alike) shadows same-package types.
+_IMPORT_BRACES_RE = re.compile(r"^\s*import\s+[\w.]+\.\{([^}]*)\}", re.MULTILINE)
+
+# Kotlin default-import types (kotlin.*, kotlin.collections.*, kotlin.io.*,
+# kotlin.text.*, kotlin.ranges.*, kotlin.sequences.*, kotlin.annotation.*,
+# kotlin.jvm.*) — visible without an import in every Kotlin file, exactly
+# like java.lang in Java. A same-package type shadowing one of these names
+# is legal but vanishingly rare next to genuine stdlib references, so the
+# name is skipped wholesale.
+_KOTLIN_DEFAULT_TYPES = frozenset({
+ "Any", "Nothing", "Unit", "String", "CharSequence",
+ "Int", "Long", "Short", "Byte", "Char", "Boolean", "Float", "Double", "Number",
+ "Array", "IntArray", "LongArray", "ShortArray", "ByteArray", "CharArray",
+ "BooleanArray", "FloatArray", "DoubleArray",
+ "List", "MutableList", "Set", "MutableSet", "Map", "MutableMap",
+ "Collection", "MutableCollection", "Iterable", "MutableIterable",
+ "Iterator", "MutableIterator", "ListIterator", "MutableListIterator",
+ "Sequence", "Pair", "Triple", "Result", "Lazy", "Regex",
+ "Comparable", "Comparator", "Throwable", "Exception", "Error",
+ "RuntimeException", "IllegalArgumentException", "IllegalStateException",
+ "IndexOutOfBoundsException", "NullPointerException",
+ "UnsupportedOperationException", "NumberFormatException",
+ "ClassCastException", "NoSuchElementException", "ConcurrentModificationException",
+ "Annotation", "Enum", "Function",
+ "IntRange", "LongRange", "CharRange", "ClosedRange",
+ "Deprecated", "Suppress", "OptIn", "DslMarker", "PublishedApi",
+ "JvmStatic", "JvmField", "JvmName", "JvmOverloads", "JvmInline",
+ "Volatile", "Synchronized", "Transient", "Strictfp", "Throws",
+ "StringBuilder", "KClass",
+})
+
+# Scala Predef / default-import types — visible without an import in every
+# Scala file. Names shared with java.lang/Kotlin (String, Exception, …) are
+# already covered by those sets; this adds the Scala-specific surface.
+_SCALA_DEFAULT_TYPES = frozenset({
+ "Option", "Some", "None", "Either", "Left", "Right", "Try", "Success",
+ "Failure", "Future", "Promise", "Seq", "IndexedSeq", "LinearSeq", "Vector",
+ "Stream", "LazyList", "Nil", "AnyRef", "AnyVal", "BigInt", "BigDecimal",
+ "Ordering", "Ordered", "PartialFunction", "Symbol", "Tuple1", "Tuple2",
+ "Tuple3", "Range", "App", "Serializable", "Product", "Equals", "Unit",
+})
+
+_SAME_PACKAGE_HINT = "same_package"
+
+
+def resolve_jvm_same_package_refs(
+ graph: nx.DiGraph,
+ jvm_index: JvmWorkspaceIndex,
+ texts: dict[str, str],
+) -> int:
+ """Emit same-package ``imports`` edges for JVM files.
+
+ *texts* maps repo-relative path → source text for every Java/Kotlin
+ (and Scala, once routed through the index) file to scan.
+
+ Returns the number of edges added.
+ """
+ from ..resolvers.jvm_workspace import _JAVA_LANG_TYPES
+
+ skip_names = _JAVA_LANG_TYPES | _KOTLIN_DEFAULT_TYPES | _SCALA_DEFAULT_TYPES
+
+ count = 0
+ for path, text in texts.items():
+ pkg_fqn = jvm_index.package_for_file(path)
+ if not pkg_fqn:
+ continue
+ pkg = jvm_index.packages.get(pkg_fqn)
+ if pkg is None or len(pkg.files) < 2:
+ continue
+
+ # Simple names this file already imports explicitly — an explicit
+ # import of com.other.Foo shadows a same-package Foo.
+ explicit_imports = {
+ m.group(1).rstrip(".").rsplit(".", 1)[-1]
+ for m in _IMPORT_LINE_RE.finditer(text)
+ }
+ for m in _IMPORT_BRACES_RE.finditer(text):
+ explicit_imports.update(re.findall(r"\w+", m.group(1)))
+
+ # target file → referenced type names
+ found: dict[str, list[str]] = {}
+ for ident in sorted(set(_TYPE_IDENT_RE.findall(text))):
+ if ident in skip_names or ident in explicit_imports:
+ continue
+ declaring = pkg.exported_top_level.get(ident)
+ if not declaring or len(declaring) != 1:
+ # Unknown in this package, or ambiguous (≥2 declaring
+ # files) — no edge to anyone.
+ continue
+ target = declaring[0]
+ if target == path:
+ continue
+ found.setdefault(target, []).append(ident)
+
+ for target, names in sorted(found.items()):
+ if not graph.has_node(path) or not graph.has_node(target):
+ continue
+ if graph.has_edge(path, target):
+ continue # a real import (or stronger evidence) wins
+ graph.add_edge(
+ path,
+ target,
+ edge_type="imports",
+ imported_names=names,
+ hint_source=_SAME_PACKAGE_HINT,
+ )
+ count += 1
+
+ return count
+
+
+def collect_jvm_source_texts(parsed_files: dict[str, Any]) -> dict[str, str]:
+ """Read each parsed JVM file's source from disk, keyed by repo path."""
+ out: dict[str, str] = {}
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in ("java", "kotlin", "scala"):
+ continue
+ try:
+ out[path] = Path(parsed.file_info.abs_path).read_text(
+ encoding="utf-8", errors="ignore"
+ )
+ except OSError:
+ continue
+ return out
diff --git a/packages/core/src/repowise/core/ingestion/languages/registry.py b/packages/core/src/repowise/core/ingestion/languages/registry.py
index 649d34cf7..9ae64f974 100644
--- a/packages/core/src/repowise/core/ingestion/languages/registry.py
+++ b/packages/core/src/repowise/core/ingestion/languages/registry.py
@@ -16,11 +16,29 @@ the TypeScript file from this registry.
from __future__ import annotations
+import re
from collections.abc import Iterable
from .spec import LanguageSpec
from .specs import ALL_SPECS as _SPECS
+# Entry-point filename stems that are conventional across languages rather
+# than owned by any one of them ("bootstrap.php", "entry.ts", "cli.py",
+# "server.go", "main.rs", "app.py", "index.js" …). Language-unique stems
+# (manage/wsgi/asgi/__main__ → python, mod → rust) live on their specs.
+_GENERIC_ENTRY_STEMS: frozenset[str] = frozenset(
+ {"main", "index", "app", "server", "cli", "bootstrap", "entry"}
+)
+
+# Stems the traverser's is_entry_point *flag* accepts for any language —
+# deliberately a different (tighter on cli/bootstrap/entry, looser on
+# run/start) set than the tour-bonus stems above: the flag is strong
+# evidence, the tour stem a weak bonus. Per-language flag stems
+# (wsgi/asgi → python) live on the specs.
+_GENERIC_ENTRY_FLAG_STEMS: frozenset[str] = frozenset(
+ {"main", "index", "app", "run", "server", "start"}
+)
+
# =========================================================================
# LanguageRegistry
# =========================================================================
@@ -82,6 +100,20 @@ class LanguageRegistry:
ext for spec in self._specs.values() if spec.is_code for ext in spec.extensions
)
+ def non_infra_code_extensions(self) -> frozenset[str]:
+ """Extensions of code languages that are not infra (typing guard).
+
+ Shell/terraform are code *and* infra — their files may still be
+ promoted to infra/CI presentation types by name and path; genuine
+ source extensions (.py … .dart .hs .clj) never are.
+ """
+ return frozenset(
+ ext
+ for spec in self._specs.values()
+ if spec.is_code and not spec.is_infra
+ for ext in spec.extensions
+ )
+
def code_languages(self) -> frozenset[str]:
"""Return tags for code languages (not config/markup/data)."""
return frozenset(s.tag for s in self._specs.values() if s.is_code and not s.is_passthrough)
@@ -121,6 +153,122 @@ class LanguageRegistry:
ext for spec in self._specs.values() if spec.tag in tag_set for ext in spec.extensions
)
+ # -- Knowledge-graph capability lookups --------------------------------
+
+ def import_support_map(self) -> dict[str, str]:
+ """Return ``{tag: "full" | "partial" | "none"}`` for every language."""
+ return {s.tag: s.import_support for s in self._specs.values()}
+
+ def import_support_for(self, tag: str) -> str:
+ """Return the import-support tier for *tag* (``"none"`` if unknown)."""
+ spec = self._specs.get(tag)
+ return spec.import_support if spec else "none"
+
+ def entry_filename_stems(self) -> frozenset[str]:
+ """Generic + per-language entry-point filename stems (tour bonus set)."""
+ return _GENERIC_ENTRY_STEMS | frozenset(
+ stem for s in self._specs.values() for stem in s.entry_stems
+ )
+
+ def entry_flag_stems(self) -> frozenset[str]:
+ """Generic + per-language stems for the traverser's is_entry_point flag."""
+ return _GENERIC_ENTRY_FLAG_STEMS | frozenset(
+ stem for s in self._specs.values() for stem in s.entry_flag_stems
+ )
+
+ def test_stem_prefixes(self) -> tuple[str, ...]:
+ """Union of test filename-stem prefixes, sorted for determinism."""
+ return tuple(sorted({p for s in self._specs.values() for p in s.test_stem_prefixes}))
+
+ def test_stem_suffixes(self) -> tuple[str, ...]:
+ """Union of test filename-stem suffixes, sorted for determinism."""
+ return tuple(sorted({p for s in self._specs.values() for p in s.test_stem_suffixes}))
+
+ def test_infixes(self) -> tuple[str, ...]:
+ """Union of test filename infixes, sorted for determinism."""
+ return tuple(sorted({p for s in self._specs.values() for p in s.test_infixes}))
+
+ def test_fixture_stems(self) -> frozenset[str]:
+ """Union of test-fixture filename stems (conftest, spec_helper, …)."""
+ return frozenset(p for s in self._specs.values() for p in s.test_fixture_stems)
+
+ def suite_anchor_stems(self) -> frozenset[str]:
+ """Union of test-suite anchor stems for the tour's closing stop."""
+ return frozenset(p for s in self._specs.values() for p in s.suite_anchor_stems)
+
+ def descriptor_filenames(self) -> frozenset[str]:
+ """Union of declaration-descriptor filenames (module-info.java, …)."""
+ return frozenset(f for s in self._specs.values() for f in s.descriptor_filenames)
+
+ def camel_test_res_by_extension(self) -> dict[str, re.Pattern[str]]:
+ """Per-extension case-sensitive camel-boundary test-suffix regexes.
+
+ Each language's ``test_camel_suffixes`` compile to one anchored
+ pattern (``(?<=[a-z0-9])(?:Tests|Test|IT)$``) keyed by that
+ language's own extensions — the lowercase-boundary lookbehind is what
+ keeps ``latest.java``/``contest.cs`` and bare ``Test.java`` out.
+ """
+ result: dict[str, re.Pattern[str]] = {}
+ for spec in self._specs.values():
+ if not spec.test_camel_suffixes:
+ continue
+ # Longest-first so "Tests" wins over "Test" inside the alternation.
+ alternation = "|".join(
+ sorted(spec.test_camel_suffixes, key=lambda sfx: (-len(sfx), sfx))
+ )
+ pattern = re.compile(rf"(?<=[a-z0-9])(?:{alternation})$")
+ for ext in spec.extensions:
+ result.setdefault(ext, pattern)
+ return result
+
+ def camel_fixture_res_by_extension(self) -> dict[str, re.Pattern[str]]:
+ """Per-extension case-sensitive camel-boundary fixture-suffix regexes.
+
+ Same compilation rules as :meth:`camel_test_res_by_extension`, for
+ ``fixture_camel_suffixes`` — files holding test support data
+ (``FooFixtures.java``) rather than tests.
+ """
+ result: dict[str, re.Pattern[str]] = {}
+ for spec in self._specs.values():
+ if not spec.fixture_camel_suffixes:
+ continue
+ alternation = "|".join(
+ sorted(spec.fixture_camel_suffixes, key=lambda sfx: (-len(sfx), sfx))
+ )
+ pattern = re.compile(rf"(?<=[a-z0-9])(?:{alternation})$")
+ for ext in spec.extensions:
+ result.setdefault(ext, pattern)
+ return result
+
+ def test_dir_paths(self) -> tuple[str, ...]:
+ """Union of multi-segment test-root dir paths, sorted for determinism."""
+ return tuple(sorted({p for s in self._specs.values() for p in s.test_dir_paths}))
+
+ def test_dir_tokens_by_language(self) -> dict[str, frozenset[str]]:
+ """Per-language single-segment test-dir tokens (unambiguous for
+ that language's files — ruby's ``spec/``)."""
+ return {
+ s.tag: frozenset(s.test_dir_tokens)
+ for s in self._specs.values()
+ if s.test_dir_tokens
+ }
+
+ def test_dir_suffixes(self) -> tuple[str, ...]:
+ """Union of case-sensitive test-project dir suffixes, sorted."""
+ return tuple(sorted({p for s in self._specs.values() for p in s.test_dir_suffixes}))
+
+ def layer_dir_hints_by_language(self) -> dict[str, tuple[tuple[str, str], ...]]:
+ """Per-language (dir_hint, layer_name) hints, sorted for determinism.
+
+ Keys are language tags; hints apply only to that language's files —
+ never another's. See ``LanguageSpec.layer_dir_hints`` for the shapes.
+ """
+ return {
+ s.tag: tuple(sorted(s.layer_dir_hints))
+ for s in self._specs.values()
+ if s.layer_dir_hints
+ }
+
def all_specs(self) -> list[LanguageSpec]:
"""Return all registered specs."""
return list(self._specs.values())
diff --git a/packages/core/src/repowise/core/ingestion/languages/spec.py b/packages/core/src/repowise/core/ingestion/languages/spec.py
index 31e332f16..e53e8d192 100644
--- a/packages/core/src/repowise/core/ingestion/languages/spec.py
+++ b/packages/core/src/repowise/core/ingestion/languages/spec.py
@@ -42,6 +42,80 @@ class LanguageSpec:
# -- Heritage --------------------------------------------------------
heritage_node_types: frozenset[str] = field(default_factory=frozenset)
+ # -- Knowledge-graph capabilities --------------------------------------
+ # How well import edges can be resolved for this language today:
+ # "full" — dedicated resolver, validated mechanics
+ # "partial" — dedicated resolver with major known gaps
+ # "none" — generic stem-lookup fallback only (passthrough/non-code)
+ # Consumed by the KG validation harness (density floors, honesty checks);
+ # the generation pipeline starts consuming it in the degradation work.
+ import_support: str = "none"
+
+ # Filename stems that mark an executable/wiring entry point *for this
+ # language only* (cross-language stems like "main"/"index" live in the
+ # registry's generic set). Union feeds the tour's entry-stem bonus.
+ entry_stems: tuple[str, ...] = ()
+
+ # Stems this language contributes to the traverser's is_entry_point
+ # *flag* (strong evidence — python's wsgi/asgi). Distinct from
+ # entry_stems: the flag set is deliberately tighter than the tour's
+ # weak-bonus stem set.
+ entry_flag_stems: tuple[str, ...] = ()
+
+ # Test-shaped filename rules this language contributes to layer
+ # inference (unions are consumed in generation/layers.py):
+ test_stem_prefixes: tuple[str, ...] = () # ("test_",)
+ test_stem_suffixes: tuple[str, ...] = () # ("_test", "_spec")
+ test_infixes: tuple[str, ...] = () # (".test.", ".spec.")
+ test_fixture_stems: tuple[str, ...] = () # ("conftest",)
+
+ # Case-sensitive camel-boundary test suffixes, applied ONLY to this
+ # language's own extensions — a convention never leaks to other
+ # languages' files. ``FooTest.java`` matches; ``latest.java`` and bare
+ # ``Test.java`` never do (conventions match with their own case).
+ test_camel_suffixes: tuple[str, ...] = () # ("Test", "Tests", "IT")
+
+ # Case-sensitive camel-boundary suffixes marking test *fixture* files
+ # ("ParameterizedTypeFixtures.java") — support data living in the test
+ # tree. A fixtures file provides data, it doesn't verify behavior, so
+ # it never faces the test suite in the tour.
+ fixture_camel_suffixes: tuple[str, ...] = () # ("Fixture", "Fixtures")
+
+ # Multi-segment test-root directory paths, lowercase, matched as
+ # consecutive path segments at any depth ("src/it/java"). Single-token
+ # roots (tests/, __tests__/) stay in the generic layer table.
+ test_dir_paths: tuple[str, ...] = ()
+
+ # Single-segment test-dir tokens that are UNAMBIGUOUS for this
+ # language's files. The generic table treats "spec(s)/" as ambiguous
+ # (OpenAPI specs, language specs) and demands a test-shaped filename —
+ # but a Ruby file under spec/ is RSpec material whatever its name
+ # (support helpers, vendored fixtures like okjson.rb included).
+ test_dir_tokens: tuple[str, ...] = ()
+
+ # Case-sensitive directory-segment suffixes that mark a test project
+ # directory (.NET sibling test projects: "Foo.Tests/").
+ test_dir_suffixes: tuple[str, ...] = ()
+
+ # Stems that anchor the tour's closing test-suite stop (conftest-likes).
+ suite_anchor_stems: tuple[str, ...] = ()
+
+ # Declaration-descriptor filenames this language reserves
+ # (module-info.java, package-info.java): real source files, but they
+ # describe a module/package rather than implement anything — never a
+ # layer face or test-suite anchor however shallow they sit.
+ descriptor_filenames: tuple[str, ...] = ()
+
+ # Extra (dir_hint → layer_name) hints applied ONLY to this language's
+ # files (never other languages'), consulted after the generic layer table at each path
+ # depth. Three hint shapes, distinguished by the key:
+ # "internal" — exact lowercase dir-name token (Go internal/ → Service)
+ # "src/bin" — multi-segment path, matched as consecutive segments
+ # ".Api"/"-cli" — case-sensitive dir-name *suffix* (leading "." or "-"):
+ # .NET project dirs (Billing.Api/), cargo crate dirs
+ # (typst-cli/)
+ layer_dir_hints: tuple[tuple[str, str], ...] = ()
+
# -- Ecosystem -------------------------------------------------------
entry_point_patterns: tuple[str, ...] = () # ("main.py", "app.py")
manifest_files: tuple[str, ...] = () # ("pyproject.toml",)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
index 61d03ee73..575b43b39 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/__init__.py
@@ -11,6 +11,7 @@ extension-to-language map is built first-spec-wins, so order is significant
from __future__ import annotations
from ..spec import LanguageSpec
+from .asciidoc import SPEC as _ASCIIDOC
from .c import SPEC as _C
from .clojure import SPEC as _CLOJURE
from .cpp import SPEC as _CPP
@@ -94,6 +95,7 @@ ALL_SPECS: tuple[LanguageSpec, ...] = (
_DOCKERFILE,
_MAKEFILE,
_MARKDOWN,
+ _ASCIIDOC,
_SQL,
_OPENAPI,
# XAML / AXAML markup for WPF, WinUI 3, UWP, MAUI, Avalonia, Uno.
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/asciidoc.py b/packages/core/src/repowise/core/ingestion/languages/specs/asciidoc.py
new file mode 100644
index 000000000..28f57c012
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/asciidoc.py
@@ -0,0 +1,17 @@
+"""LanguageSpec for asciidoc.
+
+AsciiDoc READMEs (README.asciidoc / README.adoc) are the convention in
+much of the Erlang/Elixir ecosystem (cowlib, cowboy, ranch); without a
+spec they are not indexed at all and the tour's overview step loses its
+root README target.
+"""
+
+from ..spec import LanguageSpec
+
+SPEC = LanguageSpec(
+ tag="asciidoc",
+ display_name="AsciiDoc",
+ extensions=frozenset({".adoc", ".asciidoc"}),
+ is_code=False,
+ is_passthrough=True,
+)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/c.py b/packages/core/src/repowise/core/ingestion/languages/specs/c.py
index 9ce91b016..6b3bef9a7 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/c.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/c.py
@@ -5,6 +5,14 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="c",
display_name="C",
+ import_support="full",
+ # Same test conventions as C++ (GoogleTest/Unity): foo_test.c / test_foo.c.
+ test_stem_prefixes=("test_",),
+ test_stem_suffixes=("_test", "_unittest"),
+ # A top-level include/ holds a C library's installed public headers —
+ # its API surface (libuv, curl, openssl layouts). Root-anchored: a
+ # vendored include/ deep in another tree must not mint the layer.
+ layer_dir_hints=(("/include", "API"),),
extensions=frozenset({".c"}),
shares_grammar_with="cpp",
scm_file="c.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/clojure.py b/packages/core/src/repowise/core/ingestion/languages/specs/clojure.py
index 920e6b220..92f03741c 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/clojure.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/clojure.py
@@ -6,5 +6,10 @@ SPEC = LanguageSpec(
tag="clojure",
display_name="Clojure",
extensions=frozenset({".clj", ".cljs", ".cljc"}),
+ # Leiningen/deps.edn convention: src/<app>/core.clj holds -main.
+ entry_point_patterns=("core.clj", "main.clj"),
+ manifest_files=("deps.edn", "project.clj"),
is_passthrough=True,
+ # Lightweight regex resolver: ns :require/:use forms → (ns …) index.
+ import_support="partial",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py b/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py
index 6f990e994..c2cd225d4 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/cpp.py
@@ -5,6 +5,14 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="cpp",
display_name="C++",
+ import_support="full",
+ # GoogleTest conventions: foo_test.cc / foo_unittest.cc / test_foo.cpp.
+ test_stem_prefixes=("test_",),
+ test_stem_suffixes=("_test", "_unittest"),
+ # A top-level include/ holds a C++ library's installed public headers —
+ # its API surface (fmt, leveldb, boost layouts). Root-anchored: a
+ # vendored include/ deep in another tree must not mint the layer.
+ layer_dir_hints=(("/include", "API"),),
extensions=frozenset({".cpp", ".cc", ".cxx", ".h", ".hpp", ".hxx"}),
grammar_package="tree_sitter_cpp",
scm_file="cpp.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/crystal.py b/packages/core/src/repowise/core/ingestion/languages/specs/crystal.py
index 31ee9999b..5db53cd61 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/crystal.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/crystal.py
@@ -6,5 +6,7 @@ SPEC = LanguageSpec(
tag="crystal",
display_name="Crystal",
extensions=frozenset({".cr"}),
+ # shards builds src/main.cr by default.
+ entry_point_patterns=("main.cr",),
is_passthrough=True,
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py b/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py
index 1b684d79b..9eebd3b6d 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/csharp.py
@@ -5,6 +5,14 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="csharp",
display_name="C#",
+ import_support="full",
+ # xUnit/NUnit conventions: FooTest(s)/FooSpec(s); sibling Foo.Tests/
+ # and BDD-style Foo.Specs/ projects (Polly's test/Polly.Specs).
+ test_camel_suffixes=("Test", "Tests", "Spec", "Specs"),
+ test_dir_suffixes=(".Tests", ".Specs"),
+ # Clean-architecture project-dir suffixes (Foo.Api/, Foo.Domain/,
+ # Foo.Infrastructure/) — not yet verified against a live .NET repo.
+ layer_dir_hints=((".Api", "API"), (".Domain", "Service"), (".Infrastructure", "Data")),
extensions=frozenset({".cs"}),
grammar_package="tree_sitter_c_sharp",
scm_file="csharp.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/dart.py b/packages/core/src/repowise/core/ingestion/languages/specs/dart.py
index 80a105369..33bd6abac 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/dart.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/dart.py
@@ -5,6 +5,12 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="dart",
display_name="Dart",
+ # package:test convention: test/foo_test.dart.
+ test_stem_suffixes=("_test",),
+ entry_point_patterns=("main.dart",),
+ manifest_files=("pubspec.yaml",),
extensions=frozenset({".dart"}),
is_passthrough=True,
+ # Lightweight regex resolver: package:/relative URIs, part/part of, export.
+ import_support="partial",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/dlang.py b/packages/core/src/repowise/core/ingestion/languages/specs/dlang.py
index ce4d8d0c0..2b4c51e09 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/dlang.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/dlang.py
@@ -6,5 +6,7 @@ SPEC = LanguageSpec(
tag="dlang",
display_name="D",
extensions=frozenset({".d"}),
+ # dub convention: source/app.d.
+ entry_point_patterns=("app.d",),
is_passthrough=True,
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/elixir.py b/packages/core/src/repowise/core/ingestion/languages/specs/elixir.py
index fdea596d8..2adae8d1c 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/elixir.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/elixir.py
@@ -5,6 +5,16 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="elixir",
display_name="Elixir",
+ # ExUnit conventions: test/foo_test.exs + test/test_helper.exs.
+ test_stem_suffixes=("_test",),
+ test_fixture_stems=("test_helper",),
+ suite_anchor_stems=("test_helper",),
+ # OTP Application callback (lib/<app>/application.ex); mix.exs is a
+ # manifest, not an entry.
+ entry_point_patterns=("application.ex",),
+ manifest_files=("mix.exs",),
extensions=frozenset({".ex", ".exs"}),
is_passthrough=True,
+ # Lightweight regex resolver: alias/import/use/require → defmodule index.
+ import_support="partial",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/elm.py b/packages/core/src/repowise/core/ingestion/languages/specs/elm.py
index 7fb857038..b10f1b292 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/elm.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/elm.py
@@ -6,5 +6,7 @@ SPEC = LanguageSpec(
tag="elm",
display_name="Elm",
extensions=frozenset({".elm"}),
+ # elm make targets src/Main.elm.
+ entry_point_patterns=("Main.elm",),
is_passthrough=True,
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/erlang.py b/packages/core/src/repowise/core/ingestion/languages/specs/erlang.py
index 03194cbfd..21bb968fb 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/erlang.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/erlang.py
@@ -6,5 +6,11 @@ SPEC = LanguageSpec(
tag="erlang",
display_name="Erlang",
extensions=frozenset({".erl", ".hrl"}),
+ # OTP application callback modules: <name>_app.erl.
+ entry_point_patterns=("*_app.erl",),
+ manifest_files=("rebar.config",),
is_passthrough=True,
+ # Lightweight regex resolver: -include(_lib)/-behaviour + qualified calls
+ # against the -module() index.
+ import_support="partial",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/fsharp.py b/packages/core/src/repowise/core/ingestion/languages/specs/fsharp.py
index 588d8980a..c22629a5d 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/fsharp.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/fsharp.py
@@ -6,5 +6,10 @@ SPEC = LanguageSpec(
tag="fsharp",
display_name="F#",
extensions=frozenset({".fs", ".fsi", ".fsx"}),
+ # .NET convention shared with C#: Program.fs.
+ entry_point_patterns=("Program.fs",),
is_passthrough=True,
+ # Lightweight regex resolver: open → namespace/module declaration index,
+ # plus the fsproj compile-order dependency spine.
+ import_support="partial",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/go.py b/packages/core/src/repowise/core/ingestion/languages/specs/go.py
index 6d1acbe62..684627afa 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/go.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/go.py
@@ -5,6 +5,11 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="go",
display_name="Go",
+ import_support="full",
+ test_stem_suffixes=("_test",),
+ # golang-standards layout: internal/ and pkg/ hold application-internal
+ # and exported library code (cmd/ → CLI is already a generic token).
+ layer_dir_hints=(("internal", "Service"), ("pkg", "Service")),
extensions=frozenset({".go"}),
grammar_package="tree_sitter_go",
scm_file="go.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/haskell.py b/packages/core/src/repowise/core/ingestion/languages/specs/haskell.py
index c38ceadb3..ef37aee15 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/haskell.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/haskell.py
@@ -5,6 +5,14 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="haskell",
display_name="Haskell",
+ # hspec convention: FooSpec.hs under test/.
+ test_camel_suffixes=("Spec",),
+ entry_point_patterns=("Main.hs",),
+ # Setup.hs/Setup.lhs are the Cabal build-script convention — package
+ # plumbing, not domain code; manifests never anchor or face layers.
+ manifest_files=("package.yaml", "stack.yaml", "Setup.hs", "Setup.lhs"),
extensions=frozenset({".hs", ".lhs"}),
is_passthrough=True,
+ # Lightweight regex resolver: import statements → module declaration index.
+ import_support="partial",
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/java.py b/packages/core/src/repowise/core/ingestion/languages/specs/java.py
index 5071a4711..062177b8d 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/java.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/java.py
@@ -5,6 +5,15 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="java",
display_name="Java",
+ import_support="full",
+ # JUnit/Maven conventions: FooTest/FooTests/FooIT; Surefire/Failsafe roots.
+ test_camel_suffixes=("Test", "Tests", "IT"),
+ # Test-data files (gson's ParameterizedTypeFixtures.java) — support
+ # data in the test tree, never the suite's face in the tour.
+ fixture_camel_suffixes=("Fixture", "Fixtures"),
+ test_dir_paths=("src/test/java", "src/it/java", "src/integrationtest/java"),
+ # JPMS/javadoc descriptors — source files that declare, not implement.
+ descriptor_filenames=("module-info.java", "package-info.java"),
extensions=frozenset({".java"}),
grammar_package="tree_sitter_java",
scm_file="java.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/javascript.py b/packages/core/src/repowise/core/ingestion/languages/specs/javascript.py
index 34df17fa3..8f5e50bb3 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/javascript.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/javascript.py
@@ -5,6 +5,8 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="javascript",
display_name="JavaScript",
+ import_support="full",
+ test_infixes=(".test.", ".spec."),
extensions=frozenset({".js", ".jsx", ".mjs", ".cjs"}),
grammar_package="tree_sitter_javascript",
scm_file="javascript.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/kotlin.py b/packages/core/src/repowise/core/ingestion/languages/specs/kotlin.py
index e0694d574..96109afbc 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/kotlin.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/kotlin.py
@@ -5,6 +5,13 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="kotlin",
display_name="Kotlin",
+ import_support="full",
+ # JUnit/Kotest conventions: FooTest/FooTests/FooSpec; Gradle sourceset
+ # roots — the "src/*Test" wildcard covers multiplatform/custom test
+ # sourcesets (src/commonTest, src/jvmTest, src/integrationTest, …).
+ test_camel_suffixes=("Test", "Tests", "Spec"),
+ test_dir_paths=("src/test/kotlin", "src/*Test"),
+ entry_point_patterns=("Main.kt", "Application.kt"),
extensions=frozenset({".kt", ".kts"}),
grammar_package="tree_sitter_kotlin",
scm_file="kotlin.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/luau.py b/packages/core/src/repowise/core/ingestion/languages/specs/luau.py
index ede050687..c57713624 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/luau.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/luau.py
@@ -5,6 +5,7 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="luau",
display_name="Luau",
+ import_support="partial",
# Rojo treats both .lua and .luau as Luau modules. Luau's grammar is
# a superset of Lua 5.1, so vanilla Lua files parse cleanly too.
extensions=frozenset({".lua", ".luau"}),
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/markdown.py b/packages/core/src/repowise/core/ingestion/languages/specs/markdown.py
index 82c022a2d..c1d279588 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/markdown.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/markdown.py
@@ -5,7 +5,7 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="markdown",
display_name="Markdown",
- extensions=frozenset({".md", ".mdx"}),
+ extensions=frozenset({".md", ".mdx", ".markdown", ".mdown"}),
is_code=False,
is_passthrough=True,
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/nim.py b/packages/core/src/repowise/core/ingestion/languages/specs/nim.py
index 7fd52b596..27177c2a9 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/nim.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/nim.py
@@ -6,5 +6,7 @@ SPEC = LanguageSpec(
tag="nim",
display_name="Nim",
extensions=frozenset({".nim"}),
+ # nimble binary projects: src/main.nim.
+ entry_point_patterns=("main.nim",),
is_passthrough=True,
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/objectivec.py b/packages/core/src/repowise/core/ingestion/languages/specs/objectivec.py
index d2f12da4d..d42d39545 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/objectivec.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/objectivec.py
@@ -6,5 +6,7 @@ SPEC = LanguageSpec(
tag="objectivec",
display_name="Objective-C",
extensions=frozenset({".m", ".mm"}),
+ # main.m holds UIApplicationMain/NSApplicationMain.
+ entry_point_patterns=("main.m",),
is_passthrough=True,
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/ocaml.py b/packages/core/src/repowise/core/ingestion/languages/specs/ocaml.py
index 3f2e5a72e..7b252738c 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/ocaml.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/ocaml.py
@@ -6,5 +6,7 @@ SPEC = LanguageSpec(
tag="ocaml",
display_name="OCaml",
extensions=frozenset({".ml", ".mli"}),
+ # dune executables conventionally live in bin/main.ml.
+ entry_point_patterns=("main.ml",),
is_passthrough=True,
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/php.py b/packages/core/src/repowise/core/ingestion/languages/specs/php.py
index 0cff9f828..a2d6af5c4 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/php.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/php.py
@@ -5,7 +5,17 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="php",
display_name="PHP",
+ # Live-validated on Slim @ e12cb05: PSR-4 + file-based requires —
+ # 5% orphans; externals are real composer deps (no vendor/ checked in).
+ import_support="full",
+ # PHPUnit convention: FooTest.php under tests/.
+ test_camel_suffixes=("Test",),
+ # Front-controller + Laravel CLI ("artisan" carries no extension —
+ # the special-filename mapping keeps the pattern alive in the traverser).
+ entry_point_patterns=("index.php", "artisan"),
extensions=frozenset({".php"}),
+ special_filenames=frozenset({"artisan"}),
+ shebang_tokens=("php",),
grammar_package="tree_sitter_php",
grammar_loader="language_php",
scm_file="php.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/python.py b/packages/core/src/repowise/core/ingestion/languages/specs/python.py
index 361b0f5a2..0b8bc99c5 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/python.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/python.py
@@ -5,6 +5,12 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="python",
display_name="Python",
+ import_support="full",
+ entry_stems=("manage", "wsgi", "asgi", "__main__"),
+ entry_flag_stems=("wsgi", "asgi"),
+ test_stem_prefixes=("test_",),
+ test_fixture_stems=("conftest",),
+ suite_anchor_stems=("conftest",),
extensions=frozenset({".py", ".pyi"}),
grammar_package="tree_sitter_python",
scm_file="python.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/ruby.py b/packages/core/src/repowise/core/ingestion/languages/specs/ruby.py
index 1f6412574..ef312f662 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/ruby.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/ruby.py
@@ -5,7 +5,20 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="ruby",
display_name="Ruby",
+ import_support="full",
+ test_stem_suffixes=("_spec",),
+ test_fixture_stems=("spec_helper", "test_helper"),
+ suite_anchor_stems=("spec_helper", "test_helper"),
+ # RSpec: a Ruby file under spec/ is test material whatever its name
+ # (support helpers, vendored fixtures) — no filename corroboration.
+ test_dir_tokens=("spec", "specs"),
+ # Rails app/jobs/ (models/controllers/services are generic tokens already).
+ layer_dir_hints=(("jobs", "Service"),),
+ entry_point_patterns=("main.rb", "app.rb", "config.ru"),
extensions=frozenset({".rb"}),
+ # Rack's config.ru is Ruby with a .ru extension — without this mapping
+ # the traverser would skip it as unknown and the entry pattern is dead.
+ special_filenames=frozenset({"config.ru"}),
grammar_package="tree_sitter_ruby",
scm_file="ruby.scm",
heritage_node_types=frozenset({"class"}),
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/rust.py b/packages/core/src/repowise/core/ingestion/languages/specs/rust.py
index babefa175..2f384a20a 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/rust.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/rust.py
@@ -5,6 +5,11 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="rust",
display_name="Rust",
+ import_support="full",
+ entry_stems=("mod",),
+ # Cargo conventions: src/bin/ holds extra binaries; workspace binary
+ # crates are conventionally named <project>-cli (typst-cli, …).
+ layer_dir_hints=(("src/bin", "CLI"), ("-cli", "CLI")),
extensions=frozenset({".rs"}),
grammar_package="tree_sitter_rust",
scm_file="rust.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/scala.py b/packages/core/src/repowise/core/ingestion/languages/specs/scala.py
index c8543a1f0..c864e1ba9 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/scala.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/scala.py
@@ -5,6 +5,11 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="scala",
display_name="Scala",
+ import_support="partial",
+ # ScalaTest/munit conventions: FooSpec/FooTest/FooSuite; sbt test roots.
+ test_camel_suffixes=("Spec", "Test", "Suite"),
+ test_dir_paths=("src/test/scala", "src/it/scala"),
+ entry_point_patterns=("Main.scala", "App.scala"),
extensions=frozenset({".scala"}),
grammar_package="tree_sitter_scala",
scm_file="scala.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/swift.py b/packages/core/src/repowise/core/ingestion/languages/specs/swift.py
index 66047f185..5953a6a16 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/swift.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/swift.py
@@ -5,6 +5,12 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="swift",
display_name="Swift",
+ # Live-validated on Alamofire @ 7595cbc: intra-module type edges,
+ # SPM target mapping, @main entry detection — 0% orphans, 0.70 resolution.
+ import_support="full",
+ # XCTest/SPM conventions: FooTest(s).swift; Tests/ root is a generic token.
+ test_camel_suffixes=("Test", "Tests"),
+ entry_point_patterns=("main.swift", "App.swift"),
extensions=frozenset({".swift"}),
grammar_package="tree_sitter_swift",
scm_file="swift.scm",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/typescript.py b/packages/core/src/repowise/core/ingestion/languages/specs/typescript.py
index 77955ed5b..503341e65 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/typescript.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/typescript.py
@@ -5,6 +5,8 @@ from ..spec import LanguageSpec
SPEC = LanguageSpec(
tag="typescript",
display_name="TypeScript",
+ import_support="full",
+ test_infixes=(".test.", ".spec."),
extensions=frozenset({".ts", ".tsx", ".mts", ".cts"}),
grammar_package="tree_sitter_typescript",
grammar_loader="language_typescript",
diff --git a/packages/core/src/repowise/core/ingestion/languages/specs/zig.py b/packages/core/src/repowise/core/ingestion/languages/specs/zig.py
index 2cafe9bf6..c7364d007 100644
--- a/packages/core/src/repowise/core/ingestion/languages/specs/zig.py
+++ b/packages/core/src/repowise/core/ingestion/languages/specs/zig.py
@@ -6,5 +6,7 @@ SPEC = LanguageSpec(
tag="zig",
display_name="Zig",
extensions=frozenset({".zig"}),
+ # zig init layout: src/main.zig.
+ entry_point_patterns=("main.zig",),
is_passthrough=True,
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/swift_same_module.py b/packages/core/src/repowise/core/ingestion/languages/swift_same_module.py
new file mode 100644
index 000000000..236d1d3b3
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/languages/swift_same_module.py
@@ -0,0 +1,167 @@
+"""Swift intra-module type-reference resolution.
+
+Background
+----------
+Swift has no intra-module imports *by design*: every file in a target
+sees every other file's top-level declarations. Without help, an SPM
+target is an edge desert — files connect only through the rare
+cross-module ``import``, so exactly the most cohesive unit of a Swift
+codebase reads as disconnected files.
+
+This pass mirrors the JVM same-package prior art
+(:mod:`.jvm_same_package`): a per-target map of declared top-level
+types (class/struct/enum/protocol/actor), then a conservative scan of
+each file's capitalized identifiers. An edge A → B is emitted only
+when ALL of:
+
+- the identifier names a top-level type declared in exactly **one**
+ file B of A's own SPM target (ambiguous names link to no one);
+- B is not A itself, and the type is not also declared in A;
+- the identifier is not a ubiquitous Swift stdlib/Foundation name
+ (the declared-in-target requirement already filters the framework
+ universe precisely — the skip list only guards the rare case of a
+ target declaring its own ``Data`` or ``View``).
+
+Files not under any SPM target (Xcode projects carry no
+``Package.swift``) fall into a single implicit module — Xcode app
+targets are one module, and references still have to match a unique
+locally-declared type.
+
+``typealias`` declarations and extensions are deliberately out of
+scope: an extension declares nothing new, and aliases are far more
+often file-local plumbing than the referenced surface.
+
+Emitted edges are ``imports`` edges carrying
+``hint_source="same_module"`` so density metrics can separate them and
+false positives stay diagnosable.
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import TYPE_CHECKING, Any
+
+if TYPE_CHECKING:
+ import networkx as nx
+
+# Top-level (and nested — indentation is not anchored, matching the JVM
+# scan's pragmatics) Swift type declarations.
+_SWIFT_TYPE_DECL_RE = re.compile(
+ r"^\s*(?:@\w+(?:\([^)]*\))?\s+)*"
+ r"(?:(?:public|open|internal|final|private|fileprivate|indirect|dynamic)\s+)*"
+ r"(?:class|struct|enum|protocol|actor)\s+([A-Z]\w*)",
+ re.MULTILINE,
+)
+
+_TYPE_IDENT_RE = re.compile(r"\b[A-Z][A-Za-z0-9_]*\b")
+
+# Ubiquitous Swift stdlib / Foundation names — references are
+# overwhelmingly to the framework type even when a target shadows one.
+_SWIFT_COMMON_TYPES = frozenset({
+ "String", "Int", "Int8", "Int16", "Int32", "Int64", "UInt", "UInt8",
+ "UInt16", "UInt32", "UInt64", "Double", "Float", "Bool", "Character",
+ "Array", "Dictionary", "Set", "Optional", "Result", "Error", "Never",
+ "Any", "AnyObject", "AnyClass", "Self", "Void", "Sequence", "Collection",
+ "Iterator", "IteratorProtocol", "Equatable", "Hashable", "Comparable",
+ "Codable", "Encodable", "Decodable", "Identifiable", "CustomStringConvertible",
+ "CaseIterable", "RawRepresentable", "ExpressibleByStringLiteral",
+ "Data", "Date", "URL", "URLRequest", "URLResponse", "URLSession",
+ "UUID", "Notification", "NotificationCenter", "IndexPath", "IndexSet",
+ "TimeInterval", "Calendar", "Locale", "TimeZone", "Bundle", "FileManager",
+ "JSONDecoder", "JSONEncoder", "JSONSerialization", "NumberFormatter",
+ "DateFormatter", "RunLoop", "Thread", "OperationQueue", "DispatchQueue",
+ "Task", "Actor", "MainActor", "Sendable", "AsyncSequence", "AsyncStream",
+ "Published", "ObservableObject", "State", "Binding", "Environment",
+ "View", "Text", "Image", "Color", "Font",
+})
+
+_SAME_MODULE_HINT = "same_module"
+
+
+def _module_for_file(path: str, target_dirs: list[tuple[str, str]]) -> str:
+ """Return the SPM target name owning *path* (longest prefix wins), or ""."""
+ best = ""
+ best_len = -1
+ for name, prefix in target_dirs:
+ if path.startswith(prefix) and len(prefix) > best_len:
+ best, best_len = name, len(prefix)
+ return best
+
+
+def resolve_swift_same_module_refs(
+ graph: nx.DiGraph,
+ swift_targets: dict[str, str],
+ texts: dict[str, str],
+) -> int:
+ """Emit same-module ``imports`` edges for Swift files.
+
+ *swift_targets* maps SPM target name → repo-relative source dir
+ (from ``Package.swift``); empty when the repo has no SPM manifest,
+ in which case all Swift files form one implicit module.
+
+ Returns the number of edges added.
+ """
+ target_dirs = [
+ (name, d.rstrip("/") + "/") for name, d in sorted(swift_targets.items())
+ ]
+
+ # Group files by module and collect each module's declared types.
+ files_by_module: dict[str, list[str]] = {}
+ declared: dict[str, dict[str, list[str]]] = {} # module → type → [files]
+ for path in sorted(texts):
+ module = _module_for_file(path, target_dirs)
+ files_by_module.setdefault(module, []).append(path)
+ type_map = declared.setdefault(module, {})
+ for m in _SWIFT_TYPE_DECL_RE.finditer(texts[path]):
+ type_map.setdefault(m.group(1), []).append(path)
+
+ count = 0
+ for module, files in files_by_module.items():
+ if len(files) < 2:
+ continue
+ type_map = declared[module]
+ for path in files:
+ text = texts[path]
+ found: dict[str, list[str]] = {}
+ for ident in sorted(set(_TYPE_IDENT_RE.findall(text))):
+ if ident in _SWIFT_COMMON_TYPES:
+ continue
+ declaring = type_map.get(ident)
+ if not declaring or len(set(declaring)) != 1:
+ continue # unknown here, or ambiguous — no edge
+ target = declaring[0]
+ if target == path:
+ continue
+ found.setdefault(target, []).append(ident)
+
+ for target, names in sorted(found.items()):
+ if not graph.has_node(path) or not graph.has_node(target):
+ continue
+ if graph.has_edge(path, target):
+ continue # a declared import (or stronger) wins
+ graph.add_edge(
+ path,
+ target,
+ edge_type="imports",
+ imported_names=names,
+ hint_source=_SAME_MODULE_HINT,
+ )
+ count += 1
+
+ return count
+
+
+def collect_swift_source_texts(parsed_files: dict[str, Any]) -> dict[str, str]:
+ """Read each parsed Swift file's source from disk, keyed by repo path."""
+ out: dict[str, str] = {}
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "swift":
+ continue
+ try:
+ out[path] = Path(parsed.file_info.abs_path).read_text(
+ encoding="utf-8", errors="ignore"
+ )
+ except OSError:
+ continue
+ return out
diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py
new file mode 100644
index 000000000..0986b4b89
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/__init__.py
@@ -0,0 +1,50 @@
+"""Regex-tier import extraction for languages without a tree-sitter grammar.
+
+Languages whose ``LanguageSpec.import_support`` is ``"partial"`` via the
+lightweight-resolver mechanism get their import statements extracted here
+with per-language regexes over the raw source text — no AST. The parser
+consults :func:`extract_lightweight_imports` on its no-grammar path, so
+these files keep an empty symbol list (the regex tier claims no symbol
+knowledge) but carry real :class:`~..models.Import` entries that flow
+through the standard resolver dispatch.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+
+from ..models import FileInfo, Import
+from .clojure import extract_clojure_imports
+from .dart import extract_dart_imports
+from .elixir import extract_elixir_imports
+from .erlang import extract_erlang_imports
+from .fsharp import extract_fsharp_imports
+from .haskell import extract_haskell_imports
+
+ExtractorFn = Callable[[str], list[Import]]
+
+_EXTRACTORS: dict[str, ExtractorFn] = {
+ "elixir": extract_elixir_imports,
+ "dart": extract_dart_imports,
+ "clojure": extract_clojure_imports,
+ "haskell": extract_haskell_imports,
+ "erlang": extract_erlang_imports,
+ "fsharp": extract_fsharp_imports,
+}
+
+LIGHTWEIGHT_IMPORT_LANGUAGES = frozenset(_EXTRACTORS)
+
+
+def extract_lightweight_imports(file_info: FileInfo, source: bytes) -> list[Import]:
+ """Return regex-extracted imports for *file_info*, or [] for other languages."""
+ extractor = _EXTRACTORS.get(file_info.language)
+ if extractor is None:
+ return []
+ text = source.decode("utf-8", errors="replace")
+ return extractor(text)
+
+
+__all__ = [
+ "LIGHTWEIGHT_IMPORT_LANGUAGES",
+ "extract_lightweight_imports",
+]
diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/clojure.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/clojure.py
new file mode 100644
index 000000000..31107466b
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/clojure.py
@@ -0,0 +1,132 @@
+"""Regex import extraction for Clojure (.clj / .cljc / .cljs).
+
+Captured forms — the require-ish blocks of the ``ns`` macro plus the
+standalone function forms:
+
+ (ns foo.bar
+ (:require [baz.qux :as q]
+ [other.ns :refer [x y]]
+ plain.ns))
+ (:use [foo.bar])
+ (require '[foo.bar :as fb])
+
+Each require spec contributes its leading namespace symbol; ``:as`` /
+``:refer`` / ``:rename`` options and their arguments are skipped by
+position (they follow the namespace inside the vector). ``(:import …)``
+blocks are deliberately NOT captured — they name JVM classes, which the
+lightweight tier has no mechanism to resolve. Legacy prefix lists
+``(:require (foo bar baz))`` are also out of scope (recorded cut).
+"""
+
+from __future__ import annotations
+
+import re
+
+from ..models import Import
+
+_BLOCK_HEAD_RE = re.compile(r"\((?::(require|use|require-macros)|(require|use))[\s'\[(]")
+
+# A namespace symbol: lowercase-ish start, at least segments/dashes; bans
+# keywords (leading :) by construction.
+_NS_SYMBOL_RE = re.compile(r"[A-Za-z*+!?<>=][\w*+!?<>=.-]*")
+
+_STRING_OR_COMMENT_RE = re.compile(r'"(?:\\.|[^"\\])*"|;[^\n]*')
+
+
+def _block_span(text: str, open_paren: int) -> int:
+ """Return the index just past the paren that closes ``text[open_paren]``."""
+ depth = 0
+ for i in range(open_paren, len(text)):
+ ch = text[i]
+ if ch == "(" or ch == "[":
+ depth += 1
+ elif ch == ")" or ch == "]":
+ depth -= 1
+ if depth == 0:
+ return i + 1
+ return len(text)
+
+
+def _spec_namespaces(block: str) -> list[str]:
+ """Leading namespace symbol of every require spec inside *block*.
+
+ A spec is either a bare symbol at block depth 1 or a vector/list whose
+ first symbol is the namespace; symbols at deeper positions (``:refer``
+ vectors) and option arguments are skipped.
+ """
+ names: list[str] = []
+ depth = 0
+ expect_ns = True # next symbol at the current position starts a spec
+ i = 0
+ while i < len(block):
+ ch = block[i]
+ if ch in "([":
+ depth += 1
+ # depth 1 = the require block itself (bare specs follow), depth 2
+ # = a spec vector (its head symbol is the namespace); anything
+ # deeper is an option payload (:refer vectors etc.)
+ expect_ns = depth <= 2
+ i += 1
+ elif ch in ")]":
+ depth -= 1
+ expect_ns = depth == 1
+ i += 1
+ elif ch == '"':
+ m = _STRING_OR_COMMENT_RE.match(block, i)
+ i = m.end() if m else i + 1
+ elif ch == ";":
+ nl = block.find("\n", i)
+ i = len(block) if nl == -1 else nl + 1
+ elif ch == ":":
+ # keyword: consume it and stop expecting a namespace until the
+ # next spec boundary (its argument is an alias/refer payload)
+ m = _NS_SYMBOL_RE.match(block, i + 1)
+ i = m.end() if m else i + 1
+ expect_ns = False
+ elif ch == "'":
+ i += 1 # quote before a spec — transparent
+ elif ch.isspace() or ch == ",":
+ i += 1
+ else:
+ m = _NS_SYMBOL_RE.match(block, i)
+ if not m:
+ i += 1
+ continue
+ symbol = m.group(0)
+ if expect_ns and depth >= 1:
+ # bare specs sit at depth 1, vector specs put the ns at the
+ # head of depth 2; either way this is the spec's first symbol
+ names.append(symbol)
+ expect_ns = depth == 1 # bare symbols may repeat at depth 1
+ i = m.end()
+ return names
+
+
+def extract_clojure_imports(text: str) -> list[Import]:
+ # Blank out strings and line comments first — a require form inside a
+ # docstring or a commented-out require must not mint edges.
+ text = _STRING_OR_COMMENT_RE.sub(
+ lambda m: '""' if m.group(0).startswith('"') else "", text
+ )
+ imports: list[Import] = []
+ seen: set[str] = set()
+ for match in _BLOCK_HEAD_RE.finditer(text):
+ open_paren = match.start()
+ block = text[open_paren : _block_span(text, open_paren)]
+ # strip the head token so it is not mistaken for a namespace
+ head_end = match.end() - 1 # keep the char that closed the head match
+ inner = block[head_end - open_paren :]
+ for namespace in _spec_namespaces("(" + inner):
+ if namespace in seen:
+ continue
+ seen.add(namespace)
+ imports.append(
+ Import(
+ raw_statement=f"(:require {namespace})",
+ module_path=namespace,
+ imported_names=[],
+ is_relative=False,
+ resolved_file=None,
+ )
+ )
+ return imports
diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/dart.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/dart.py
new file mode 100644
index 000000000..05f2aa047
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/dart.py
@@ -0,0 +1,71 @@
+"""Regex import extraction for Dart.
+
+Captured forms:
+
+ import 'package:name/path.dart'; — package URI
+ import 'relative/path.dart' as x; — importer-relative
+ import 'dart:async'; — SDK library (dropped at resolve)
+ export 'src/api.dart'; — re-export edge (barrel)
+ part 'impl.dart'; — strong intra-library edge
+ part of 'lib.dart'; / part of my.lib — back-edge to the owning library
+
+``part``/``part of`` are emitted as plain imports: the edge direction
+(fragment ↔ library, both ways across the two files' own statements) is
+exactly the coupling the graph wants.
+"""
+
+from __future__ import annotations
+
+import re
+
+from ..models import Import
+
+_URI_DIRECTIVE_RE = re.compile(
+ r"^[ \t]*(import|export|part)[ \t]+['\"]([^'\"]+)['\"]",
+ re.M,
+)
+# `part of` with either a URI or a dotted library name.
+_PART_OF_RE = re.compile(
+ r"^[ \t]*part[ \t]+of[ \t]+(?:['\"]([^'\"]+)['\"]|([A-Za-z_][A-Za-z0-9_.]*))",
+ re.M,
+)
+
+
+def extract_dart_imports(text: str) -> list[Import]:
+ imports: list[Import] = []
+ seen: set[str] = set()
+
+ for match in _PART_OF_RE.finditer(text):
+ uri, library_name = match.group(1), match.group(2)
+ module = uri if uri else f"library:{library_name}"
+ if module in seen:
+ continue
+ seen.add(module)
+ imports.append(
+ Import(
+ raw_statement=match.group(0).strip(),
+ module_path=module,
+ imported_names=[],
+ is_relative=bool(uri),
+ resolved_file=None,
+ )
+ )
+
+ for match in _URI_DIRECTIVE_RE.finditer(text):
+ directive, uri = match.group(1), match.group(2)
+ # `part of '…'` already handled above; the URI regex would re-match
+ # a plain `part` head, never the two-word form, so no overlap.
+ if uri in seen:
+ continue
+ seen.add(uri)
+ imports.append(
+ Import(
+ raw_statement=match.group(0).strip(),
+ module_path=uri,
+ imported_names=[],
+ is_relative=not uri.startswith(("package:", "dart:")),
+ resolved_file=None,
+ is_reexport=directive == "export",
+ )
+ )
+ return imports
diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/elixir.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/elixir.py
new file mode 100644
index 000000000..7890a8992
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/elixir.py
@@ -0,0 +1,58 @@
+"""Regex import extraction for Elixir.
+
+Captured forms (all compile-time module references — ``use`` injects code,
+so it is an edge like the rest):
+
+ alias Foo.Bar
+ alias Foo.Bar, as: B
+ alias Foo.{Bar, Baz.Qux}
+ import Foo.Bar
+ require Foo.Bar
+ use Foo.Bar, option: :x
+
+Skipped: ``__MODULE__``-relative aliases (self-references), Erlang-atom
+modules (``import :math`` — cross-runtime, no Elixir file to resolve to).
+"""
+
+from __future__ import annotations
+
+import re
+
+from ..models import Import
+
+# Module path after the directive; an optional `.{…}` brace group expands to
+# one import per member. `[^}]` deliberately crosses newlines — multi-line
+# brace groups are idiomatic mix formatting.
+_DIRECTIVE_RE = re.compile(
+ r"^[ \t]*(alias|import|require|use)[ \t]+"
+ r"([A-Z][A-Za-z0-9_]*(?:\.[A-Za-z0-9_]+)*)"
+ r"(\.\{[^}]*\})?",
+ re.M,
+)
+
+_MEMBER_RE = re.compile(r"[A-Z][A-Za-z0-9_.]*")
+
+
+def extract_elixir_imports(text: str) -> list[Import]:
+ imports: list[Import] = []
+ seen: set[str] = set()
+ for match in _DIRECTIVE_RE.finditer(text):
+ directive, base, brace = match.group(1), match.group(2), match.group(3)
+ modules = (
+ [f"{base}.{member}" for member in _MEMBER_RE.findall(brace)] if brace else [base]
+ )
+ raw = match.group(0).split("\n", 1)[0].strip()
+ for module in modules:
+ if module in seen:
+ continue
+ seen.add(module)
+ imports.append(
+ Import(
+ raw_statement=raw,
+ module_path=module,
+ imported_names=["*"] if directive == "import" else [],
+ is_relative=False,
+ resolved_file=None,
+ )
+ )
+ return imports
diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/erlang.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/erlang.py
new file mode 100644
index 000000000..6fe62283a
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/erlang.py
@@ -0,0 +1,85 @@
+"""Regex import extraction for Erlang.
+
+Captured forms:
+
+ -include("header.hrl"). — importer-relative / include-dir
+ -include_lib("app/include/header.hrl"). — library include (app-prefixed)
+ -behaviour(gen_thing). / -behavior(…) — callback-module dependency
+ mod:fun(Args) — module-qualified call
+
+Module-qualified calls are the real dependency spine of Erlang's flat
+namespace, but a bare regex over call sites would drown the graph in
+stdlib references (``io:format``, ``lists:map``). They are therefore
+emitted with a ``call:`` marker prefix and the resolver applies a strict
+local-index-hit-or-drop policy: a qualified call only becomes an edge
+when the target module is declared in this repo, and never mints an
+external node.
+"""
+
+from __future__ import annotations
+
+import re
+
+from ..models import Import
+
+_INCLUDE_RE = re.compile(r'^-(include|include_lib)\("([^"]+)"\)', re.M)
+_BEHAVIOUR_RE = re.compile(r"^-behaviou?r\(([a-z][A-Za-z0-9_]*)\)", re.M)
+# module:function( — both atoms lowercase-led; ?MACRO: and Var: forms don't match.
+_QUALIFIED_CALL_RE = re.compile(r"\b([a-z][a-z0-9_]*):[a-z][a-z0-9_]*\(")
+_COMMENT_RE = re.compile(r"%[^\n]*")
+_STRING_RE = re.compile(r'"(?:\\.|[^"\\])*"')
+
+
+def extract_erlang_imports(text: str) -> list[Import]:
+ imports: list[Import] = []
+ seen: set[str] = set()
+
+ for match in _INCLUDE_RE.finditer(text):
+ directive, header = match.group(1), match.group(2)
+ module = f"lib:{header}" if directive == "include_lib" else header
+ if module in seen:
+ continue
+ seen.add(module)
+ imports.append(
+ Import(
+ raw_statement=match.group(0),
+ module_path=module,
+ imported_names=[],
+ is_relative=directive == "include",
+ resolved_file=None,
+ )
+ )
+
+ for match in _BEHAVIOUR_RE.finditer(text):
+ module = match.group(1)
+ if module in seen:
+ continue
+ seen.add(module)
+ imports.append(
+ Import(
+ raw_statement=match.group(0),
+ module_path=module,
+ imported_names=[],
+ is_relative=False,
+ resolved_file=None,
+ )
+ )
+
+ # Strip comments and strings before the call scan — `%% lists:map(`
+ # in a comment or a log format string must not mint an edge.
+ stripped = _STRING_RE.sub('""', _COMMENT_RE.sub("", text))
+ for match in _QUALIFIED_CALL_RE.finditer(stripped):
+ module = f"call:{match.group(1)}"
+ if module in seen:
+ continue
+ seen.add(module)
+ imports.append(
+ Import(
+ raw_statement=match.group(0).rstrip("("),
+ module_path=module,
+ imported_names=[],
+ is_relative=False,
+ resolved_file=None,
+ )
+ )
+ return imports
diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/fsharp.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/fsharp.py
new file mode 100644
index 000000000..d711592d9
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/fsharp.py
@@ -0,0 +1,40 @@
+"""Regex import extraction for F#.
+
+Captured form:
+
+ open Foo.Bar
+ open type Foo.Bar.Baz
+
+``open`` names a namespace or module — F#'s only textual cross-file
+reference. The compile-order dependency spine (fsproj ``<Compile
+Include>`` order) is project-file data, not source text, and is emitted
+by a dedicated graph pass instead.
+"""
+
+from __future__ import annotations
+
+import re
+
+from ..models import Import
+
+_OPEN_RE = re.compile(r"^[ \t]*open[ \t]+(?:type[ \t]+)?([A-Z][A-Za-z0-9_.]*)", re.M)
+
+
+def extract_fsharp_imports(text: str) -> list[Import]:
+ imports: list[Import] = []
+ seen: set[str] = set()
+ for match in _OPEN_RE.finditer(text):
+ module = match.group(1)
+ if module in seen:
+ continue
+ seen.add(module)
+ imports.append(
+ Import(
+ raw_statement=match.group(0).strip(),
+ module_path=module,
+ imported_names=[],
+ is_relative=False,
+ resolved_file=None,
+ )
+ )
+ return imports
diff --git a/packages/core/src/repowise/core/ingestion/lightweight_imports/haskell.py b/packages/core/src/repowise/core/ingestion/lightweight_imports/haskell.py
new file mode 100644
index 000000000..80bd6aa02
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/lightweight_imports/haskell.py
@@ -0,0 +1,49 @@
+"""Regex import extraction for Haskell.
+
+Captured forms:
+
+ import Foo.Bar
+ import qualified Foo.Bar as FB
+ import Foo.Bar (thing, Other)
+ import safe qualified Foo.Bar
+ import "pkg" Foo.Bar — PackageImports
+
+The import list / hiding clause is not parsed — the edge target is the
+module, which is all the file graph needs.
+"""
+
+from __future__ import annotations
+
+import re
+
+from ..models import Import
+
+_IMPORT_RE = re.compile(
+ r"^import[ \t]+"
+ r"(?:safe[ \t]+)?"
+ r"(?:qualified[ \t]+)?"
+ r'(?:"[^"]+"[ \t]+)?'
+ r"(?:qualified[ \t]+)?" # GHC accepts qualified after the package literal too
+ r"([A-Z][A-Za-z0-9_.']*)",
+ re.M,
+)
+
+
+def extract_haskell_imports(text: str) -> list[Import]:
+ imports: list[Import] = []
+ seen: set[str] = set()
+ for match in _IMPORT_RE.finditer(text):
+ module = match.group(1)
+ if module in seen:
+ continue
+ seen.add(module)
+ imports.append(
+ Import(
+ raw_statement=match.group(0).strip(),
+ module_path=module,
+ imported_names=[],
+ is_relative=False,
+ resolved_file=None,
+ )
+ )
+ return imports
diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.py
index 0caaf9a5f..74ad68443 100644
--- a/packages/core/src/repowise/core/ingestion/models.py
+++ b/packages/core/src/repowise/core/ingestion/models.py
@@ -34,6 +34,25 @@ LanguageTag = Literal[
"kotlin",
"scala",
"luau",
+ # Passthrough code languages (no AST parser yet — empty ParsedFile,
+ # files enter the graph via the generic resolver). Before these tags
+ # existed the traverser silently skipped such files as unknown, so e.g.
+ # an Elixir repo indexed only its yaml/markdown.
+ "elixir",
+ "erlang",
+ "clojure",
+ "dart",
+ "haskell",
+ "ocaml",
+ "fsharp",
+ "crystal",
+ "nim",
+ "dlang",
+ "elm",
+ "zig",
+ "objectivec",
+ "julia",
+ "r",
"shell",
"yaml",
"json",
@@ -44,6 +63,7 @@ LanguageTag = Literal[
"dockerfile",
"makefile",
"markdown",
+ "asciidoc",
"sql",
"openapi",
"xaml",
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index d827a4a84..71aa5c002 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -56,6 +56,7 @@ from .models import (
TypeReference,
)
from .parser_helpers import (
+ TYPE_HEAD_EXTRACTORS,
_build_qualified_name,
_classify_param_origin,
_collect_error_nodes,
@@ -66,7 +67,6 @@ from .parser_helpers import (
_is_async_node,
_qualified_cpp_parent,
_run_query,
- TYPE_HEAD_EXTRACTORS,
)
log = structlog.get_logger(__name__)
@@ -234,10 +234,15 @@ class ASTParser:
language=lang,
path=file_info.path,
)
+ # Languages without a grammar may still carry regex-tier import
+ # extraction (their specs declare import_support="partial");
+ # symbols stay empty — the regex tier claims no symbol knowledge.
+ from .lightweight_imports import extract_lightweight_imports
+
return ParsedFile(
file_info=file_info,
symbols=[],
- imports=[],
+ imports=extract_lightweight_imports(file_info, source),
exports=[],
docstring=None,
parse_errors=[],
@@ -529,6 +534,67 @@ class ASTParser:
if not module_text:
continue
+ # Scala: the query's ``(identifier)`` capture is only the FIRST
+ # path segment (``import com.foo.Bar`` arrived as ``com``), and
+ # one declaration can hold several clauses, brace selectors,
+ # renames, and wildcards. Reconstruct full dotted paths and emit
+ # one Import per selected name.
+ if file_info.language == "scala" and stmt_node.type == "import_declaration":
+ from .extractors.bindings.scala import expand_scala_import_clauses
+ from .models import NamedBinding
+
+ for clause_path, clause_names in expand_scala_import_clauses(stmt_node, src):
+ local = clause_names[0]
+ exported = None if local == "*" else clause_path.rsplit(".", 1)[-1]
+ imports.append(
+ Import(
+ raw_statement=raw,
+ module_path=clause_path,
+ imported_names=clause_names,
+ is_relative=False,
+ resolved_file=None,
+ bindings=[
+ NamedBinding(
+ local_name=local,
+ exported_name=exported,
+ source_file=None,
+ )
+ ],
+ is_reexport=False,
+ )
+ )
+ continue
+
+ # CommonJS assignment / Object.assign shapes: the query captures
+ # the outer statement once; walk it for every require() it
+ # contains (a hub like Object.assign(module.exports,
+ # require('./a'), require('./b')) is several imports) and mark
+ # module.exports/exports shapes as re-exports so barrel logic
+ # treats CJS hubs like ESM barrels.
+ if file_info.language in ("javascript", "typescript") and stmt_node.type in (
+ "assignment_expression",
+ "call_expression",
+ ):
+ from .extractors.bindings.ts_js import (
+ cjs_statement_is_reexport,
+ collect_cjs_requires,
+ )
+
+ cjs_reexport = cjs_statement_is_reexport(stmt_node, src)
+ for cjs_module in collect_cjs_requires(stmt_node, src):
+ imports.append(
+ Import(
+ raw_statement=raw,
+ module_path=cjs_module,
+ imported_names=["*"] if cjs_reexport else [],
+ is_relative=cjs_module.startswith("."),
+ resolved_file=None,
+ bindings=[],
+ is_reexport=cjs_reexport,
+ )
+ )
+ continue
+
# Rust #[path = "..."] attribute overrides module file location.
# In tree-sitter-rust, outer attributes are preceding siblings of
# the item, not children.
@@ -549,6 +615,16 @@ class ASTParser:
k -= 1
break
+ # JVM wildcard imports: the grammar query captures the scoped
+ # identifier only — the trailing ``*`` is a sibling node, so
+ # ``import com.foo.*`` arrives as ``com.foo`` and the resolvers'
+ # package fan-out branch can never fire. Restore it from the
+ # raw statement text.
+ if file_info.language in ("java", "kotlin") and not module_text.endswith("*"):
+ stmt_text = raw.rstrip().rstrip(";").rstrip()
+ if stmt_text.endswith(".*"):
+ module_text += ".*"
+
# Language-specific import name + binding extraction
imported_names, bindings = extract_import_bindings(stmt_node, src, file_info.language)
is_relative = (
@@ -562,6 +638,10 @@ class ASTParser:
if child.type == "visibility_modifier":
is_reexport = True
break
+ # Swift: ``@_exported import FooKit`` re-exports the module —
+ # importers of THIS module see FooKit's symbols too.
+ elif file_info.language == "swift" and raw.startswith("@_exported"):
+ is_reexport = True
imports.append(
Import(
diff --git a/packages/core/src/repowise/core/ingestion/queries/javascript.scm b/packages/core/src/repowise/core/ingestion/queries/javascript.scm
index edda78495..227eeb458 100644
--- a/packages/core/src/repowise/core/ingestion/queries/javascript.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/javascript.scm
@@ -53,6 +53,44 @@
(#eq? @_require "require")
) @import.statement
+; CommonJS member pick: var x = require('./svc').member — the value is a
+; member_expression WRAPPING the call, so the bare-call declarator pattern
+; above never matches it (express's lib/*.js are full of this shape).
+(variable_declarator
+ value: (member_expression
+ object: (call_expression
+ function: (identifier) @_require_member
+ arguments: (arguments (string) @import.module)))
+ (#eq? @_require_member "require")
+) @import.statement
+
+; CommonJS re-export / property assignment:
+; module.exports = require('./x')
+; exports.foo = require('./y')
+; module.exports.foo = require('./z')
+; (any member-expression LHS is a genuine dependency; the parser decides
+; whether the shape is a re-export from the statement context)
+(assignment_expression
+ left: (member_expression)
+ right: (call_expression
+ function: (identifier) @_require_assign
+ arguments: (arguments (string) @import.module))
+ (#eq? @_require_assign "require")
+) @import.statement
+
+; CommonJS hub: Object.assign(module.exports, require('./a'), require('./b'))
+; The parser walks the whole statement for every require() it contains, so
+; multi-require hubs survive raw-statement dedup.
+(call_expression
+ function: (member_expression) @_objassign_fn
+ arguments: (arguments
+ (call_expression
+ function: (identifier) @_require_arg
+ arguments: (arguments (string) @import.module)))
+ (#eq? @_objassign_fn "Object.assign")
+ (#eq? @_require_arg "require")
+) @import.statement
+
; ---------------------------------------------------------------------------
; Calls
; ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/queries/php.scm b/packages/core/src/repowise/core/ingestion/queries/php.scm
index f8ef60052..47f8da4f4 100644
--- a/packages/core/src/repowise/core/ingestion/queries/php.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/php.scm
@@ -66,11 +66,26 @@
)
) @import.statement
-; require/include file imports
+; require/include file imports — double-quoted strings are
+; encapsed_string nodes, single-quoted (the common form) are plain
+; string nodes, and the __DIR__ . '<path>' idiom nests either inside a
+; binary_expression. All shapes capture the literal path.
(require_expression (encapsed_string (string_content) @import.module)) @import.statement
(require_once_expression (encapsed_string (string_content) @import.module)) @import.statement
(include_expression (encapsed_string (string_content) @import.module)) @import.statement
(include_once_expression (encapsed_string (string_content) @import.module)) @import.statement
+(require_expression (string (string_content) @import.module)) @import.statement
+(require_once_expression (string (string_content) @import.module)) @import.statement
+(include_expression (string (string_content) @import.module)) @import.statement
+(include_once_expression (string (string_content) @import.module)) @import.statement
+(require_expression (binary_expression (string (string_content) @import.module))) @import.statement
+(require_once_expression (binary_expression (string (string_content) @import.module))) @import.statement
+(include_expression (binary_expression (string (string_content) @import.module))) @import.statement
+(include_once_expression (binary_expression (string (string_content) @import.module))) @import.statement
+(require_expression (binary_expression (encapsed_string (string_content) @import.module))) @import.statement
+(require_once_expression (binary_expression (encapsed_string (string_content) @import.module))) @import.statement
+(include_expression (binary_expression (encapsed_string (string_content) @import.module))) @import.statement
+(include_once_expression (binary_expression (encapsed_string (string_content) @import.module))) @import.statement
; ---------------------------------------------------------------------------
; Calls
diff --git a/packages/core/src/repowise/core/ingestion/queries/typescript.scm b/packages/core/src/repowise/core/ingestion/queries/typescript.scm
index 496626abd..c62fc71ba 100644
--- a/packages/core/src/repowise/core/ingestion/queries/typescript.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/typescript.scm
@@ -98,6 +98,44 @@
(#eq? @_require "require")
) @import.statement
+; CommonJS member pick: var x = require('./svc').member — the value is a
+; member_expression WRAPPING the call, so the bare-call declarator pattern
+; above never matches it (express's lib/*.js are full of this shape).
+(variable_declarator
+ value: (member_expression
+ object: (call_expression
+ function: (identifier) @_require_member
+ arguments: (arguments (string) @import.module)))
+ (#eq? @_require_member "require")
+) @import.statement
+
+; CommonJS re-export / property assignment:
+; module.exports = require('./x')
+; exports.foo = require('./y')
+; module.exports.foo = require('./z')
+; (any member-expression LHS is a genuine dependency; the parser decides
+; whether the shape is a re-export from the statement context)
+(assignment_expression
+ left: (member_expression)
+ right: (call_expression
+ function: (identifier) @_require_assign
+ arguments: (arguments (string) @import.module))
+ (#eq? @_require_assign "require")
+) @import.statement
+
+; CommonJS hub: Object.assign(module.exports, require('./a'), require('./b'))
+; The parser walks the whole statement for every require() it contains, so
+; multi-require hubs survive raw-statement dedup.
+(call_expression
+ function: (member_expression) @_objassign_fn
+ arguments: (arguments
+ (call_expression
+ function: (identifier) @_require_arg
+ arguments: (arguments (string) @import.module)))
+ (#eq? @_objassign_fn "Object.assign")
+ (#eq? @_require_arg "require")
+) @import.statement
+
; ---------------------------------------------------------------------------
; Calls
; ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
index efb13b3e4..e6d76b8b5 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py
@@ -4,11 +4,17 @@ from __future__ import annotations
from collections.abc import Callable
+from .clojure import resolve_clojure_import
from .context import ResolverContext
from .cpp import resolve_cpp_import
from .csharp import resolve_csharp_import
+from .dart import resolve_dart_import
+from .elixir import resolve_elixir_import
+from .erlang import resolve_erlang_import
+from .fsharp import resolve_fsharp_import
from .generic import resolve_generic_import
from .go import resolve_go_import
+from .haskell import resolve_haskell_import
from .java import resolve_java_import
from .kotlin import resolve_kotlin_import
from .luau import resolve_luau_import
@@ -38,6 +44,13 @@ _RESOLVERS: dict[str, ResolverFn] = {
"swift": resolve_swift_import,
"scala": resolve_scala_import,
"php": resolve_php_import,
+ # Lightweight regex-tier resolvers (import_support="partial")
+ "elixir": resolve_elixir_import,
+ "dart": resolve_dart_import,
+ "clojure": resolve_clojure_import,
+ "haskell": resolve_haskell_import,
+ "erlang": resolve_erlang_import,
+ "fsharp": resolve_fsharp_import,
}
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/clojure.py b/packages/core/src/repowise/core/ingestion/resolvers/clojure.py
new file mode 100644
index 000000000..baf615ee6
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/clojure.py
@@ -0,0 +1,71 @@
+"""Clojure import resolution (lightweight regex tier).
+
+Resolution order:
+
+1. Declared-namespace index — ``(ns foo.bar)`` scanned from every
+ ``.clj``/``.cljc``/``.cljs`` file, with the classpath convention
+ (``src/foo/bar.clj`` → ``foo.bar``, underscores → dashes) as the
+ inverse fallback. Namespace → file is one-to-one, so no segment
+ stripping.
+2. ``clojure.*`` / ClojureScript core namespaces → dropped after a local
+ miss.
+3. Everything else → external node.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+from .module_name_index import get_or_build_module_index, lookup_module
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+_NS_DECL_RE = re.compile(r"^[ \t]*\(ns[ \t\n]+\^?[:{]?[ \t\n]*([A-Za-z][\w*+!?<>=.-]*)", re.M)
+
+# Source roots whose remainder maps to the namespace (deps.edn default +
+# Leiningen + Maven-style layouts).
+_SOURCE_ROOTS = (
+ "src/main/clojure/",
+ "src/test/clojure/",
+ "src/",
+ "test/",
+ "dev/",
+)
+
+_CORE_PREFIXES = ("clojure.", "cljs.", "goog.")
+
+
+def _path_to_namespace(path: str) -> str | None:
+ stem = path.rsplit(".", 1)[0]
+ for root in _SOURCE_ROOTS:
+ idx = stem.find(root)
+ if idx == 0 or (idx > 0 and stem[idx - 1] == "/"):
+ tail = stem[idx + len(root) :]
+ if tail:
+ return tail.replace("/", ".").replace("_", "-")
+ return None
+
+
+def _get_index(ctx: ResolverContext) -> dict[str, list[str]]:
+ return get_or_build_module_index(
+ ctx,
+ cache_attr="_clojure_ns_index",
+ extensions=(".clj", ".cljc", ".cljs"),
+ declaration_re=_NS_DECL_RE,
+ path_to_module=_path_to_namespace,
+ )
+
+
+def resolve_clojure_import(
+ module_path: str, importer_path: str, ctx: ResolverContext
+) -> str | None:
+ hit = lookup_module(_get_index(ctx), module_path)
+ if hit and hit != importer_path:
+ return hit
+ if hit == importer_path:
+ return None
+ if module_path.startswith(_CORE_PREFIXES) or module_path in ("clojure", "cljs"):
+ return None
+ return f"external:{module_path}"
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/context.py b/packages/core/src/repowise/core/ingestion/resolvers/context.py
index 54df8cb20..1a7e2fcbe 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/context.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/context.py
@@ -47,6 +47,22 @@ class ResolverContext:
# mirrors the dotnet/index.py pattern and keeps language-specific bloat
# off the dataclass.
+ # Cached sorted view of ``path_set``. Resolvers that scan for a *first*
+ # match MUST iterate this, never the raw set: set iteration order varies
+ # run-to-run (parallel parse insertion order + hash seeding), which made
+ # import targets — and everything downstream (PageRank, communities, the
+ # tour order) — nondeterministic across identical runs.
+ _sorted_paths_cache: tuple[str, ...] | None = field(
+ default=None, init=False, repr=False, compare=False
+ )
+
+ @property
+ def sorted_paths(self) -> tuple[str, ...]:
+ """Deterministically ordered view of ``path_set`` (cached)."""
+ if self._sorted_paths_cache is None:
+ self._sorted_paths_cache = tuple(sorted(self.path_set))
+ return self._sorted_paths_cache
+
def stem_lookup(self, stem: str) -> str | None:
"""Return the highest-priority path for *stem*, or None."""
candidates = self.stem_map.get(stem)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/cpp.py b/packages/core/src/repowise/core/ingestion/resolvers/cpp.py
index bf16fdb6f..f700edb95 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/cpp.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/cpp.py
@@ -192,7 +192,11 @@ def resolve_cpp_import_all(
# single-header library can otherwise pull in dozens of TUs and
# blow up the import-edge count. Cap at the target's first 32
# sources (stable order) which is enough for the rescue effect.
- for src in t.sources[:32]:
+ # Header-only targets (fmt-like: public headers, zero sources)
+ # fan out across the target's other headers instead — otherwise
+ # one included header leaves the rest of the library orphaned.
+ pool = t.sources or (t.public_headers + t.private_headers)
+ for src in pool[:32]:
if src in seen:
continue
seen.add(src)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/cpp_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/cpp_workspace.py
index 29d53b168..0d447bc61 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/cpp_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/cpp_workspace.py
@@ -406,7 +406,8 @@ def build_cpp_workspace_index(ctx: "ResolverContext") -> CppWorkspaceIndex:
if _EXPORT_LIKE_NAME_RE.match(base):
macros.add(base)
if not header_candidates:
- for p in path_set:
+ # Sorted: the 200-candidate cap below must cut deterministically.
+ for p in sorted(path_set):
if p.startswith(("include/", "include\\")) and p.lower().endswith((".h", ".hpp", ".hxx")):
header_candidates.append(p)
if len(header_candidates) > 200:
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/csharp.py b/packages/core/src/repowise/core/ingestion/resolvers/csharp.py
index e9926a2f0..998d2416a 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/csharp.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/csharp.py
@@ -61,7 +61,7 @@ def _legacy_stem_resolve(
return result
if len(parts) > 1:
dir_suffix = "/".join(parts)
- for p in ctx.path_set:
+ for p in ctx.sorted_paths:
if p.endswith(".cs") and dir_suffix.lower() in p.lower():
return p
return None
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dart.py b/packages/core/src/repowise/core/ingestion/resolvers/dart.py
new file mode 100644
index 000000000..c91694a33
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dart.py
@@ -0,0 +1,88 @@
+"""Dart import resolution (lightweight regex tier).
+
+Resolution order:
+
+1. ``dart:*`` SDK URIs → dropped (no node).
+2. ``package:<name>/<path>`` → pubspec.yaml index: every pubspec's
+ ``name:`` maps the package name to its directory, so a self-import
+ (``package:own_name/src/x.dart``) resolves to ``lib/<path>`` inside
+ that package — monorepos with several pubspecs included. Other
+ package URIs become labelled externals (``external:pub:<name>``).
+3. Relative URIs (``import``/``export``/``part``) → importer-relative
+ probe.
+4. ``part of <library.name>`` → ``library`` declaration index; unresolved
+ library names are dropped, not externalised (they are intra-package
+ by construction).
+"""
+
+from __future__ import annotations
+
+import posixpath
+import re
+from typing import TYPE_CHECKING
+
+from .module_name_index import get_or_build_module_index, lookup_module
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+_PUBSPEC_NAME_RE = re.compile(r"^name:[ \t]*[\"']?([A-Za-z0-9_]+)", re.M)
+_LIBRARY_DECL_RE = re.compile(r"^[ \t]*library[ \t]+([A-Za-z_][A-Za-z0-9_.]*)", re.M)
+
+
+def _pubspec_map(ctx: ResolverContext) -> dict[str, str]:
+ """``{package_name: package_root_dir}`` from every pubspec.yaml (cached)."""
+ cached = getattr(ctx, "_dart_pubspec_map", None)
+ if cached is not None:
+ return cached
+ result: dict[str, str] = {}
+ repo = ctx.repo_path
+ for path in ctx.sorted_paths:
+ if not (path == "pubspec.yaml" or path.endswith("/pubspec.yaml")):
+ continue
+ if repo is None:
+ continue
+ try:
+ text = (repo / path).read_text(encoding="utf-8", errors="replace")
+ except OSError:
+ continue
+ m = _PUBSPEC_NAME_RE.search(text)
+ if m:
+ root = path[: -len("pubspec.yaml")].rstrip("/")
+ result.setdefault(m.group(1), root)
+ ctx._dart_pubspec_map = result # type: ignore[attr-defined]
+ return result
+
+
+def _library_index(ctx: ResolverContext) -> dict[str, list[str]]:
+ return get_or_build_module_index(
+ ctx,
+ cache_attr="_dart_library_index",
+ extensions=(".dart",),
+ declaration_re=_LIBRARY_DECL_RE,
+ path_to_module=None,
+ )
+
+
+def resolve_dart_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
+ if module_path.startswith("dart:"):
+ return None
+
+ if module_path.startswith("package:"):
+ name, _, rest = module_path[len("package:") :].partition("/")
+ root = _pubspec_map(ctx).get(name)
+ if root is not None and rest:
+ candidate = f"{root}/lib/{rest}" if root else f"lib/{rest}"
+ if candidate in ctx.path_set:
+ return candidate
+ return f"external:pub:{name}"
+
+ if module_path.startswith("library:"):
+ return lookup_module(_library_index(ctx), module_path[len("library:") :])
+
+ # Relative URI — import/export/part 'path.dart'
+ importer_dir = posixpath.dirname(importer_path)
+ candidate = posixpath.normpath(posixpath.join(importer_dir, module_path))
+ if candidate in ctx.path_set:
+ return candidate
+ return f"external:{module_path}"
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
index a58a71ecc..28a0dd3cc 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/index.py
@@ -39,6 +39,11 @@ class DotNetProjectIndex:
with the same simple name in different namespaces). Callers rank the
candidates by project enclosure — see ``rank_type_candidates`` below."""
+ partial_types: dict[str, list[Path]] = field(default_factory=dict)
+ """Maps a fully-qualified ``partial`` type name → files carrying a
+ fragment. Co-fragments of one FQN are literally one class — the
+ graph links them bidirectionally."""
+
project_globals: dict[Path, set[str]] = field(default_factory=dict)
"""Maps a project's directory → global+implicit using namespaces."""
@@ -264,8 +269,8 @@ def build_index(repo_path: Path, *, prune_nested_git: bool = True) -> DotNetProj
]
index.file_to_project = _bucket_files_by_project(all_cs_files, project_dirs)
- # ---- 4. Namespace + type map from cached texts ----
- index.namespace_map, index.type_map = build_namespace_map(
+ # ---- 4. Namespace + type + partial maps from cached texts ----
+ index.namespace_map, index.type_map, index.partial_types = build_namespace_map(
all_cs_files, texts=cs_texts
)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py
index 1f0676bee..f228dc7ce 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/dotnet/namespace_map.py
@@ -33,8 +33,8 @@ _NAMESPACE_RE = re.compile(
# alternation does not include ``/`` and the modifier-soup group is
# anchored on whitespace, not arbitrary text.
_TYPE_DECL_RE = re.compile(
- r"(?:^|;)\s*(?:(?:public|private|internal|protected|static|sealed|abstract|partial|"
- r"readonly|ref|unsafe|new|file)\s+)*"
+ r"(?:^|;)\s*((?:(?:public|private|internal|protected|static|sealed|abstract|partial|"
+ r"readonly|ref|unsafe|new|file)\s+)*)"
r"(?:class|interface|struct|enum|record(?:\s+(?:class|struct))?)\s+"
r"([A-Za-z_]\w*)",
re.MULTILINE,
@@ -50,28 +50,86 @@ def declared_namespaces(cs_text: str) -> list[str]:
return [m.group(1) for m in _NAMESPACE_RE.finditer(cs_text)]
+class TypeDecl:
+ """One type declaration: bare + one-level-qualified name, partial flag."""
+
+ __slots__ = ("is_partial", "name", "namespace", "qualified")
+
+ def __init__(self, name: str, qualified: str, namespace: str, is_partial: bool):
+ self.name = name
+ self.qualified = qualified
+ self.namespace = namespace
+ self.is_partial = is_partial
+
+ @property
+ def fqn(self) -> str:
+ return f"{self.namespace}.{self.qualified}" if self.namespace else self.qualified
+
+
+def scan_type_declarations(cs_text: str) -> list[TypeDecl]:
+ """Scan *cs_text* for type declarations with nesting + partial info.
+
+ Nesting is tracked one level via raw brace depth at each match
+ position (strings/comments are not lexed — same pragmatics as the
+ rest of this module): a declaration whose depth exceeds the previous
+ declaration's gets ``Outer.Inner`` as its qualified name. Deeper
+ nesting collapses onto the immediate parent (recorded cut). The
+ namespace is the nearest declaration preceding the match.
+ """
+ ns_positions = [(m.start(), m.group(1)) for m in _NAMESPACE_RE.finditer(cs_text)]
+
+ decls: list[TypeDecl] = []
+ stack: list[tuple[int, str]] = [] # (brace depth at decl, bare name)
+ pos = 0
+ depth = 0
+ for m in _TYPE_DECL_RE.finditer(cs_text):
+ depth += cs_text.count("{", pos, m.start()) - cs_text.count("}", pos, m.start())
+ pos = m.start()
+
+ while stack and stack[-1][0] >= depth:
+ stack.pop()
+
+ name = m.group(2)
+ parent = stack[-1][1] if stack else None
+ qualified = f"{parent}.{name}" if parent else name
+ namespace = ""
+ for ns_start, ns in ns_positions:
+ if ns_start < m.start():
+ namespace = ns
+ else:
+ break
+ is_partial = "partial" in (m.group(1) or "").split()
+ decls.append(TypeDecl(name, qualified, namespace, is_partial))
+ stack.append((depth, name))
+ return decls
+
+
def declared_type_names(cs_text: str) -> list[str]:
- """Return every top-level type name declared in *cs_text*.
+ """Return every type name declared in *cs_text* (bare, unqualified).
Generic parameters and base clauses are stripped. ``partial`` types
declared across multiple files yield one match per file — the caller
builds a list-valued map so all defining files are surfaced.
"""
- return [m.group(1) for m in _TYPE_DECL_RE.finditer(cs_text)]
+ return [m.group(2) for m in _TYPE_DECL_RE.finditer(cs_text)]
def build_namespace_map(
cs_files: list[Path],
*,
texts: dict[Path, str] | None = None,
-) -> tuple[dict[str, list[Path]], dict[str, list[Path]]]:
- """Return ``(namespace_map, type_map)`` for every .cs file given.
+) -> tuple[dict[str, list[Path]], dict[str, list[Path]], dict[str, list[Path]]]:
+ """Return ``(namespace_map, type_map, partial_map)`` for the .cs files.
* ``namespace_map[ns]`` → files declaring that namespace.
- * ``type_map[type_name]`` → files declaring that type (unqualified
- name). Multiple files per name is expected (partial types,
- same-named types in different namespaces) — callers disambiguate
- by project enclosure.
+ * ``type_map[type_name]`` → files declaring that type. Keyed by both
+ the unqualified name and (for one-level nested types) the
+ ``Outer.Inner`` qualified form. Multiple files per name is
+ expected (partial types, same-named types in different
+ namespaces) — callers disambiguate by project enclosure.
+ * ``partial_map[fqn]`` → files carrying a ``partial`` declaration of
+ that fully-qualified type. Fragments of one class across several
+ files are literally one type — the graph links them.
When *texts* is provided, file contents are read from the dict
rather than the filesystem — this is the hot path used by
@@ -81,6 +139,7 @@ def build_namespace_map(
"""
namespaces: dict[str, list[Path]] = {}
types: dict[str, list[Path]] = {}
+ partials: dict[str, list[Path]] = {}
for path in cs_files:
if texts is not None:
text = texts.get(path)
@@ -98,9 +157,14 @@ def build_namespace_map(
seen_ns.add(ns)
namespaces.setdefault(ns, []).append(path)
seen_t: set[str] = set()
- for tn in declared_type_names(text):
- if tn in seen_t:
- continue
- seen_t.add(tn)
- types.setdefault(tn, []).append(path)
- return namespaces, types
+ seen_p: set[str] = set()
+ for decl in scan_type_declarations(text):
+ for key in {decl.name, decl.qualified}:
+ if key in seen_t:
+ continue
+ seen_t.add(key)
+ types.setdefault(key, []).append(path)
+ if decl.is_partial and decl.fqn not in seen_p:
+ seen_p.add(decl.fqn)
+ partials.setdefault(decl.fqn, []).append(path)
+ return namespaces, types, partials
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/elixir.py b/packages/core/src/repowise/core/ingestion/resolvers/elixir.py
new file mode 100644
index 000000000..227f188cc
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/elixir.py
@@ -0,0 +1,81 @@
+"""Elixir import resolution (lightweight regex tier).
+
+Resolution order:
+
+1. Declared-module index — ``defmodule Foo.Bar`` scanned from every
+ ``.ex``/``.exs`` file, with the Mix path convention
+ (``lib/foo/bar.ex`` → ``Foo.Bar``, umbrella ``apps/<app>/lib/…``
+ included) as the inverse fallback for files without declarations.
+ Trailing segments are stripped progressively so ``alias Foo.Bar.Baz``
+ still hits ``foo/bar.ex`` when ``Baz`` is a nested module.
+2. Elixir/OTP standard library → dropped (no node), but only AFTER the
+ local lookup misses — a repo may BE one of these libraries.
+3. Everything else → external node.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+from .module_name_index import get_or_build_module_index, lookup_with_trailing_strip
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+_DEFMODULE_RE = re.compile(r"^[ \t]*defmodule[ \t]+([A-Z][A-Za-z0-9_.]*)", re.M)
+
+# First-segment match: Elixir stdlib + OTP-shipped applications. Checked
+# only after the local index misses (D-034 policy shape).
+_ELIXIR_STDLIB = frozenset(
+ {
+ "Access", "Agent", "Application", "Atom", "Base", "Behaviour", "Bitwise",
+ "Calendar", "Code", "Config", "Date", "DateTime", "Duration", "DynamicSupervisor",
+ "EEx", "Enum", "Enumerable", "Exception", "ExUnit", "File", "Float", "Function",
+ "GenEvent", "GenServer", "IEx", "IO", "Inspect", "Integer", "JSON", "Kernel",
+ "Keyword", "List", "Logger", "Macro", "Map", "MapSet", "Mix", "Module",
+ "NaiveDateTime", "Node", "OptionParser", "PartitionSupervisor", "Path", "Port",
+ "Process", "Protocol", "Range", "Record", "Regex", "Registry", "Stream",
+ "String", "StringIO", "Supervisor", "System", "Task", "Time", "Tuple", "URI",
+ "Version",
+ }
+)
+
+
+def _path_to_module(path: str) -> str | None:
+ """Mix convention inverse: ``[apps/<app>/]lib/foo/bar.ex`` → ``Foo.Bar``."""
+ segments = path.rsplit(".", 1)[0].split("/")
+ anchor = -1
+ for i, seg in enumerate(segments[:-1]): # last "lib" before the filename
+ if seg == "lib":
+ anchor = i
+ if anchor == -1:
+ return None
+ tail = segments[anchor + 1 :]
+ if not tail:
+ return None
+ return ".".join("".join(part.capitalize() for part in seg.split("_")) for seg in tail)
+
+
+def _get_index(ctx: ResolverContext) -> dict[str, list[str]]:
+ return get_or_build_module_index(
+ ctx,
+ cache_attr="_elixir_module_index",
+ extensions=(".ex", ".exs"),
+ declaration_re=_DEFMODULE_RE,
+ path_to_module=_path_to_module,
+ )
+
+
+def resolve_elixir_import(
+ module_path: str, importer_path: str, ctx: ResolverContext
+) -> str | None:
+ index = _get_index(ctx)
+ hit = lookup_with_trailing_strip(index, module_path)
+ if hit and hit != importer_path:
+ return hit
+ if module_path.split(".", 1)[0] in _ELIXIR_STDLIB:
+ return None
+ if hit == importer_path: # self-reference (alias of a sibling nested module)
+ return None
+ return f"external:{module_path}"
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/erlang.py b/packages/core/src/repowise/core/ingestion/resolvers/erlang.py
new file mode 100644
index 000000000..97e58b8b5
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/erlang.py
@@ -0,0 +1,102 @@
+"""Erlang import resolution (lightweight regex tier).
+
+Resolution per extracted form:
+
+- ``-include("h.hrl")`` → importer-relative probe, then the app-local and
+ repo-root ``include/`` conventions, then a deterministic
+ ``…/include/h.hrl`` suffix scan.
+- ``-include_lib("app/include/h.hrl")`` (``lib:`` marker) → the app may be
+ THIS repo (rebar umbrella ``apps/<app>/include``); otherwise a labelled
+ external.
+- ``-behaviour(mod)`` / bare modules → declared ``-module(x)`` index
+ (flat namespace; filename stem as inverse); OTP behaviours drop after
+ a local miss.
+- ``call:mod`` (module-qualified call sites) → strict local-hit-or-drop:
+ an edge only when the module is declared in this repo, never an
+ external node — anything else would drown the graph in stdlib calls.
+"""
+
+from __future__ import annotations
+
+import posixpath
+import re
+from typing import TYPE_CHECKING
+
+from .module_name_index import get_or_build_module_index, lookup_module
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+_MODULE_DECL_RE = re.compile(r"^-module\(([a-z][A-Za-z0-9_]*)\)", re.M)
+
+_OTP_MODULES = frozenset(
+ {
+ "application", "gen_event", "gen_fsm", "gen_server", "gen_statem", "supervisor",
+ "supervisor_bridge", "ct_suite",
+ }
+)
+
+
+def _path_to_module(path: str) -> str | None:
+ stem = path.rsplit("/", 1)[-1].rsplit(".", 1)[0]
+ return stem if stem and stem[0].islower() else None
+
+
+def _get_index(ctx: ResolverContext) -> dict[str, list[str]]:
+ return get_or_build_module_index(
+ ctx,
+ cache_attr="_erlang_module_index",
+ extensions=(".erl",),
+ declaration_re=_MODULE_DECL_RE,
+ path_to_module=_path_to_module,
+ )
+
+
+def _resolve_include(header: str, importer_path: str, ctx: ResolverContext) -> str | None:
+ importer_dir = posixpath.dirname(importer_path)
+ candidates = [
+ posixpath.normpath(posixpath.join(importer_dir, header)),
+ # src/foo.erl including a header from its app's include/ dir
+ posixpath.normpath(posixpath.join(importer_dir, "..", "include", header)),
+ f"include/{header}",
+ header,
+ ]
+ for candidate in candidates:
+ if candidate in ctx.path_set:
+ return candidate
+ suffix = f"/include/{header}"
+ for path in ctx.sorted_paths:
+ if path.endswith(suffix):
+ return path
+ return f"external:{header}"
+
+
+def _resolve_include_lib(spec: str, ctx: ResolverContext) -> str | None:
+ app, _, rest = spec.partition("/")
+ if rest:
+ suffix = f"{app}/{rest}"
+ for path in ctx.sorted_paths:
+ if path == suffix or path.endswith(f"/{suffix}"):
+ return path
+ return f"external:{app}"
+
+
+def resolve_erlang_import(
+ module_path: str, importer_path: str, ctx: ResolverContext
+) -> str | None:
+ if module_path.startswith("lib:"):
+ return _resolve_include_lib(module_path[len("lib:") :], ctx)
+ if module_path.endswith(".hrl"):
+ return _resolve_include(module_path, importer_path, ctx)
+
+ strict = module_path.startswith("call:")
+ module = module_path[len("call:") :] if strict else module_path
+
+ hit = lookup_module(_get_index(ctx), module)
+ if hit and hit != importer_path:
+ return hit
+ if strict or hit == importer_path:
+ return None # qualified calls: local hit or nothing
+ if module in _OTP_MODULES:
+ return None
+ return f"external:{module}"
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/fsharp.py b/packages/core/src/repowise/core/ingestion/resolvers/fsharp.py
new file mode 100644
index 000000000..a6b07fa4d
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/fsharp.py
@@ -0,0 +1,68 @@
+"""F# import resolution (lightweight regex tier).
+
+``open Foo.Bar`` names a namespace or a top-level module. Namespaces span
+many files, so resolution is deliberately conservative:
+
+1. Declared-name index — file-level ``namespace Foo.Bar`` /
+ ``module Foo.Bar`` headers (nested ``module X =`` bindings are
+ excluded by the no-``=`` guard). An ``open`` resolves only when
+ exactly ONE other file declares the name — an ambiguous namespace
+ produces no edge rather than a guessed one. Trailing segments strip
+ progressively (``open Foo.Bar.Helpers`` hits the file-level module
+ ``Foo.Bar`` when ``Helpers`` is nested inside it).
+2. ``System.* / Microsoft.* / FSharp.*`` → dropped after a local miss.
+3. Everything else → external node.
+
+The real F# dependency spine — fsproj ``<Compile Include>`` order — is
+emitted separately by the compile-order graph pass.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+from .module_name_index import get_or_build_module_index
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+# File-level declarations only: a nested module binding always carries
+# `= …` on the same line; `module rec` / access modifiers allowed.
+_DECL_RE = re.compile(
+ r"^(?:namespace[ \t]+(?:rec[ \t]+)?|"
+ r"module[ \t]+(?:rec[ \t]+)?(?:public[ \t]+|private[ \t]+|internal[ \t]+)?)"
+ r"([A-Z][A-Za-z0-9_.]*)[ \t]*\r?$",
+ re.M,
+)
+
+_DOTNET_PREFIXES = frozenset({"System", "Microsoft", "FSharp"})
+
+
+def _get_index(ctx: ResolverContext) -> dict[str, list[str]]:
+ return get_or_build_module_index(
+ ctx,
+ cache_attr="_fsharp_module_index",
+ extensions=(".fs", ".fsx"),
+ declaration_re=_DECL_RE,
+ path_to_module=None,
+ )
+
+
+def resolve_fsharp_import(
+ module_path: str, importer_path: str, ctx: ResolverContext
+) -> str | None:
+ index = _get_index(ctx)
+ candidate = module_path
+ while candidate:
+ declarers = [p for p in index.get(candidate, ()) if p != importer_path]
+ if declarers:
+ # exactly one declaring file = unambiguous; a namespace spanning
+ # several files yields no edge (no guessing)
+ return declarers[0] if len(declarers) == 1 else None
+ if "." not in candidate:
+ break
+ candidate = candidate.rsplit(".", 1)[0]
+ if module_path.split(".", 1)[0] in _DOTNET_PREFIXES:
+ return None
+ return f"external:{module_path}"
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/go.py b/packages/core/src/repowise/core/ingestion/resolvers/go.py
index 61bedb375..c1420a97f 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/go.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/go.py
@@ -71,7 +71,7 @@ def resolve_go_import(module_path: str, importer_path: str, ctx: ResolverContext
rel_dir = f"{module_dir}/{suffix}"
else:
rel_dir = module_dir or suffix
- for p in ctx.path_set:
+ for p in ctx.sorted_paths:
if p.endswith(".go"):
p_dir = str(Path(p).parent.as_posix())
if p_dir == rel_dir or (rel_dir and p_dir.endswith(f"/{rel_dir}")):
@@ -89,7 +89,7 @@ def resolve_go_import(module_path: str, importer_path: str, ctx: ResolverContext
# ``go_modules`` was not populated (e.g. tests building a context manually).
if not ctx.go_modules and ctx.go_module_path and module_path.startswith(ctx.go_module_path):
suffix = module_path[len(ctx.go_module_path) :].lstrip("/")
- for p in ctx.path_set:
+ for p in ctx.sorted_paths:
if p.endswith(".go"):
p_dir = str(Path(p).parent.as_posix())
if p_dir == suffix or p_dir.endswith(f"/{suffix}"):
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/go_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/go_workspace.py
index 1f7958225..d125127d6 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/go_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/go_workspace.py
@@ -41,6 +41,7 @@ class GoPackage:
files: tuple[str, ...] # repo-relative POSIX ``.go`` paths, sorted
build_constrained: bool = False # any file carries //go:build or // +build
has_init: bool = False # any file declares a top-level ``func init``
+ main_files: tuple[str, ...] = () # ``package main`` files declaring ``func main``
# name → defining file(s) within this package. Deferred to Phase 3
# (call/type-ref resolution) — left empty here to keep the warmup pure
# and dependency-light. See GO_PARITY_PLAN.md Phase 3.
@@ -81,17 +82,19 @@ class GoPackageIndex:
_BUILD_TAG_PREFIXES = ("//go:build", "// +build", "//+build")
-def _scan_go_file(text: str) -> tuple[str, bool, bool, bool]:
- """Return ``(pkg_name, is_main, build_constrained, has_init)``.
+def _scan_go_file(text: str) -> tuple[str, bool, bool, bool, bool]:
+ """Return ``(pkg_name, is_main, build_constrained, has_init, has_main_func)``.
Reads only what's needed to characterise the file: the ``package``
clause, whether a build constraint is present (must appear before the
package clause, in the leading comment block), and whether a top-level
- ``func init()`` is declared. Cheap line scan — no tree-sitter.
+ ``func init()`` / ``func main()`` is declared. Cheap line scan — no
+ tree-sitter.
"""
pkg_name = ""
build_constrained = False
has_init = False
+ has_main_func = False
seen_package = False
for raw in text.splitlines():
line = raw.strip()
@@ -107,7 +110,12 @@ def _scan_go_file(text: str) -> tuple[str, bool, bool, bool]:
# Top-level ``func init()`` — no receiver, exact name.
if seen_package and line.startswith("func init(") and "init()" in line.replace(" ", ""):
has_init = True
- return pkg_name, pkg_name == "main", build_constrained, has_init
+ # Top-level ``func main()`` — the program entry when the file is
+ # ``package main``. Filename is irrelevant to Go (cmd/task/task.go
+ # is as much an entry as cmd/release/main.go).
+ if seen_package and line.startswith("func main(") and "main()" in line.replace(" ", ""):
+ has_main_func = True
+ return pkg_name, pkg_name == "main", build_constrained, has_init, has_main_func
def _read_text(ctx: "ResolverContext", rel_path: str) -> str:
@@ -157,7 +165,7 @@ def build_go_package_index(ctx: "ResolverContext") -> GoPackageIndex:
go_modules = (("", ctx.go_module_path),)
files_by_dir: dict[str, list[str]] = {}
- for path in ctx.path_set:
+ for path in ctx.sorted_paths:
if not path.endswith(".go"):
continue
parent = PurePosixPath(path).parent.as_posix()
@@ -172,8 +180,9 @@ def build_go_package_index(ctx: "ResolverContext") -> GoPackageIndex:
is_main = False
build_constrained = False
has_init = False
+ main_files: list[str] = []
for f in files:
- name, file_main, file_bc, file_init = _scan_go_file(_read_text(ctx, f))
+ name, file_main, file_bc, file_init, file_main_func = _scan_go_file(_read_text(ctx, f))
# First non-empty package name wins (sibling files agree by
# Go rule, except for the ``_test`` external-test package).
if name and not pkg_name:
@@ -181,6 +190,8 @@ def build_go_package_index(ctx: "ResolverContext") -> GoPackageIndex:
is_main = is_main or file_main
build_constrained = build_constrained or file_bc
has_init = has_init or file_init
+ if file_main and file_main_func:
+ main_files.append(f)
index.packages[pkg_dir] = GoPackage(
dir=pkg_dir,
pkg_name=pkg_name,
@@ -188,6 +199,7 @@ def build_go_package_index(ctx: "ResolverContext") -> GoPackageIndex:
files=tuple(files),
build_constrained=build_constrained,
has_init=has_init,
+ main_files=tuple(main_files),
)
import_path = _import_path_for_dir(pkg_dir, go_modules)
if import_path is not None:
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/haskell.py b/packages/core/src/repowise/core/ingestion/resolvers/haskell.py
new file mode 100644
index 000000000..a63298944
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/haskell.py
@@ -0,0 +1,72 @@
+"""Haskell import resolution (lightweight regex tier).
+
+Resolution order:
+
+1. Declared-module index — ``module Foo.Bar`` scanned from every
+ ``.hs``/``.lhs`` file. The inverse fallback derives the module name
+ from the *trailing capitalized path segments*
+ (``src/Data/Aeson/Types.hs`` → ``Data.Aeson.Types``), which handles
+ arbitrary hs-source-dirs without parsing ``.cabal``/``package.yaml``
+ — Haskell's PascalCase directory convention IS the source-dir marker.
+2. base-ish namespaces (``Prelude``/``Data.*``/``Control.*``/…) →
+ dropped after a local miss. This consciously also drops external
+ *packages* living under those namespaces (e.g. ``Data.Aeson`` used
+ from another repo) rather than minting externals — same trade as the
+ JVM ``java.*`` filter: no noise edges, no false internals.
+3. Everything else → external node.
+"""
+
+from __future__ import annotations
+
+import re
+from typing import TYPE_CHECKING
+
+from .module_name_index import get_or_build_module_index, lookup_module
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+_MODULE_DECL_RE = re.compile(r"^module[ \t]+([A-Z][A-Za-z0-9_.']*)", re.M)
+
+_BASE_PREFIXES = frozenset(
+ {
+ "Prelude", "Control", "Data", "System", "GHC", "Text", "Foreign",
+ "Numeric", "Debug", "Unsafe", "Type",
+ }
+)
+
+
+def _path_to_module(path: str) -> str | None:
+ segments = path.rsplit(".", 1)[0].split("/")
+ tail: list[str] = []
+ for seg in reversed(segments):
+ if seg and seg[0].isupper():
+ tail.append(seg)
+ else:
+ break
+ if not tail:
+ return None
+ return ".".join(reversed(tail))
+
+
+def _get_index(ctx: ResolverContext) -> dict[str, list[str]]:
+ return get_or_build_module_index(
+ ctx,
+ cache_attr="_haskell_module_index",
+ extensions=(".hs", ".lhs"),
+ declaration_re=_MODULE_DECL_RE,
+ path_to_module=_path_to_module,
+ )
+
+
+def resolve_haskell_import(
+ module_path: str, importer_path: str, ctx: ResolverContext
+) -> str | None:
+ hit = lookup_module(_get_index(ctx), module_path)
+ if hit and hit != importer_path:
+ return hit
+ if hit == importer_path:
+ return None
+ if module_path.split(".", 1)[0] in _BASE_PREFIXES:
+ return None
+ return f"external:{module_path}"
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/java.py b/packages/core/src/repowise/core/ingestion/resolvers/java.py
index 7122dee7b..dfd4dbae1 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/java.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/java.py
@@ -17,7 +17,7 @@ from pathlib import PurePosixPath
from typing import TYPE_CHECKING
from .jvm_gradle import resolve_via_jvm_gradle_index
-from .jvm_workspace import get_or_build_jvm_index
+from .jvm_workspace import classify_jvm_import, get_or_build_jvm_index
if TYPE_CHECKING:
from .context import ResolverContext
@@ -49,8 +49,9 @@ def resolve_java_import_all(
jvm_index = get_or_build_jvm_index(ctx)
- # Filter java.lang.* builtins
- if jvm_index.is_java_lang(module_path):
+ # Filter JDK namespaces (java./javax./jdk.) and bare java.lang types
+ namespace_class = classify_jvm_import(module_path)
+ if namespace_class == "stdlib" or jvm_index.is_java_lang(module_path):
return ()
parts = module_path.split(".")
@@ -61,26 +62,38 @@ def resolve_java_import_all(
if not pkg_fqn:
return ()
files = jvm_index.wildcard_expand(pkg_fqn)
+ if files:
+ return files
+ # ``import static com.foo.Bar.*`` — the prefix is a type, not a
+ # package: resolve the declaring file(s) of Bar.
+ files = jvm_index.files_for_fqn(pkg_fqn) or jvm_index.files_for_member_fqn(pkg_fqn)
if files:
return files
# External package
return (ctx.add_external_node(module_path),)
- # Handle static wildcard: import static com.foo.Bar.*
- # (parsed as "com.foo.Bar.*" by the import extractor, or
- # the static keyword is stripped leaving "com.foo.Bar")
- # Also handles: import static com.foo.Bar.CONSTANT → resolve Bar
-
# Try direct FQN resolution first
files = jvm_index.files_for_fqn(module_path)
if files:
return files
+ # Static member imports: ``import static com.foo.Bar.CONSTANT`` names
+ # a member inside a type — resolve the declaring type instead.
+ files = jvm_index.files_for_member_fqn(module_path)
+ if files:
+ return files
+
# Try Gradle index (handles cases where workspace index missed something)
gradle_match = resolve_via_jvm_gradle_index(module_path, ctx)
if gradle_match is not None:
return (gradle_match,)
+ # Known-external namespaces (e.g. jakarta.) — exact lookups above get
+ # first refusal (the repo may BE that library), but the fuzzy stem /
+ # directory fallbacks below must not false-match a local file.
+ if namespace_class == "external":
+ return (ctx.add_external_node(module_path),)
+
# Try stem lookup (class name)
local = parts[-1]
result = ctx.stem_lookup(local.lower())
@@ -90,7 +103,7 @@ def resolve_java_import_all(
# Try matching package path as directory structure
if len(parts) > 1:
dir_suffix = "/".join(parts[:-1])
- for p in ctx.path_set:
+ for p in ctx.sorted_paths:
if (p.endswith(".java") or p.endswith(".kt")) and dir_suffix in p:
stem = PurePosixPath(p).stem
if stem.lower() == local.lower():
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py
index 08943ef0b..83cbfcc88 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/jvm_workspace.py
@@ -29,12 +29,53 @@ if TYPE_CHECKING:
log = structlog.get_logger(__name__)
_PACKAGE_RE = re.compile(r"^\s*package\s+([\w.]+)", re.MULTILINE)
+# Compound kinds (``enum class`` / ``annotation class`` — Kotlin) must come
+# before their single-keyword prefixes in the alternation, otherwise the
+# bare ``enum`` / ``annotation`` branch matches first and captures the
+# literal word "class" as the type name. ``trait`` and the ``case`` /
+# ``implicit`` modifiers cover Scala's type declarations.
_TOP_LEVEL_TYPE_RE = re.compile(
- r"^\s*(?:public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+|sealed\s+|open\s+|data\s+)*"
- r"(?:class|interface|enum|object|record|annotation)\s+(\w+)",
+ r"^\s*(?:public\s+|private\s+|protected\s+|internal\s+|abstract\s+|final\s+"
+ r"|sealed\s+|open\s+|data\s+|value\s+|inline\s+|case\s+|implicit\s+)*"
+ r"(?:annotation\s+class|enum\s+class|class|interface|trait|enum|object|record|annotation)\s+(\w+)",
re.MULTILINE,
)
-_JVM_EXTENSIONS = frozenset({".java", ".kt"})
+_JVM_EXTENSIONS = frozenset({".java", ".kt", ".scala"})
+
+# Chained Scala package clauses (``package org.example`` then ``package
+# tools`` → org.example.tools) are scanned line-wise from the top of the
+# file; ``package object foo`` is a definition, not a clause.
+_SCALA_PACKAGE_LINE_RE = re.compile(r"package\s+(?!object\b)([\w.]+)")
+
+# JDK / Kotlin-stdlib namespaces never resolve to repo files and produce
+# no node at all. Each prefix carries its trailing dot so matching stays
+# segment-aware (``javautil.Foo`` must not match ``java.``).
+_JAVA_STDLIB_PREFIXES = ("java.", "javax.", "jdk.")
+_KOTLIN_STDLIB_PREFIXES = ("kotlin.",)
+
+# Well-known external library namespaces: a real dependency (an external
+# node is wanted), but short-circuited before the stem/directory fallbacks
+# so e.g. ``jakarta.servlet.Filter`` can never false-match a repo-local
+# ``Filter.java``. Unlike stdlib these only apply AFTER exact workspace
+# lookup fails — a repo can legitimately contain these namespaces (the
+# library's own source tree).
+_JAVA_EXTERNAL_PREFIXES = ("jakarta.",)
+_KOTLIN_EXTERNAL_PREFIXES = ("kotlinx.",)
+
+
+def classify_jvm_import(module_path: str, *, kotlin: bool = False) -> str | None:
+ """Classify an import path as ``"stdlib"`` (drop — no node),
+ ``"external"`` (external node, skip fuzzy local fallbacks), or
+ ``None`` (may be repo-local)."""
+ if module_path.startswith(_JAVA_STDLIB_PREFIXES):
+ return "stdlib"
+ if kotlin and module_path.startswith(_KOTLIN_STDLIB_PREFIXES):
+ return "stdlib"
+ if module_path.startswith(_JAVA_EXTERNAL_PREFIXES):
+ return "external"
+ if kotlin and module_path.startswith(_KOTLIN_EXTERNAL_PREFIXES):
+ return "external"
+ return None
# Standard-library packages that should never produce import edges
_JAVA_LANG_PACKAGES = frozenset({
@@ -110,6 +151,24 @@ class JvmWorkspaceIndex:
files = pkg.exported_top_level.get(type_name)
return files if files else ()
+ def files_for_member_fqn(self, fqn: str) -> tuple[str, ...]:
+ """Resolve an import whose tail is a *member*, not a type.
+
+ Kotlin member imports (``import okio.ByteString.Companion.encodeUtf8``)
+ and Java static-member imports (``import static com.foo.Bar.CONSTANT``)
+ name a function/constant inside a type. Strip trailing segments until
+ the prefix resolves as a type FQN — ``…ByteString.Companion.encodeUtf8``
+ → ``…ByteString.Companion`` → ``…ByteString`` (hit). At least
+ ``package.Type`` (two segments) must remain.
+ """
+ parts = fqn.split(".")
+ while len(parts) > 2:
+ parts = parts[:-1]
+ files = self.files_for_fqn(".".join(parts))
+ if files:
+ return files
+ return ()
+
def wildcard_expand(self, pkg_fqn: str) -> tuple[str, ...]:
"""Expand ``import pkg.*`` → all files in the package."""
return self.files_for_package(pkg_fqn)
@@ -160,9 +219,12 @@ def _scan_jvm_file(abs_path: str) -> tuple[str, tuple[str, ...]]:
return "", ()
package = ""
- pkg_match = _PACKAGE_RE.search(text)
- if pkg_match:
- package = pkg_match.group(1)
+ if abs_path.endswith(".scala"):
+ package = _scala_package(text)
+ else:
+ pkg_match = _PACKAGE_RE.search(text)
+ if pkg_match:
+ package = pkg_match.group(1)
types: list[str] = []
for m in _TOP_LEVEL_TYPE_RE.finditer(text):
@@ -171,6 +233,27 @@ def _scan_jvm_file(abs_path: str) -> tuple[str, tuple[str, ...]]:
return package, tuple(types)
+def _scala_package(text: str) -> str:
+ """Join chained Scala package clauses from the top of the file.
+
+ ``package org.example`` followed by ``package tools`` nests —
+ the file's package is ``org.example.tools``. Scanning stops at the
+ first non-package code line so a ``package`` token later in the file
+ (strings, comments mid-file) cannot append junk.
+ """
+ pkgs: list[str] = []
+ for line in text.splitlines():
+ stripped = line.strip()
+ if not stripped or stripped.startswith(("//", "/*", "*")):
+ continue
+ m = _SCALA_PACKAGE_LINE_RE.match(stripped)
+ if m:
+ pkgs.append(m.group(1))
+ continue
+ break
+ return ".".join(pkgs)
+
+
_JPMS_PROVIDES_RE = re.compile(
r"provides\s+([\w.]+)\s+with\s+([\w.,\s]+);",
re.MULTILINE,
@@ -315,8 +398,8 @@ def build_jvm_workspace_index(ctx: "ResolverContext") -> JvmWorkspaceIndex:
pkg_files: dict[str, list[str]] = {}
pkg_types: dict[str, dict[str, list[str]]] = {}
- for path in ctx.path_set:
- if not (path.endswith(".java") or path.endswith(".kt")):
+ for path in ctx.sorted_paths:
+ if not path.endswith((".java", ".kt", ".scala")):
continue
abs_path = str((repo_path / path).resolve())
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py
index 436b7fee3..f5e990e3a 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py
@@ -10,7 +10,7 @@ from __future__ import annotations
from pathlib import PurePosixPath
from typing import TYPE_CHECKING
-from .jvm_workspace import get_or_build_jvm_index
+from .jvm_workspace import classify_jvm_import, get_or_build_jvm_index
from .kotlin_gradle import resolve_via_kotlin_index
if TYPE_CHECKING:
@@ -42,8 +42,10 @@ def resolve_kotlin_import_all(
jvm_index = get_or_build_jvm_index(ctx)
- # Filter java.lang.* builtins
- if jvm_index.is_java_lang(module_path):
+ # Filter stdlib namespaces (java./javax./jdk./kotlin.) and bare
+ # java.lang types
+ namespace_class = classify_jvm_import(module_path, kotlin=True)
+ if namespace_class == "stdlib" or jvm_index.is_java_lang(module_path):
return ()
# Handle wildcard import: import com.foo.*
@@ -53,6 +55,11 @@ def resolve_kotlin_import_all(
files = jvm_index.wildcard_expand(pkg_fqn)
if files:
return files
+ # ``import okio.ByteString.Companion.*`` — the prefix is a
+ # type (or nested object), not a package.
+ files = jvm_index.files_for_fqn(pkg_fqn) or jvm_index.files_for_member_fqn(pkg_fqn)
+ if files:
+ return files
return (ctx.add_external_node(module_path),) if module_path else ()
# Try JVM workspace index first (handles cross-language Java ↔ Kotlin)
@@ -60,11 +67,23 @@ def resolve_kotlin_import_all(
if files:
return files
+ # Member imports: ``import okio.ByteString.Companion.encodeUtf8``
+ # names a function/constant inside a type — resolve the declaring type.
+ files = jvm_index.files_for_member_fqn(module_path)
+ if files:
+ return files
+
# Gradle-aware resolution (settings.gradle subprojects)
gradle_match = resolve_via_kotlin_index(module_path, ctx)
if gradle_match is not None:
return (gradle_match,)
+ # Known-external namespaces (e.g. kotlinx.) — exact lookups above get
+ # first refusal (the repo may BE that library), but the fuzzy stem /
+ # directory fallbacks below must not false-match a local file.
+ if namespace_class == "external":
+ return (ctx.add_external_node(module_path),)
+
# Try stem lookup on the class/function name
result = ctx.stem_lookup(local.lower())
if result and (result.endswith(".kt") or result.endswith(".kts") or result.endswith(".java")):
@@ -73,7 +92,7 @@ def resolve_kotlin_import_all(
# Try matching the package path as a directory structure
if len(parts) > 1:
dir_suffix = "/".join(parts[:-1])
- for p in ctx.path_set:
+ for p in ctx.sorted_paths:
if (p.endswith(".kt") or p.endswith(".java")) and dir_suffix in p:
stem = PurePosixPath(p).stem
if stem.lower() == local.lower():
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/luau.py b/packages/core/src/repowise/core/ingestion/resolvers/luau.py
index de6ce8dd7..fe2683e5a 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/luau.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/luau.py
@@ -7,16 +7,16 @@ Luau's ``require(...)`` accepts four kinds of argument:
2. Relative instance paths — ``require(script.Parent.Foo)``,
``require(script.Foo)``, or the Rojo-safe variant
``require(script.Parent:WaitForChild("Foo"))``.
-3. Absolute Roblox instance paths — ``require(game.ReplicatedStorage.Foo)``,
- where the leading service is resolved against a Rojo project's ``tree``
- mapping in ``default.project.json``.
+3. Absolute Roblox instance paths — ``require(game.ReplicatedStorage.Foo)``
+ (also the ``game:GetService("ReplicatedStorage")`` idiom), resolved
+ against a Rojo project's ``tree`` mapping in ``default.project.json``.
4. ``.luaurc``-aliased requires — ``require("@dep")``, resolved by reading
- ``.luaurc`` files along the directory hierarchy for an ``aliases`` map.
+ ``.luaurc`` files along the directory hierarchy for an ``aliases`` map
+ (nearest declaration wins, child overrides parent).
-This resolver handles (1) and (2). (3) requires a Rojo ``default.project.json``
-reader layered in via ``core/ingestion/dynamic_hints/rojo.py``; (4) requires a
-``.luaurc`` reader analogous to the tsconfig resolver. Both are deferred to
-follow-ups — see the xfail tests in ``test_luau_resolver.py``.
+All four are handled here; (3) and (4) via the readers in
+:mod:`.luau_config`. Repos without a ``default.project.json`` /
+``.luaurc`` keep the external-node fallback.
Unresolved paths are intentionally *not* silently matched by filename — a
wrong edge is worse than no edge when the downstream graph feeds docs and
@@ -47,6 +47,11 @@ _SCRIPT_RELATIVE = re.compile(r"^\s*script\s*((?:\.\s*\w+\s*)+)\s*$")
# `game.<Service>.<Path>...` — capture the service and the remainder.
_GAME_ABSOLUTE = re.compile(r"^\s*game\s*\.\s*(\w+)\s*((?:\.\s*\w+\s*)*)$")
+# `game:GetService("ReplicatedStorage")` — semantically identical to
+# `game.ReplicatedStorage` for module lookup; normalized to the dot form so
+# one regex handles both.
+_GET_SERVICE_CALL = re.compile(r'^(\s*game)\s*:\s*GetService\s*\(\s*["\'](\w+)["\']\s*\)')
+
# Roblox name-lookup method calls: `:WaitForChild("Foo")` / `:FindFirstChild("Foo")`.
# These are the race-safe idioms actual Rojo code uses in place of the bare
# `.Foo` field access — on OSRPS they account for ~93% of all `require(...)`
@@ -71,6 +76,7 @@ def _normalize_instance_methods(arg: str) -> str:
front keeps a single regex for both shapes and avoids duplicating the
path-walking logic in ``_resolve_script_relative``.
"""
+ arg = _GET_SERVICE_CALL.sub(lambda m: f"{m.group(1)}.{m.group(2)}", arg)
return _INSTANCE_METHOD_CALL.sub(lambda m: f".{m.group(1)}", arg)
@@ -103,14 +109,30 @@ def resolve_luau_import(
return resolved
return ctx.add_external_node(raw)
- # Absolute instance path: game.<Service>.Path...
- # Full Rojo-tree resolution is deferred to the Rojo follow-up; fall through
- # to an external node so the graph still records the reference.
- if _GAME_ABSOLUTE.match(arg):
+ # Absolute instance path: game.<Service>.Path... — resolved through the
+ # Rojo project tree (default.project.json). No project file (or an
+ # unmapped instance path) falls through to an external node so the
+ # graph still records the reference.
+ gm = _GAME_ABSOLUTE.match(arg)
+ if gm:
+ from .luau_config import resolve_game_path
+
+ segments = [gm.group(1)] + [
+ p.strip() for p in gm.group(2).split(".") if p.strip()
+ ]
+ resolved = resolve_game_path(segments, ctx)
+ if resolved is not None:
+ return resolved
return ctx.add_external_node(raw)
- # `.luaurc` alias: require("@dep"). Needs a luaurc reader; deferred.
+ # `.luaurc` alias: require("@dep/...") — nearest .luaurc declaring the
+ # alias wins, child overrides parent.
if raw.startswith("@"):
+ from .luau_config import resolve_luaurc_alias
+
+ resolved = resolve_luaurc_alias(raw, importer_path, ctx)
+ if resolved is not None:
+ return resolved
return ctx.add_external_node(raw)
# Everything else is a string-literal path. The parser has already
@@ -171,6 +193,14 @@ def _resolve_script_relative(
remainder = parts[i:]
if not remainder:
+ # Bare ``require(script.Parent)`` — the container itself is the
+ # module. Rojo: a directory holding ``init.luau``/``init.lua`` IS
+ # that module instance, and its children (e.g. ``init.spec.lua``)
+ # require it this way.
+ for suffix in _LUAU_SUFFIXES:
+ candidate = (here / f"init{suffix}").as_posix()
+ if candidate in ctx.path_set and candidate != importer_path:
+ return candidate
return None
base = here
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/luau_config.py b/packages/core/src/repowise/core/ingestion/resolvers/luau_config.py
new file mode 100644
index 000000000..c84541e69
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/luau_config.py
@@ -0,0 +1,241 @@
+"""Rojo project-tree and ``.luaurc`` alias readers for Luau resolution.
+
+Rojo (``default.project.json``) maps the Roblox instance tree onto the
+filesystem::
+
+ {
+ "name": "MyGame",
+ "tree": {
+ "$className": "DataModel",
+ "ReplicatedStorage": {
+ "Shared": { "$path": "src/shared" }
+ },
+ "ServerScriptService": { "$path": "src/server" }
+ }
+ }
+
+so ``require(game.ReplicatedStorage.Shared.Util)`` resolves by finding the
+longest instance-path prefix with a ``$path`` (``ReplicatedStorage.Shared``
+→ ``src/shared``) and descending the remaining segments on disk.
+
+``.luaurc`` declares require aliases::
+
+ { "aliases": { "dep": "./dependency" } }
+
+``require("@dep/foo")`` resolves against the ``aliases`` map of the nearest
+``.luaurc`` walking UP from the importer; a child directory's ``.luaurc``
+overrides parent aliases per key. Alias targets are relative to the
+directory of the ``.luaurc`` that declares them.
+
+Both indexes are built once per resolver run and cached on the context.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from pathlib import Path, PurePosixPath
+from typing import TYPE_CHECKING
+
+import structlog
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+log = structlog.get_logger(__name__)
+
+_LUAU_SUFFIXES: tuple[str, ...] = (".luau", ".lua")
+
+# // and /* */ comments are legal in .luaurc (and common in the wild).
+_LINE_COMMENT_RE = re.compile(r"^\s*//.*$", re.MULTILINE)
+_BLOCK_COMMENT_RE = re.compile(r"/\*.*?\*/", re.DOTALL)
+
+
+# ---------------------------------------------------------------------------
+# Rojo
+# ---------------------------------------------------------------------------
+
+
+def _walk_rojo_tree(node: dict, prefix: tuple[str, ...], out: dict[tuple[str, ...], str]) -> None:
+ """Collect ``instance path → $path`` mappings from a Rojo tree node."""
+ path = node.get("$path")
+ if isinstance(path, str):
+ out[prefix] = path.strip("./")
+ for key, child in node.items():
+ if key.startswith("$") or not isinstance(child, dict):
+ continue
+ _walk_rojo_tree(child, (*prefix, key), out)
+
+
+def build_rojo_index(repo_path: Path | None) -> dict[tuple[str, ...], str]:
+ """Parse ``default.project.json`` at the repo root into an instance map.
+
+ Keys are instance-path tuples relative to ``game`` (the DataModel),
+ values are repo-relative directory (or file) paths.
+ """
+ if repo_path is None:
+ return {}
+ project_file = repo_path / "default.project.json"
+ if not project_file.is_file():
+ return {}
+ try:
+ data = json.loads(project_file.read_text(encoding="utf-8", errors="ignore"))
+ except (OSError, json.JSONDecodeError):
+ return {}
+ tree = data.get("tree")
+ if not isinstance(tree, dict):
+ return {}
+ out: dict[tuple[str, ...], str] = {}
+ _walk_rojo_tree(tree, (), out)
+ return out
+
+
+def get_or_build_rojo_index(ctx: ResolverContext) -> dict[tuple[str, ...], str]:
+ cached = getattr(ctx, "_rojo_index", None)
+ if cached is not None:
+ return cached
+ index = build_rojo_index(ctx.repo_path)
+ ctx._rojo_index = index # type: ignore[attr-defined]
+ return index
+
+
+def resolve_game_path(segments: list[str], ctx: ResolverContext) -> str | None:
+ """Resolve ``game.<Service>.…`` instance segments through the Rojo tree.
+
+ *segments* excludes the leading ``game``. Longest declared instance
+ prefix wins; remaining segments descend on the filesystem; the
+ terminal segment is a ``<name>.luau``/``.lua`` file or a directory
+ with ``init.luau``/``init.lua``.
+ """
+ index = get_or_build_rojo_index(ctx)
+ if not index:
+ return None
+
+ for cut in range(len(segments), 0, -1):
+ prefix = tuple(segments[:cut])
+ base = index.get(prefix)
+ if base is None:
+ continue
+ remainder = segments[cut:]
+ if not remainder:
+ # The require names the mapped instance itself.
+ if base in ctx.path_set:
+ return base
+ for suffix in _LUAU_SUFFIXES:
+ candidate = f"{base}/init{suffix}"
+ if candidate in ctx.path_set:
+ return candidate
+ return None
+ dir_path = PurePosixPath(base)
+ for seg in remainder[:-1]:
+ dir_path = dir_path / seg
+ name = remainder[-1]
+ for suffix in _LUAU_SUFFIXES:
+ candidate = (dir_path / f"{name}{suffix}").as_posix()
+ if candidate in ctx.path_set:
+ return candidate
+ for suffix in _LUAU_SUFFIXES:
+ candidate = (dir_path / name / f"init{suffix}").as_posix()
+ if candidate in ctx.path_set:
+ return candidate
+ return None
+ return None
+
+
+# ---------------------------------------------------------------------------
+# .luaurc aliases
+# ---------------------------------------------------------------------------
+
+
+def _read_luaurc(path: Path) -> dict[str, str]:
+ """Read one ``.luaurc``'s ``aliases`` map (comment-tolerant JSON)."""
+ try:
+ text = path.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ return {}
+ text = _BLOCK_COMMENT_RE.sub("", _LINE_COMMENT_RE.sub("", text))
+ try:
+ data = json.loads(text)
+ except json.JSONDecodeError:
+ return {}
+ aliases = data.get("aliases")
+ if not isinstance(aliases, dict):
+ return {}
+ return {str(k): str(v) for k, v in aliases.items() if isinstance(v, str)}
+
+
+def get_or_build_luaurc_cache(ctx: ResolverContext) -> dict[str, dict[str, str]]:
+ """Per-directory cache of parsed ``.luaurc`` alias maps (lazy)."""
+ cached = getattr(ctx, "_luaurc_cache", None)
+ if cached is None:
+ cached = {}
+ ctx._luaurc_cache = cached # type: ignore[attr-defined]
+ return cached
+
+
+def resolve_luaurc_alias(alias_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
+ """Resolve ``@alias[/sub/path]`` via ``.luaurc`` files above the importer.
+
+ The nearest ``.luaurc`` declaring the alias wins (child overrides
+ parent); the alias target is relative to that ``.luaurc``'s directory.
+ """
+ if ctx.repo_path is None or not alias_path.startswith("@"):
+ return None
+ body = alias_path[1:]
+ if not body:
+ return None
+ alias, _, rest = body.partition("/")
+
+ cache = get_or_build_luaurc_cache(ctx)
+ repo = ctx.repo_path
+
+ # Walk from the importer's directory up to the repo root.
+ cur = PurePosixPath(importer_path).parent
+ dirs: list[str] = []
+ while True:
+ dirs.append(cur.as_posix())
+ if cur.as_posix() in (".", "/"):
+ break
+ parent = cur.parent
+ if parent == cur:
+ break
+ cur = parent
+
+ for d in dirs:
+ key = d if d != "." else ""
+ if key not in cache:
+ luaurc = (repo / d / ".luaurc") if key else (repo / ".luaurc")
+ cache[key] = _read_luaurc(luaurc) if luaurc.is_file() else {}
+ target = cache[key].get(alias)
+ if target is None:
+ continue
+ base_dir = PurePosixPath(key) if key else PurePosixPath(".")
+ combined = base_dir / target.lstrip("./") if not target.startswith("/") else PurePosixPath(target.lstrip("/"))
+ if rest:
+ combined = combined / rest
+ normalized = PurePosixPath(*(
+ seg for seg in combined.as_posix().split("/") if seg not in (".", "")
+ ))
+ # Resolve ".." segments textually (paths are repo-relative posix).
+ parts: list[str] = []
+ for seg in normalized.parts:
+ if seg == "..":
+ if parts:
+ parts.pop()
+ else:
+ parts.append(seg)
+ candidate_base = "/".join(parts)
+ if candidate_base in ctx.path_set:
+ return candidate_base
+ for suffix in _LUAU_SUFFIXES:
+ candidate = f"{candidate_base}{suffix}"
+ if candidate in ctx.path_set:
+ return candidate
+ for suffix in _LUAU_SUFFIXES:
+ candidate = f"{candidate_base}/init{suffix}"
+ if candidate in ctx.path_set:
+ return candidate
+ # The nearest declaration of the alias decides — a parent's same
+ # alias must not silently shadow a broken child mapping.
+ return None
+ return None
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/module_name_index.py b/packages/core/src/repowise/core/ingestion/resolvers/module_name_index.py
new file mode 100644
index 000000000..f7611887c
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/module_name_index.py
@@ -0,0 +1,108 @@
+"""Shared declared-module-name index for lightweight (regex-tier) resolvers.
+
+Languages whose import statements name *modules* rather than files
+(Elixir ``alias Foo.Bar``, Clojure ``(:require [foo.bar])``, Haskell
+``import Foo.Bar``, Erlang ``mod:fun()``) resolve through one uniform
+mechanism: a map from declared module name → defining file(s), built once
+per build from
+
+1. a single declaration regex over every file of the language
+ (``defmodule Foo.Bar`` / ``(ns foo.bar)`` / ``module Foo.Bar where`` /
+ ``-module(foo)``), plus
+2. an optional path-convention inverse (``lib/foo/bar.ex`` → ``Foo.Bar``)
+ as a fallback for files whose head carries no declaration.
+
+The index is cached on the :class:`~.context.ResolverContext` via the
+same ``getattr``/``setattr`` idiom every other lazy per-language index
+uses, and iterates ``ctx.sorted_paths`` so its first-match behaviour is
+deterministic.
+"""
+
+from __future__ import annotations
+
+import re
+from collections.abc import Callable
+from typing import TYPE_CHECKING
+
+import structlog
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+log = structlog.get_logger(__name__)
+
+# Declarations live near the top of a file in every supported convention;
+# capping the read keeps the index build linear in file *count*, not size.
+_HEAD_BYTES = 65536
+
+
+def get_or_build_module_index(
+ ctx: ResolverContext,
+ *,
+ cache_attr: str,
+ extensions: tuple[str, ...],
+ declaration_re: re.Pattern[str],
+ path_to_module: Callable[[str], str | None] | None = None,
+) -> dict[str, list[str]]:
+ """Return (building on first call) ``{module_name: [paths…]}`` for one language.
+
+ ``declaration_re`` must carry exactly one capture group (the declared
+ name) and is applied with ``findall`` to the head of each file whose
+ suffix is in ``extensions``. ``path_to_module`` supplies the
+ path-convention inverse for files with no declaration.
+ """
+ cached = getattr(ctx, cache_attr, None)
+ if cached is not None:
+ return cached
+
+ index: dict[str, list[str]] = {}
+ repo = ctx.repo_path
+ for path in ctx.sorted_paths:
+ if not path.endswith(extensions):
+ continue
+ declared: list[str] = []
+ if repo is not None:
+ try:
+ with open(repo / path, encoding="utf-8", errors="replace") as f:
+ head = f.read(_HEAD_BYTES)
+ declared = declaration_re.findall(head)
+ except OSError:
+ declared = []
+ if not declared and path_to_module is not None:
+ inverse = path_to_module(path)
+ if inverse:
+ declared = [inverse]
+ for name in declared:
+ index.setdefault(name, []).append(path)
+
+ setattr(ctx, cache_attr, index)
+ log.debug("module name index built", cache=cache_attr, modules=len(index))
+ return index
+
+
+def lookup_module(index: dict[str, list[str]], name: str) -> str | None:
+ """Deterministic single-file lookup: first path in sorted insertion order."""
+ paths = index.get(name)
+ return paths[0] if paths else None
+
+
+def lookup_with_trailing_strip(
+ index: dict[str, list[str]], name: str, *, separator: str = "."
+) -> str | None:
+ """Look up *name*, progressively dropping trailing segments.
+
+ Covers imports of nested modules whose own segment never appears in a
+ file head (``Foo.Bar.Baz`` declared inside ``foo/bar.ex``) — the same
+ shape as the JVM member-import stripping. Only exact index keys hit;
+ a single remaining segment is still allowed (top-level single-segment
+ modules are the norm in Elixir libraries).
+ """
+ candidate = name
+ while candidate:
+ hit = lookup_module(index, candidate)
+ if hit:
+ return hit
+ if separator not in candidate:
+ return None
+ candidate = candidate.rsplit(separator, 1)[0]
+ return None
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/php.py b/packages/core/src/repowise/core/ingestion/resolvers/php.py
index 531e77bc6..c321f594c 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/php.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/php.py
@@ -2,12 +2,30 @@
from __future__ import annotations
+import posixpath
+
from .context import ResolverContext
from .php_composer import resolve_via_psr4
def resolve_php_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
- """Resolve a PHP use declaration to a repo-relative file path."""
+ """Resolve a PHP use declaration or require/include to a repo-relative path."""
+ # File-based require/include: ``require 'lib/helpers.php'`` /
+ # ``require __DIR__ . '/inc/db.php'`` (the captured literal keeps the
+ # leading slash from the concatenation — importer-relative either way).
+ # Probe importer-relative first, then repo-root-relative; no fuzzy
+ # fallback — a literal path that matches nothing is external.
+ if module_path.endswith(".php"):
+ literal = module_path.replace("\\", "/").lstrip("/")
+ importer_dir = posixpath.dirname(importer_path)
+ candidate = posixpath.normpath(posixpath.join(importer_dir, literal))
+ if candidate in ctx.path_set:
+ return candidate
+ root_candidate = posixpath.normpath(literal)
+ if root_candidate in ctx.path_set:
+ return root_candidate
+ return ctx.add_external_node(module_path)
+
# composer.json autoload.psr-4 is the authoritative mapping in real
# Laravel/Symfony/etc. apps; consult before stem fallback so non-conventional
# prefix maps (``"App\\": "src/"``) resolve correctly.
@@ -27,7 +45,7 @@ def resolve_php_import(module_path: str, importer_path: str, ctx: ResolverContex
# Try PSR-4 style: namespace path maps to directory
php_name = f"{local}.php"
- for p in ctx.path_set:
+ for p in ctx.sorted_paths:
if p.endswith(php_name):
return p
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/php_composer.py b/packages/core/src/repowise/core/ingestion/resolvers/php_composer.py
index e6bc8e244..c1278c1be 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/php_composer.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/php_composer.py
@@ -89,7 +89,7 @@ def resolve_via_psr4(module_path: str, ctx: "ResolverContext") -> str | None:
# Also tolerate paths whose first segment differs (some repos vendor
# the root differently). Probe by suffix as a forgiving fallback.
suffix_probe = f"/{candidate}"
- for p in ctx.path_set:
+ for p in ctx.sorted_paths:
if p == candidate or p.endswith(suffix_probe):
return p
return None
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ruby.py b/packages/core/src/repowise/core/ingestion/resolvers/ruby.py
index f7312ab1a..d694aa438 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/ruby.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/ruby.py
@@ -1,11 +1,121 @@
-"""Ruby import resolution."""
+"""Ruby import resolution.
+
+Resolution order, highest fidelity first:
+
+1. ``require_relative`` / dot-leading paths — importer-relative join.
+2. ``$LOAD_PATH`` convention probes — a gem puts ``lib/`` on the load
+ path, so ``require 'sinatra/base'`` from anywhere in the repo means
+ ``lib/sinatra/base.rb``; plain repo-root joins cover script-style
+ layouts.
+3. Stem lookup / suffix matching (legacy fuzzy fallbacks).
+4. Rails / Zeitwerk autoload roots.
+5. External: requires matching a Gemfile/gemspec dependency become a
+ clearly-labelled gem node (``external:gem:<name>``); everything else
+ keeps the plain external node.
+"""
from __future__ import annotations
+import re
from pathlib import PurePosixPath
from .context import ResolverContext
+# Gemfile: gem 'rack', '~> 3.0'
+_GEMFILE_GEM_RE = re.compile(r"^\s*gem\s+[\"']([A-Za-z0-9_.-]+)[\"']", re.MULTILINE)
+# gemspec: spec.add_dependency 'rack' / add_runtime_dependency / add_development_dependency
+_GEMSPEC_DEP_RE = re.compile(
+ r"\.add_(?:runtime_|development_)?dependency\s*\(?\s*[\"']([A-Za-z0-9_.-]+)[\"']"
+)
+
+# Ruby standard library require names (default + bundled gems shipping with
+# the interpreter). Requires of these produce no node at all — same policy
+# as the JDK namespaces for Java. First path segment is matched, so
+# ``net/http`` and ``io/console`` are covered by their roots.
+_RUBY_STDLIB = frozenset({
+ "abbrev", "base64", "benchmark", "bigdecimal", "cgi", "coverage", "csv",
+ "date", "delegate", "digest", "drb", "English", "english", "erb", "etc",
+ "fcntl", "fiddle", "fileutils", "find", "forwardable", "getoptlong",
+ "io", "ipaddr", "irb", "json", "logger", "minitest", "monitor", "mutex_m",
+ "net", "nkf", "objspace", "observer", "open-uri", "open3", "openssl",
+ "optparse", "ostruct", "pathname", "pp", "prettyprint", "prime", "pstore",
+ "psych", "pty", "racc", "rake", "rbconfig", "rdoc", "readline", "resolv",
+ "rexml", "rinda", "ripper", "rss", "rubygems", "securerandom", "set",
+ "shellwords", "singleton", "socket", "stringio", "strscan", "syslog",
+ "tempfile", "test", "time", "timeout", "tmpdir", "tsort", "un", "uri",
+ "weakref", "yaml", "zlib",
+})
+
+
+def is_ruby_stdlib(module_path: str) -> bool:
+ """True when the require names a Ruby standard-library module."""
+ head = module_path.split("/", 1)[0]
+ return head in _RUBY_STDLIB
+
+
+def _scan_gem_metadata(ctx: ResolverContext) -> tuple[frozenset[str], tuple[str, ...]]:
+ """Scan every Gemfile + *.gemspec once: dependency names + lib roots.
+
+ Monorepos (sinatra: rack-protection/, sinatra-contrib/) declare each
+ sub-gem's dependencies in its own gemspec — the walk covers them all.
+ Every gemspec's directory contributes a ``<dir>/lib`` load-path root,
+ exactly as ``gem build``/bundler put it on ``$LOAD_PATH``.
+ """
+ cached = getattr(ctx, "_ruby_gem_meta", None)
+ if cached is not None:
+ return cached
+ names: set[str] = set()
+ lib_roots: set[str] = set()
+ if ctx.repo_path is not None:
+ from repowise.core.fs_walk import iter_glob
+
+ repo = ctx.repo_path.resolve()
+ candidates: list = []
+ try:
+ candidates.extend(
+ iter_glob(ctx.repo_path, "Gemfile", prune_nested_git=ctx.prune_nested_git)
+ )
+ candidates.extend(
+ iter_glob(ctx.repo_path, "*.gemspec", prune_nested_git=ctx.prune_nested_git)
+ )
+ except OSError:
+ pass
+ for f in sorted(candidates):
+ if not f.is_file():
+ continue
+ try:
+ text = f.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ names.update(_GEMFILE_GEM_RE.findall(text))
+ names.update(_GEMSPEC_DEP_RE.findall(text))
+ if f.name.endswith(".gemspec"):
+ try:
+ rel_dir = f.parent.resolve().relative_to(repo).as_posix()
+ except (OSError, ValueError):
+ continue
+ lib_roots.add("lib" if rel_dir == "." else f"{rel_dir}/lib")
+ result = (frozenset(names), tuple(sorted(lib_roots)))
+ ctx._ruby_gem_meta = result # type: ignore[attr-defined]
+ return result
+
+
+def _get_or_build_gem_names(ctx: ResolverContext) -> frozenset[str]:
+ return _scan_gem_metadata(ctx)[0]
+
+
+def _is_declared_gem(module_path: str, ctx: ResolverContext) -> bool:
+ """True when the require names a Gemfile/gemspec dependency.
+
+ ``require 'rack/protection'`` matches either the first path segment
+ (gem ``rack``) or the dash-joined full path (gem ``rack-protection``).
+ """
+ gems = _get_or_build_gem_names(ctx)
+ if not gems:
+ return False
+ head = module_path.split("/", 1)[0]
+ return head in gems or module_path.replace("/", "-") in gems
+
def resolve_ruby_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
"""Resolve a Ruby require/require_relative to a repo-relative file path."""
@@ -19,6 +129,27 @@ def resolve_ruby_import(module_path: str, importer_path: str, ctx: ResolverConte
if full in ctx.path_set:
return full
+ # $LOAD_PATH convention: gems put lib/ on the path, so a plain
+ # ``require 'sinatra/base'`` from ANY file in the repo means
+ # ``lib/sinatra/base.rb``. Probe before any fuzzy fallback — these
+ # joins are exact.
+ if not module_path.startswith("."):
+ # Repo-root lib/ + every sub-gem's lib/ (gemspec dirs) + root join.
+ _gems, lib_roots = _scan_gem_metadata(ctx)
+ bases = dict.fromkeys(("lib", *lib_roots, ""))
+ for base in bases:
+ candidate = f"{base}/{module_path}.rb" if base else f"{module_path}.rb"
+ if candidate in ctx.path_set:
+ return candidate
+
+ # Standard-library requires produce no node — same policy as the JDK
+ # namespace filter for Java. The exact probes above get first refusal
+ # (the repo may BE the json gem), but stdlib names never reach the
+ # fuzzy stem/suffix fallbacks where `require 'time'` would happily
+ # false-match any time.rb in the repo.
+ if not module_path.startswith(".") and is_ruby_stdlib(module_path):
+ return None
+
# Try stem lookup
stem = PurePosixPath(module_path).stem.lower().replace("-", "_")
result = ctx.stem_lookup(stem)
@@ -27,7 +158,7 @@ def resolve_ruby_import(module_path: str, importer_path: str, ctx: ResolverConte
# Try matching the path directly
rb_name = f"{module_path}.rb"
- for p in ctx.path_set:
+ for p in ctx.sorted_paths:
if p.endswith(rb_name) or PurePosixPath(p).name == PurePosixPath(rb_name).name:
return p
@@ -52,4 +183,9 @@ def resolve_ruby_import(module_path: str, importer_path: str, ctx: ResolverConte
if hit:
return hit
+ # External: a require that matches a declared Gemfile/gemspec
+ # dependency is a gem, labelled so the graph (and any reader of it)
+ # can tell library dependencies from genuinely unresolved requires.
+ if _is_declared_gem(module_path, ctx):
+ return ctx.add_external_node(f"gem:{module_path}")
return ctx.add_external_node(module_path)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/rust.py b/packages/core/src/repowise/core/ingestion/resolvers/rust.py
index 8ba1d9b46..f2f53a8a6 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/rust.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/rust.py
@@ -29,8 +29,18 @@ def _get_frozen_parsed_keys(ctx: ResolverContext) -> frozenset[str]:
return frozen
-def resolve_rust_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
- """Resolve a Rust ``use`` path to a repo-relative file."""
+def resolve_rust_import(
+ module_path: str,
+ importer_path: str,
+ ctx: ResolverContext,
+ *,
+ _reexport_depth: int = 0,
+) -> str | None:
+ """Resolve a Rust ``use`` path to a repo-relative file.
+
+ ``_reexport_depth`` caps ``pub use`` hop-following at one level —
+ re-export cycles between crate roots must not recurse.
+ """
# Strip `as <alias>` suffix from aliased imports (e.g. "typst_syntax as syntax")
if " as " in module_path:
module_path = module_path.split(" as ")[0].strip()
@@ -59,7 +69,13 @@ def resolve_rust_import(module_path: str, importer_path: str, ctx: ResolverConte
# --- crate:: — resolve from the crate root ---
if prefix == "crate":
crate_root = _find_rust_crate_root(importer_path, ctx)
- return _probe_rust_path(crate_root, parts[1:], frozen_path_set)
+ resolved = _probe_rust_path(crate_root, parts[1:], frozen_path_set)
+ if resolved is None and _reexport_depth == 0:
+ # `use crate::Type` where lib.rs re-exports Type (the prelude
+ # pattern `pub use crate::module::Type`) — follow one hop
+ # through the crate root's re-exports.
+ resolved = _follow_crate_root_reexport(crate_root, parts[1:], ctx)
+ return resolved
# --- self:: — resolve from the current module's directory ---
if prefix == "self":
@@ -113,6 +129,11 @@ def resolve_rust_import(module_path: str, importer_path: str, ctx: ResolverConte
sibling_src = ws_index.lookup(prefix)
if sibling_src is not None and sibling_src != crate_root:
resolved = _probe_rust_path(sibling_src, parts[1:], frozen_path_set)
+ if resolved is None and _reexport_depth == 0:
+ # `use crate_x::ReexportedName`: the name is no module file —
+ # follow one hop through the sibling crate root's `pub use`
+ # re-exports to the defining module.
+ resolved = _follow_crate_root_reexport(sibling_src, parts[1:], ctx)
if resolved is None:
# Probe the crate root itself (lib.rs / main.rs) when the
# import has no further path segments.
@@ -127,6 +148,58 @@ def resolve_rust_import(module_path: str, importer_path: str, ctx: ResolverConte
return ctx.add_external_node(module_path)
+def _follow_crate_root_reexport(
+ crate_src_dir: str, remaining_parts: list[str], ctx: ResolverContext
+) -> str | None:
+ """Follow ONE ``pub use`` hop through a crate root's re-exports.
+
+ ``lib.rs`` saying ``pub use crate::module::Type`` makes
+ ``use crate_x::Type`` (and within-crate ``use crate::Type``) legal —
+ but ``Type`` is no module file, so path probing fails. Match the
+ first unresolved segment against the crate root's re-exported names
+ and resolve that ``pub use``'s own module path instead. Depth is
+ capped at one hop: a chain of re-exporting hubs resolves to the next
+ hub, whose own ``pub use`` edges keep the graph connected.
+ """
+ if not remaining_parts:
+ return None
+ parsed_files = ctx.parsed_files or {}
+ root_path = None
+ for root_file in ("lib.rs", "main.rs"):
+ candidate = f"{crate_src_dir}/{root_file}" if crate_src_dir not in (".", "") else root_file
+ if candidate in parsed_files:
+ root_path = candidate
+ break
+ if root_path is None:
+ return None
+
+ name = remaining_parts[0]
+ for imp in getattr(parsed_files[root_path], "imports", []) or []:
+ if not getattr(imp, "is_reexport", False):
+ continue
+ mp = imp.module_path.split(" as ")[0].strip()
+ segments = mp.split("::")
+ last = segments[-1]
+ names = list(getattr(imp, "imported_names", []) or [])
+ if last.startswith("{"):
+ # Brace group: `pub use crate::module::{A, B}` — the extractor
+ # carries the selected names.
+ if name not in names:
+ continue
+ target_mp = "::".join([*segments[:-1], name])
+ elif last == "*":
+ # Glob re-export: `pub use crate::module::*` — resolve the module.
+ target_mp = "::".join(segments[:-1])
+ elif last == name or name in names:
+ target_mp = mp
+ else:
+ continue
+ resolved = resolve_rust_import(target_mp, root_path, ctx, _reexport_depth=1)
+ if resolved is not None and not resolved.startswith("external:"):
+ return resolved
+ return None
+
+
@lru_cache(maxsize=4096)
def _find_rust_crate_root_cached(
importer_path: str, parsed_file_keys: frozenset[str]
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/scala.py b/packages/core/src/repowise/core/ingestion/resolvers/scala.py
index ab426538c..a521ba8fd 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/scala.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/scala.py
@@ -1,38 +1,104 @@
-"""Scala import resolution."""
+"""Scala import resolution with JVM workspace awareness.
+
+Resolves Scala imports through the shared :class:`JvmWorkspaceIndex`
+(package → files, FQN lookup, wildcard expansion — the same surface the
+Java and Kotlin resolvers use, including cross-language Scala ↔ Java
+resolution), with the sbt/Mill project index as a fallback for layouts
+the package scan misses.
+
+Handles:
+- ``import com.foo.Bar`` → file(s) defining ``Bar`` in package ``com.foo``
+- ``import com.foo._``/``.*`` → all files in package ``com.foo``
+- ``import com.foo`` → package fan-out (Scala allows package imports)
+- ``scala.`` / JDK namespaces → no edge (stdlib)
+
+Brace imports and renames (``{A, B => C}``) are expanded into separate
+single-name imports at extraction time, so they arrive here as plain
+dotted paths. Implicits/givens resolution is out of scope for static
+analysis — ``ScalaDynamicHints`` marks implicit/given declarations so
+implicit-heavy files keep a liveness signal.
+"""
from __future__ import annotations
-from .context import ResolverContext
+from typing import TYPE_CHECKING
+
+from .jvm_workspace import get_or_build_jvm_index
from .scala_build import resolve_via_scala_index
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+_SCALA_STDLIB_PREFIXES = ("scala.", "java.", "javax.", "jdk.")
+
+
+def resolve_scala_import(
+ module_path: str, importer_path: str, ctx: ResolverContext
+) -> str | None:
+ """Resolve a Scala import to a single representative repo-relative file."""
+ targets = resolve_scala_import_all(module_path, importer_path, ctx)
+ return targets[0] if targets else None
+
+
+def resolve_scala_import_all(
+ module_path: str, importer_path: str, ctx: ResolverContext
+) -> tuple[str, ...]:
+ """Resolve a Scala import to all matching repo-relative file paths.
+
+ Wildcards fan out to every file in the package; package imports fan
+ out the same way (importing a package is legal Scala and a real
+ dependency on its contents).
+ """
+ if not module_path:
+ return ()
+
+ # Stdlib namespaces produce no node (segment-aware: trailing dots).
+ if module_path.startswith(_SCALA_STDLIB_PREFIXES):
+ return ()
-def resolve_scala_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
- """Resolve a Scala import to a repo-relative file path."""
parts = module_path.split(".")
local = parts[-1]
+ jvm_index = get_or_build_jvm_index(ctx)
+
+ # Wildcard: import com.foo._ / com.foo.* (extraction normalises to *)
if local in ("*", "_"):
- return None
+ pkg_fqn = ".".join(parts[:-1])
+ if not pkg_fqn:
+ return ()
+ files = jvm_index.wildcard_expand(pkg_fqn)
+ if files:
+ return files
+ return (ctx.add_external_node(module_path),)
+
+ # Exact FQN: package + top-level type (class/trait/object/case class)
+ files = jvm_index.files_for_fqn(module_path)
+ if files:
+ return files
+
+ # Package import: import com.foo.bar → depend on the package's files
+ pkg_files = jvm_index.files_for_package(module_path)
+ if pkg_files:
+ return pkg_files
- # SBT/Mill multi-project index: package → file map built from declared
- # subprojects' source roots. Consult before stem matching so cross-project
- # imports resolve correctly in monorepos.
+ # sbt/Mill project index (source-root aware) — catches layouts whose
+ # package declarations the workspace scan missed.
build_match = resolve_via_scala_index(module_path, ctx)
if build_match is not None:
- return build_match
+ return (build_match,)
- # Try stem lookup on the last name component
+ # Stem lookup on the type/object name
result = ctx.stem_lookup(local.lower())
if result and result.endswith(".scala"):
- return result
+ return (result,)
- # Try matching package path as directory structure
+ # Package path as directory structure
if len(parts) > 1:
dir_suffix = "/".join(parts[:-1])
- for p in ctx.path_set:
+ for p in ctx.sorted_paths:
if p.endswith(".scala") and dir_suffix.lower() in p.lower():
stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0]
if stem.lower() == local.lower():
- return p
+ return (p,)
- return ctx.add_external_node(module_path)
+ return (ctx.add_external_node(module_path),)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/swift.py b/packages/core/src/repowise/core/ingestion/resolvers/swift.py
index bc3be08f2..873befdb4 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/swift.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/swift.py
@@ -25,7 +25,7 @@ def resolve_swift_import(module_path: str, importer_path: str, ctx: ResolverCont
return result
# Look for directory matching module name
- for p in ctx.path_set:
+ for p in ctx.sorted_paths:
if p.endswith(".swift"):
parent_name = PurePosixPath(p).parent.name.lower()
if parent_name == module_path.lower():
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/swift_spm.py b/packages/core/src/repowise/core/ingestion/resolvers/swift_spm.py
index debc87c53..fe8b4dc5b 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/swift_spm.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/swift_spm.py
@@ -108,7 +108,7 @@ def resolve_via_swift_targets(module_path: str, ctx: "ResolverContext") -> str |
return None
# Pick any .swift file under that dir; prefer one whose stem matches.
target_prefix = target_dir.rstrip("/") + "/"
- matches = [p for p in ctx.path_set if p.endswith(".swift") and p.startswith(target_prefix)]
+ matches = [p for p in ctx.sorted_paths if p.endswith(".swift") and p.startswith(target_prefix)]
if not matches:
# Module imported by name but no source files indexed yet (target may
# be excluded). Treat as unresolved; caller falls back further.
diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.py
index e28de904c..fcc4d5445 100644
--- a/packages/core/src/repowise/core/ingestion/traverser.py
+++ b/packages/core/src/repowise/core/ingestion/traverser.py
@@ -150,13 +150,19 @@ _MANIFEST_FILES: frozenset[str] = frozenset(
{"pyproject.toml", "package.json", "Cargo.toml", "go.mod"}
)
-# Entry-point filename stems
-_ENTRY_POINT_STEMS: frozenset[str] = frozenset(
- {"main", "index", "app", "run", "server", "start", "wsgi", "asgi"}
+# Entry-point evidence, all registry-derived: exact filenames (Main.kt,
+# config.ru), "*"-prefixed filename suffixes (OTP's <name>_app.erl), and
+# the flag-stem set. The historical
+# extra {run.py, server.py} patterns were dropped — the run/server stems
+# already cover them.
+_ENTRY_POINT_STEMS: frozenset[str] = _LANG_REGISTRY.entry_flag_stems()
+
+_ENTRY_POINT_NAMES: frozenset[str] = frozenset(
+ p for p in _LANG_REGISTRY.entry_point_names() if not p.startswith("*")
)
-_ENTRY_POINT_NAMES: frozenset[str] = _LANG_REGISTRY.entry_point_names() | frozenset(
- {"run.py", "server.py"} # extra traverser-specific patterns not in language specs
+_ENTRY_POINT_NAME_SUFFIXES: tuple[str, ...] = tuple(
+ sorted(p[1:] for p in _LANG_REGISTRY.entry_point_names() if p.startswith("*"))
)
# Default file-size limit
@@ -466,7 +472,11 @@ class FileTraverser:
is_test=_is_test_file(rel_str, filename),
is_config=_is_config_file(language),
is_api_contract=_is_api_contract(abs_path, language),
- is_entry_point=filename in _ENTRY_POINT_NAMES or _stem_is_entry_point(abs_path),
+ is_entry_point=(
+ filename in _ENTRY_POINT_NAMES
+ or filename.endswith(_ENTRY_POINT_NAME_SUFFIXES)
+ or _stem_is_entry_point(abs_path)
+ ),
)
# ------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
index b729577a1..6397580cf 100644
--- a/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
+++ b/packages/core/src/repowise/core/ingestion/type_ref_resolution.py
@@ -181,7 +181,8 @@ def _find_rust_type_file(
graph: "nx.DiGraph",
) -> str | None:
"""Find the file defining *type_name*, preferring imported files."""
- for imp_file in import_targets:
+ # Sorted: import_targets is a set; first-match must be deterministic.
+ for imp_file in sorted(import_targets):
if not graph.has_node(imp_file):
continue
for succ in graph.successors(imp_file):
@@ -266,7 +267,8 @@ def _find_go_type_file(
graph: "nx.DiGraph",
) -> str | None:
"""Return a candidate file that defines a type named *type_name*."""
- for cand in candidate_files:
+ # Sorted: set iteration; first-match must be deterministic.
+ for cand in sorted(candidate_files):
if not graph.has_node(cand):
continue
for succ in graph.successors(cand):
@@ -394,7 +396,8 @@ def _find_c_type_file(
sibling ``.cc`` declaring an internal class that another ``.cc`` in
the same target uses by value), then the global stem map.
"""
- for imp_file in import_targets:
+ # Sorted: import_targets is a set; first-match must be deterministic.
+ for imp_file in sorted(import_targets):
if not graph.has_node(imp_file):
continue
for succ in graph.successors(imp_file):
@@ -402,7 +405,8 @@ def _find_c_type_file(
if nd.get("node_type") == "symbol" and nd.get("name") == type_name:
return imp_file
- for sib in sibling_files:
+ # Sorted: set iteration; first-match must be deterministic.
+ for sib in sorted(sibling_files):
if sib == from_path or not graph.has_node(sib):
continue
for succ in graph.successors(sib):
@@ -620,7 +624,8 @@ def _find_jvm_type_file(
graph: "nx.DiGraph",
) -> str | None:
"""Return a candidate file that defines a top-level type named *type_name*."""
- for cand in candidate_files:
+ # Sorted: set iteration; first-match must be deterministic.
+ for cand in sorted(candidate_files):
if not graph.has_node(cand):
continue
for succ in graph.successors(cand):
diff --git a/packages/core/src/repowise/core/persistence/__init__.py b/packages/core/src/repowise/core/persistence/__init__.py
index 365a2fb88..8fcd9e5e8 100644
--- a/packages/core/src/repowise/core/persistence/__init__.py
+++ b/packages/core/src/repowise/core/persistence/__init__.py
@@ -48,6 +48,8 @@ from .crud import (
get_graph_node,
get_graph_nodes_by_ids,
get_kg_layers,
+ get_kg_node_meta,
+ get_kg_project_meta,
get_kg_tour_steps,
get_node_degree_counts,
get_page,
@@ -80,6 +82,8 @@ from .crud import (
upsert_git_metadata,
upsert_git_metadata_bulk,
upsert_kg_layers,
+ upsert_kg_node_meta,
+ upsert_kg_project_meta,
upsert_kg_tour_steps,
upsert_page,
upsert_page_from_generated,
@@ -124,6 +128,8 @@ from .models import (
GraphMetric,
GraphNode,
KnowledgeGraphLayer,
+ KnowledgeGraphNodeMeta,
+ KnowledgeGraphProjectMeta,
KnowledgeGraphTourStep,
Page,
PageVersion,
@@ -167,6 +173,8 @@ __all__ = [
"InMemoryVectorStore",
# knowledge graph
"KnowledgeGraphLayer",
+ "KnowledgeGraphNodeMeta",
+ "KnowledgeGraphProjectMeta",
"KnowledgeGraphTourStep",
"LanceDBVectorStore",
"MockEmbedder",
@@ -227,6 +235,8 @@ __all__ = [
"get_graph_nodes_by_ids",
# knowledge graph crud
"get_kg_layers",
+ "get_kg_node_meta",
+ "get_kg_project_meta",
"get_kg_tour_steps",
"get_node_degree_counts",
"get_page",
@@ -266,6 +276,8 @@ __all__ = [
"upsert_git_metadata",
"upsert_git_metadata_bulk",
"upsert_kg_layers",
+ "upsert_kg_node_meta",
+ "upsert_kg_project_meta",
"upsert_kg_tour_steps",
"upsert_page",
"upsert_page_from_generated",
diff --git a/packages/core/src/repowise/core/persistence/crud/knowledge_graph.py b/packages/core/src/repowise/core/persistence/crud/knowledge_graph.py
index 4c3562d78..37dd5191b 100644
--- a/packages/core/src/repowise/core/persistence/crud/knowledge_graph.py
+++ b/packages/core/src/repowise/core/persistence/crud/knowledge_graph.py
@@ -13,6 +13,8 @@ from sqlalchemy.ext.asyncio import AsyncSession
from ..models import (
KnowledgeGraphLayer,
+ KnowledgeGraphNodeMeta,
+ KnowledgeGraphProjectMeta,
KnowledgeGraphTourStep,
)
@@ -35,6 +37,7 @@ async def upsert_kg_layers(session: AsyncSession, repo_id: str, layers: list[dic
description=layer.get("description", ""),
node_ids_json=json.dumps(layer.get("nodeIds", layer.get("node_ids", []))),
display_order=layer.get("display_order", i),
+ sub_groups_json=json.dumps(layer.get("subGroups", layer.get("sub_groups", []))),
)
)
await session.flush()
@@ -63,6 +66,12 @@ async def upsert_kg_tour_steps(session: AsyncSession, repo_id: str, steps: list[
title=step["title"],
description=step.get("description", ""),
node_ids_json=json.dumps(step.get("nodeIds", step.get("node_ids", []))),
+ target_path=step.get("target_path"),
+ layer_id=step.get("layer_id"),
+ reason=step.get("reason", ""),
+ depth=step.get("depth"),
+ kind=step.get("kind", ""),
+ page_type=step.get("page_type"),
)
)
await session.flush()
@@ -76,3 +85,82 @@ async def get_kg_tour_steps(session: AsyncSession, repo_id: str) -> list[Knowled
.order_by(KnowledgeGraphTourStep.step_order)
)
return list(result.scalars())
+
+
+async def upsert_kg_project_meta(
+ session: AsyncSession,
+ repo_id: str,
+ entry_points: list[str],
+ entry_candidates: list[str] | None = None,
+) -> None:
+ """Replace the project-level curated KG metadata for a repo (one row)."""
+ await session.execute(
+ delete(KnowledgeGraphProjectMeta).where(KnowledgeGraphProjectMeta.repository_id == repo_id)
+ )
+ session.add(
+ KnowledgeGraphProjectMeta(
+ repository_id=repo_id,
+ entry_points_json=json.dumps(entry_points),
+ entry_candidates_json=json.dumps(entry_candidates or []),
+ )
+ )
+ await session.flush()
+
+
+async def get_kg_project_meta(
+ session: AsyncSession, repo_id: str
+) -> KnowledgeGraphProjectMeta | None:
+ """Fetch the project-level curated KG metadata row, if any."""
+ result = await session.execute(
+ select(KnowledgeGraphProjectMeta).where(KnowledgeGraphProjectMeta.repository_id == repo_id)
+ )
+ return result.scalars().first()
+
+
+def file_node_meta_from_kg_nodes(nodes: list[dict]) -> list[dict]:
+ """Extract per-file curated metadata from exported KG ``nodes``.
+
+ Keeps only ``file:``-prefixed nodes and strips the prefix so the stored
+ ``node_id`` matches the architecture view's plain repo-relative paths.
+ Shared by the pipeline persister and the on-read file → DB migration.
+ """
+ return [
+ {
+ "node_id": node["id"].removeprefix("file:"),
+ "node_type": node.get("type", "file"),
+ "summary": node.get("summary", ""),
+ "tags": node.get("tags", []),
+ }
+ for node in nodes
+ if isinstance(node.get("id"), str) and node["id"].startswith("file:")
+ ]
+
+
+async def upsert_kg_node_meta(session: AsyncSession, repo_id: str, nodes: list[dict]) -> None:
+ """Replace all per-node curated KG metadata for a repo (delete + bulk insert).
+
+ Each *node* dict carries ``id``/``node_id``, optional ``type``/``node_type``,
+ ``summary`` and ``tags``; ids are stored verbatim (callers strip prefixes).
+ """
+ await session.execute(
+ delete(KnowledgeGraphNodeMeta).where(KnowledgeGraphNodeMeta.repository_id == repo_id)
+ )
+ for node in nodes:
+ session.add(
+ KnowledgeGraphNodeMeta(
+ repository_id=repo_id,
+ node_id=node.get("node_id", node.get("id", "")),
+ node_type=node.get("node_type", node.get("type", "file")),
+ summary=node.get("summary", ""),
+ tags_json=json.dumps(node.get("tags", [])),
+ )
+ )
+ await session.flush()
+
+
+async def get_kg_node_meta(session: AsyncSession, repo_id: str) -> list[KnowledgeGraphNodeMeta]:
+ """Fetch all per-node curated KG metadata rows for a repo."""
+ result = await session.execute(
+ select(KnowledgeGraphNodeMeta).where(KnowledgeGraphNodeMeta.repository_id == repo_id)
+ )
+ return list(result.scalars())
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 82dc01900..a73305760 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -1008,6 +1008,8 @@ class KnowledgeGraphLayer(Base):
description: Mapped[str] = mapped_column(Text, nullable=False, default="")
node_ids_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
display_order: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
+ # Curated sub-groups within the layer: [{"id", "name", "nodeIds"}].
+ sub_groups_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
)
@@ -1026,6 +1028,13 @@ class KnowledgeGraphTourStep(Base):
title: Mapped[str] = mapped_column(Text, nullable=False)
description: Mapped[str] = mapped_column(Text, nullable=False, default="")
node_ids_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
+ # Curated, layer-aware tour fields (empty/None for legacy LLM tours).
+ target_path: Mapped[str | None] = mapped_column(Text, nullable=True)
+ layer_id: Mapped[str | None] = mapped_column(Text, nullable=True)
+ reason: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ depth: Mapped[int | None] = mapped_column(Integer, nullable=True)
+ kind: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ page_type: Mapped[str | None] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), nullable=False, default=_now_utc
)
@@ -1033,6 +1042,54 @@ class KnowledgeGraphTourStep(Base):
__table_args__ = (UniqueConstraint("repository_id", "step_order", name="uq_kg_tour_step"),)
+class KnowledgeGraphProjectMeta(Base):
+ """Project-level curated KG metadata — one row per repository.
+
+ Holds the ranked entry points surfaced by the curation pass so the server
+ never has to read workspace files at request time. JSON columns leave room
+ for future project-level curated metadata.
+ """
+
+ __tablename__ = "kg_project_meta"
+
+ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)
+ repository_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
+ )
+ entry_points_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
+ entry_candidates_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc
+ )
+
+ __table_args__ = (UniqueConstraint("repository_id", name="uq_kg_project_meta"),)
+
+
+class KnowledgeGraphNodeMeta(Base):
+ """Per-node curated KG metadata (presentation view only).
+
+ Stores the curated ``type``/``summary``/``tags`` for file nodes so the
+ architecture view can prefer them over heuristics after the one-time
+ file → DB migration. The AST graph's ``graph_nodes`` rows are untouched.
+ """
+
+ __tablename__ = "kg_node_meta"
+
+ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)
+ repository_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
+ )
+ node_id: Mapped[str] = mapped_column(Text, nullable=False)
+ node_type: Mapped[str] = mapped_column(Text, nullable=False, default="file")
+ summary: Mapped[str] = mapped_column(Text, nullable=False, default="")
+ tags_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
+ created_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc
+ )
+
+ __table_args__ = (UniqueConstraint("repository_id", "node_id", name="uq_kg_node_meta"),)
+
+
class PipelineJob(Base):
"""Checkpoint/resume state for one execution of a pipeline phase.
diff --git a/packages/core/src/repowise/core/persistence/vector_store/_base.py b/packages/core/src/repowise/core/persistence/vector_store/_base.py
index e5d1d970b..1bdf34f7b 100644
--- a/packages/core/src/repowise/core/persistence/vector_store/_base.py
+++ b/packages/core/src/repowise/core/persistence/vector_store/_base.py
@@ -52,9 +52,7 @@ class VectorStore(ABC):
"""Embed *query* and return the *limit* nearest pages."""
...
- async def search_many(
- self, queries: list[str], limit: int = 10
- ) -> list[list[SearchResult]]:
+ async def search_many(self, queries: list[str], limit: int = 10) -> list[list[SearchResult]]:
"""Batch variant of :meth:`search` — one result list per query, aligned
by index.
@@ -79,6 +77,18 @@ class VectorStore(ABC):
"""Remove the vector for *page_id* from the store."""
...
+ async def delete_many(self, page_ids: list[str]) -> None:
+ """Remove the vectors for many *page_ids* from the store.
+
+ Embeddings are keyed by page_id, so when a re-index sweeps stale
+ structurally-keyed pages their vectors must be dropped too — otherwise
+ a retired page's embedding lingers and pollutes search. The default
+ implementation loops over :meth:`delete`; backends that can express a
+ single bulk delete override this. Empty input is a no-op.
+ """
+ for page_id in page_ids:
+ await self.delete(page_id)
+
@abstractmethod
async def close(self) -> None:
"""Release any resources held by the store."""
diff --git a/packages/core/src/repowise/core/persistence/vector_store/in_memory.py b/packages/core/src/repowise/core/persistence/vector_store/in_memory.py
index 02188d188..b61ca9d2e 100644
--- a/packages/core/src/repowise/core/persistence/vector_store/in_memory.py
+++ b/packages/core/src/repowise/core/persistence/vector_store/in_memory.py
@@ -64,9 +64,7 @@ class InMemoryVectorStore(VectorStore):
q_vecs = await self._embedder.embed([query])
return self._search_by_vector(q_vecs[0], limit)
- async def search_many(
- self, queries: list[str], limit: int = 10
- ) -> list[list[SearchResult]]:
+ async def search_many(self, queries: list[str], limit: int = 10) -> list[list[SearchResult]]:
"""One embedder call for all queries, then local scoring per query."""
if not queries:
return []
@@ -78,6 +76,10 @@ class InMemoryVectorStore(VectorStore):
async def delete(self, page_id: str) -> None:
self._store.pop(page_id, None)
+ async def delete_many(self, page_ids: list[str]) -> None:
+ for page_id in page_ids:
+ self._store.pop(page_id, None)
+
async def close(self) -> None:
self._store.clear()
diff --git a/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py b/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py
index 4d521c1ba..5e4866b68 100644
--- a/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py
+++ b/packages/core/src/repowise/core/persistence/vector_store/lancedb_store.py
@@ -21,6 +21,16 @@ def _paths_in_filter(paths: list[str]) -> str:
return f"target_path IN ({quoted})"
+def _page_ids_in_filter(page_ids: list[str]) -> str:
+ """Build an SQL-injection-safe ``page_id IN (...)`` LanceDB filter.
+
+ Mirrors :func:`_paths_in_filter` but on the ``page_id`` column, using the
+ same quote-doubling escape as the single-id delete.
+ """
+ quoted = ", ".join("'" + p.replace("'", "''") + "'" for p in page_ids)
+ return f"page_id IN ({quoted})"
+
+
class LanceDBVectorStore(VectorStore):
"""Vector store backed by LanceDB (embedded, local file storage).
@@ -197,9 +207,7 @@ class LanceDBVectorStore(VectorStore):
q_vecs = await self._embedder.embed([query])
return await self._search_by_vector([float(v) for v in q_vecs[0]], limit)
- async def search_many(
- self, queries: list[str], limit: int = 10
- ) -> list[list[SearchResult]]:
+ async def search_many(self, queries: list[str], limit: int = 10) -> list[list[SearchResult]]:
"""One embedder call for all queries; the vector lookups are local."""
if not queries:
return []
@@ -221,6 +229,18 @@ class LanceDBVectorStore(VectorStore):
safe_id = page_id.replace("'", "''")
await self._table.delete(f"page_id = '{safe_id}'") # type: ignore[union-attr]
+ async def delete_many(self, page_ids: list[str]) -> None:
+ if not page_ids:
+ return
+ await self._ensure_connected()
+ if self._table is None:
+ return
+ # LanceDB's ``.where()`` has no bind params, so build a quoted IN
+ # predicate; chunk to keep the SQL string bounded.
+ for i in range(0, len(page_ids), 500):
+ batch = page_ids[i : i + 500]
+ await self._table.delete(_page_ids_in_filter(batch)) # type: ignore[union-attr]
+
async def close(self) -> None:
self._table = None
self._db = None
diff --git a/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py b/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py
index 8c441ed39..065f95274 100644
--- a/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py
+++ b/packages/core/src/repowise/core/persistence/vector_store/pgvector_store.py
@@ -65,9 +65,7 @@ class PgVectorStore(VectorStore):
async with self._session_factory() as session:
await session.execute(
- sa_text(
- "UPDATE wiki_pages SET embedding = CAST(:emb AS vector) WHERE id = :pid"
- ),
+ sa_text("UPDATE wiki_pages SET embedding = CAST(:emb AS vector) WHERE id = :pid"),
{"emb": vec_str, "pid": page_id},
)
await session.commit()
@@ -84,9 +82,7 @@ class PgVectorStore(VectorStore):
from sqlalchemy.sql import text as sa_text
- stmt = sa_text(
- "UPDATE wiki_pages SET embedding = CAST(:emb AS vector) WHERE id = :pid"
- )
+ stmt = sa_text("UPDATE wiki_pages SET embedding = CAST(:emb AS vector) WHERE id = :pid")
async with self._session_factory() as session:
# executemany: one driver round-trip batch instead of one UPDATE
# round-trip per row.
@@ -126,9 +122,7 @@ class PgVectorStore(VectorStore):
for r in raw
]
- async def search_many(
- self, queries: list[str], limit: int = 10
- ) -> list[list[SearchResult]]:
+ async def search_many(self, queries: list[str], limit: int = 10) -> list[list[SearchResult]]:
"""One embedder call for all queries; per-query SELECTs share a session."""
if not queries:
return []
@@ -148,9 +142,7 @@ class PgVectorStore(VectorStore):
async with self._session_factory() as session:
for q_vec in q_vecs:
try:
- rows = await session.execute(
- stmt, {"q": _encode(q_vec), "lim": limit}
- )
+ rows = await session.execute(stmt, {"q": _encode(q_vec), "lim": limit})
raw = rows.fetchall()
except Exception:
out.append([])
@@ -181,6 +173,20 @@ class PgVectorStore(VectorStore):
)
await session.commit()
+ async def delete_many(self, page_ids: list[str]) -> None:
+ if not page_ids:
+ return
+ from sqlalchemy import bindparam
+ from sqlalchemy.sql import text as sa_text
+
+ stmt = sa_text("UPDATE wiki_pages SET embedding = NULL WHERE id IN :ids").bindparams(
+ bindparam("ids", expanding=True)
+ )
+
+ async with self._session_factory() as session:
+ await session.execute(stmt, {"ids": list(page_ids)})
+ await session.commit()
+
async def close(self) -> None:
pass # session_factory manages connection lifecycle
@@ -205,9 +211,7 @@ class PgVectorStore(VectorStore):
async with self._session_factory() as session:
rows = await session.execute(
sa_text(
- "SELECT content, metadata FROM wiki_pages "
- "WHERE target_path = :path "
- "LIMIT 1"
+ "SELECT content, metadata FROM wiki_pages WHERE target_path = :path LIMIT 1"
),
{"path": path},
)
@@ -232,8 +236,7 @@ class PgVectorStore(VectorStore):
from sqlalchemy.sql import text as sa_text
stmt = sa_text(
- "SELECT target_path, content, metadata FROM wiki_pages "
- "WHERE target_path IN :paths"
+ "SELECT target_path, content, metadata FROM wiki_pages WHERE target_path IN :paths"
).bindparams(bindparam("paths", expanding=True))
async with self._session_factory() as session:
diff --git a/packages/core/src/repowise/core/pipeline/__init__.py b/packages/core/src/repowise/core/pipeline/__init__.py
index 13f8fcab8..0b0497b00 100644
--- a/packages/core/src/repowise/core/pipeline/__init__.py
+++ b/packages/core/src/repowise/core/pipeline/__init__.py
@@ -11,6 +11,9 @@ Usage::
"""
from .orchestrator import PipelineResult, run_generation, run_pipeline
+from .persist import (
+ _sweep_stale_generated_pages as sweep_stale_generated_pages,
+)
from .persist import (
persist_analysis,
persist_generation,
@@ -35,4 +38,5 @@ __all__ = [
"rehydrate_graph_builder",
"run_generation",
"run_pipeline",
+ "sweep_stale_generated_pages",
]
diff --git a/packages/core/src/repowise/core/pipeline/orchestrator.py b/packages/core/src/repowise/core/pipeline/orchestrator.py
index 4639cbaae..3e18bb3d0 100644
--- a/packages/core/src/repowise/core/pipeline/orchestrator.py
+++ b/packages/core/src/repowise/core/pipeline/orchestrator.py
@@ -136,6 +136,16 @@ class PipelineResult:
it is already on disk — and writes only analysis + generation. False for
every non-resume caller, which persist the full result as before."""
+ authoritative_page_types: set[str] = field(default_factory=set)
+ """Structural page types this run fully decided — i.e. its emitted set is
+ "exactly these, possibly none". The stale-page sweep retires prior rows of
+ a type when it was produced OR is named here, so a legitimately-empty
+ authoritative type (e.g. every curated module collapsed into its layer via
+ wholeLayer) still wipes the previous run's stragglers. Populated only on a
+ curated run with a real KG; left empty on degraded/community fallback and
+ on incremental no-KG paths, which preserves degradation honesty (a fallback
+ run never wipes curated pages it could not reproduce)."""
+
# ---------------------------------------------------------------------------
# Pipeline
@@ -525,6 +535,34 @@ async def run_pipeline(
f"{len(knowledge_graph_result.layers)} layers",
)
_phase_done(progress, "knowledge_graph.skeleton")
+
+ # ---- KG curation/presentation pass (flagged, default on) ---------
+ # Reshapes only the exported KG (layers/tour/entry-points/summaries);
+ # never touches the AST graph, communities, or centrality. No-op when
+ # REPOWISE_KG_CURATION is set to a falsy value (the raw uncurated
+ # export). Runs in BOTH FAST and STANDARD (before the generate branch).
+ if knowledge_graph_result is not None:
+ from repowise.core.analysis.kg_curation import (
+ curate_knowledge_graph,
+ curation_enabled,
+ )
+
+ try:
+ # In generate mode the summary floor is deferred to run after
+ # the wiki-page backfill (in ``enrich_knowledge_graph``), so
+ # rich page summaries win; FAST mode floors here.
+ will_generate = generate_docs and llm_client is not None
+ knowledge_graph_result = curate_knowledge_graph(
+ knowledge_graph_result,
+ parsed_files=parsed_files,
+ graph_builder=graph_builder,
+ repo_structure=repo_structure,
+ community_info=graph_builder.community_info(),
+ enabled=curation_enabled(),
+ defer_summary_floor=will_generate,
+ )
+ except (ValueError, KeyError, RuntimeError) as cur_err:
+ logger.error("kg_curation_failed", error=str(cur_err), exc_info=True)
except (ValueError, KeyError, OSError, RuntimeError) as kg_err:
logger.error("kg_skeleton_building_failed", error=str(kg_err), exc_info=True)
@@ -543,6 +581,10 @@ async def run_pipeline(
# ---- Phase 3: Generation (optional) ------------------------------------
generated_pages: list[Any] | None = None
+ # Structural page types this run was authoritative for (see
+ # PipelineResult.authoritative_page_types). Stays empty unless curated
+ # generation engaged below.
+ authoritative_page_types: set[str] = set()
if generate_docs and llm_client is not None:
if progress:
progress.on_message("info", "Phase 3: Generation")
@@ -590,7 +632,38 @@ async def run_pipeline(
decision_report=gen_decision_report,
external_systems=external_systems,
on_page_ready=on_page_ready,
+ # In-memory KG — the artifact file is written after generation,
+ # so it cannot carry layers/tour/modules on a fresh init.
+ kg_modules=(
+ knowledge_graph_result.modules or None
+ if knowledge_graph_result is not None
+ else None
+ ),
+ kg_data=(
+ knowledge_graph_result.to_dict()
+ if knowledge_graph_result is not None
+ else None
+ ),
+ )
+
+ # Record which structural page types this run authoritatively decided,
+ # so the sweep can retire prior rows of a type even when this run
+ # legitimately emitted zero pages of it. Mirrors the selector's curated
+ # engagement test (_build_curated_module_groups returns None — i.e.
+ # falls back to community — only when kg_modules is empty) so the signal
+ # is set iff the curated grouping actually engaged. On the degraded
+ # community fallback both stay unset, preserving degradation honesty.
+ kg_modules_present = bool(
+ knowledge_graph_result is not None and knowledge_graph_result.modules
+ )
+ kg_layers_present = bool(
+ knowledge_graph_result is not None and knowledge_graph_result.layers
)
+ module_grouping = getattr(resolved_generation_config, "module_grouping", "community")
+ if module_grouping == "curated" and kg_modules_present:
+ authoritative_page_types.add("module_page")
+ if kg_layers_present:
+ authoritative_page_types.add("layer_page")
# ---- Knowledge Graph LLM enrichment (layer naming + tour) -----------------
if knowledge_graph_result is not None and generate_docs and llm_client is not None:
@@ -674,6 +747,7 @@ async def run_pipeline(
index_persisted_incrementally=(
resume_controller.index_persisted if resume_controller is not None else False
),
+ authoritative_page_types=authoritative_page_types,
)
diff --git a/packages/core/src/repowise/core/pipeline/persist.py b/packages/core/src/repowise/core/pipeline/persist.py
index fc71d80d3..c5f0ee8ff 100644
--- a/packages/core/src/repowise/core/pipeline/persist.py
+++ b/packages/core/src/repowise/core/pipeline/persist.py
@@ -216,6 +216,74 @@ async def _prune_stale_file_rows(
await _delete_stale_by_paths(GitMetadata, GitMetadata.file_path, current_git_file_paths)
+# Generated page types keyed on run-scoped structure: module/scc pages on
+# clustering ordinals, layer pages on display names. Those keys shift between
+# runs, so re-runs mint fresh page ids and the previous rows linger as
+# duplicates unless swept against the current run's output.
+_SWEPT_GENERATED_PAGE_TYPES = ("module_page", "layer_page", "scc_page")
+
+
+async def _sweep_stale_generated_pages(
+ session: Any,
+ repo_id: str,
+ generated_pages: list[Any] | None,
+ authoritative_page_types: set[str] | None = None,
+) -> list[str]:
+ """Delete structurally-keyed generated pages this run did not produce.
+
+ Sweeps a page type when the run either produced at least one page of it OR
+ declared itself authoritative for it (``authoritative_page_types`` — set by
+ the generation layer when it fully decided the type, even if that decision
+ was "emit none"; e.g. a curated run whose modules all collapsed into their
+ layers via ``wholeLayer``). A type that is neither produced nor authoritative
+ is left untouched, so a skipped/failed/degraded level never wipes the last
+ good set. When authoritative-but-empty, the current set is empty and every
+ prior row of that type is retired. Page versions go with their page (FK
+ enforcement requires it, and a retired structural id never comes back to
+ claim its history). Returns the swept page ids so the caller can drop them
+ from FTS after the session closes (the FTS store must not be touched
+ in-session).
+ """
+ from sqlalchemy import delete, select
+
+ from repowise.core.persistence.models import Page, PageVersion
+
+ produced: dict[str, set[str]] = {}
+ for page in generated_pages or []:
+ produced.setdefault(page.page_type, set()).add(page.page_id)
+ authoritative = authoritative_page_types or set()
+
+ swept: list[str] = []
+ for page_type in _SWEPT_GENERATED_PAGE_TYPES:
+ current = produced.get(page_type)
+ if not current and page_type not in authoritative:
+ continue
+ current = current or set()
+ existing = (
+ (
+ await session.execute(
+ select(Page.id).where(
+ Page.repository_id == repo_id, Page.page_type == page_type
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ stale = [pid for pid in existing if pid not in current]
+ for i in range(0, len(stale), _PRUNE_CHUNK):
+ batch = stale[i : i + _PRUNE_CHUNK]
+ await session.execute(delete(PageVersion).where(PageVersion.page_id.in_(batch)))
+ await session.execute(
+ delete(Page).where(Page.repository_id == repo_id, Page.id.in_(batch))
+ )
+ swept.extend(stale)
+
+ if swept:
+ logger.info("stale_generated_pages_swept", repo_id=repo_id, count=len(swept))
+ return swept
+
+
async def persist_ingestion(result: Any, session: Any, repo_id: str) -> int:
"""Persist ingestion-phase outputs: graph nodes/edges, external systems,
symbols, and the per-file security scan.
@@ -479,22 +547,45 @@ async def persist_generation(result: Any, session: Any, repo_id: str) -> None:
for page in result.generated_pages:
await upsert_page_from_generated(session, page, repo_id)
- # ---- Knowledge graph layers & tour steps --------------------------------
+ # ---- Knowledge graph layers, tour steps & curated meta ------------------
kg = getattr(result, "knowledge_graph_result", None)
if kg is not None:
- from repowise.core.persistence.crud import upsert_kg_layers, upsert_kg_tour_steps
+ from repowise.core.persistence.crud import (
+ file_node_meta_from_kg_nodes,
+ upsert_kg_layers,
+ upsert_kg_node_meta,
+ upsert_kg_project_meta,
+ upsert_kg_tour_steps,
+ )
if hasattr(kg, "layers") and kg.layers:
await upsert_kg_layers(session, repo_id, kg.layers)
if hasattr(kg, "tour") and kg.tour:
await upsert_kg_tour_steps(session, repo_id, kg.tour)
+ # Project-level curated meta (ranked entry points from the curation pass).
+ project = getattr(kg, "project", None)
+ if isinstance(project, dict) and project.get("entry_points"):
+ await upsert_kg_project_meta(
+ session,
+ repo_id,
+ entry_points=project["entry_points"],
+ entry_candidates=project.get("entry_candidates", []),
+ )
+
+ # Per-node curated meta (type/summary/tags) for file nodes, stored with
+ # the "file:" prefix stripped so the architecture view can match its
+ # node ids (plain repo-relative paths) directly.
+ file_node_meta = file_node_meta_from_kg_nodes(getattr(kg, "nodes", None) or [])
+ if file_node_meta:
+ await upsert_kg_node_meta(session, repo_id, file_node_meta)
+
async def persist_pipeline_result(
result: Any,
session: Any,
repo_id: str,
-) -> None:
+) -> list[str]:
"""Persist all outputs from a :class:`PipelineResult` into the database.
Thin composition of the four phase-scoped persisters
@@ -512,6 +603,11 @@ async def persist_pipeline_result(
repo_id:
The repository ID to associate all records with.
+ Returns
+ -------
+ The page ids of stale generated pages swept by this run. Callers should
+ remove them from the FTS index after the session closes.
+
Note
----
FTS indexing is intentionally excluded here — callers must do it after
@@ -537,6 +633,17 @@ async def persist_pipeline_result(
await persist_analysis(result, session, repo_id)
await persist_generation(result, session, repo_id)
+ # Sweep structurally-keyed generated pages (module/layer/scc) that this
+ # run did not reproduce — their ids drift between runs, so without the
+ # sweep every re-index strands the previous set as duplicates. Full runs
+ # only, same rule as _prune_stale_file_rows.
+ swept_page_ids = await _sweep_stale_generated_pages(
+ session,
+ repo_id,
+ result.generated_pages,
+ getattr(result, "authoritative_page_types", None),
+ )
+
logger.info(
"pipeline_result_persisted",
repo_id=repo_id,
@@ -545,3 +652,4 @@ async def persist_pipeline_result(
symbols=symbol_count,
git_files=len(result.git_metadata_list),
)
+ return swept_page_ids
diff --git a/packages/core/src/repowise/core/pipeline/phases/generation.py b/packages/core/src/repowise/core/pipeline/phases/generation.py
index 4d35b3563..d2a642224 100644
--- a/packages/core/src/repowise/core/pipeline/phases/generation.py
+++ b/packages/core/src/repowise/core/pipeline/phases/generation.py
@@ -40,6 +40,8 @@ async def run_generation(
external_systems: list[dict] | None = None,
on_page_ready: Any | None = None,
prior_pages: dict[str, Any] | None = None,
+ kg_modules: list[dict] | None = None,
+ kg_data: dict | None = None,
) -> list[Any]:
"""Run LLM-powered page generation.
@@ -137,6 +139,8 @@ async def run_generation(
decision_report=decision_report,
external_systems=external_systems,
on_page_ready=on_page_ready,
+ kg_modules=kg_modules,
+ kg_data=kg_data,
)
# Onboarding summary — count generated slots and surface which ones
diff --git a/packages/server/src/repowise/server/job_executor.py b/packages/server/src/repowise/server/job_executor.py
index 53c58afb8..e9d183308 100644
--- a/packages/server/src/repowise/server/job_executor.py
+++ b/packages/server/src/repowise/server/job_executor.py
@@ -311,7 +311,7 @@ async def execute_job(
# ---- Persist results -----------------------------------------------
async with get_session(session_factory) as session:
- await persist_pipeline_result(result, session, repo_id)
+ swept_page_ids = await persist_pipeline_result(result, session, repo_id)
# Persist incrementally regenerated pages
if incremental_pages:
@@ -320,8 +320,22 @@ async def execute_job(
for page in incremental_pages:
await upsert_page_from_generated(session, page, repo_id)
- # FTS indexing runs after session closes to avoid SQLite write conflicts
+ # Drop swept pages from the vector store *before* the SQL session
+ # commits. The vector store is a separate engine/file (pgvector DB,
+ # LanceDB dir, or in-memory), so there is no SQLite write-lock
+ # conflict and the idempotent delete leaves the durable SQL commit
+ # last: an interrupted run self-heals (embedding already gone, SQL
+ # rows follow on commit).
+ if swept_page_ids and vector_store is not None:
+ await vector_store.delete_many(swept_page_ids)
+
+ # FTS deletes/indexing run after the session closes: the FTS index can
+ # share the SQLite file with the session, so writing it while the
+ # session holds a write lock raises "database is locked". The swept-id
+ # delete is idempotent (orphan FTS rows only) and must stay here.
all_pages = (result.generated_pages or []) + incremental_pages
+ if fts is not None and swept_page_ids:
+ await fts.delete_many(swept_page_ids)
if fts is not None and all_pages:
for page in all_pages:
await fts.index(page.page_id, page.title, page.content)
@@ -528,6 +542,7 @@ async def _incremental_page_regen(
result.repo_structure,
result.repo_name,
git_meta_map=result.git_meta_map,
+ repo_path=repo_path,
)
logger.info("incremental_page_regen_done", pages=len(pages))
diff --git a/packages/server/src/repowise/server/routers/c4.py b/packages/server/src/repowise/server/routers/c4.py
index 8c7ade485..4d0be7d0b 100644
--- a/packages/server/src/repowise/server/routers/c4.py
+++ b/packages/server/src/repowise/server/routers/c4.py
@@ -22,6 +22,7 @@ from repowise.server.schemas import (
ArchitectureViewResponse,
ArchLayerResponse,
ArchNodeResponse,
+ ArchSubGroupResponse,
ArchTourStepResponse,
C4ComponentResponse,
C4ContainerResponse,
@@ -222,6 +223,11 @@ def _arch_layer(layer: ArchLayer) -> ArchLayerResponse:
file_count=layer.file_count,
complexity_distribution=layer.complexity_distribution,
health_score=layer.health_score,
+ sub_groups=[
+ ArchSubGroupResponse(id=sg.id, name=sg.name, node_ids=sg.node_ids)
+ for sg in layer.sub_groups
+ ],
+ display_order=layer.display_order,
)
@@ -270,6 +276,12 @@ def _arch_tour_step(s: ArchTourStep) -> ArchTourStepResponse:
title=s.title,
description=s.description,
node_ids=s.node_ids,
+ target_path=s.target_path,
+ layer_id=s.layer_id,
+ reason=s.reason,
+ depth=s.depth,
+ kind=s.kind,
+ page_type=s.page_type,
)
@@ -287,4 +299,6 @@ def _architecture_view_response(view: ArchitectureView) -> ArchitectureViewRespo
languages=view.languages,
frameworks=view.frameworks,
external_systems=[_external(e) for e in view.external_systems],
+ entry_points=view.entry_points,
+ entry_candidates=view.entry_candidates,
)
diff --git a/packages/server/src/repowise/server/routers/graph/community.py b/packages/server/src/repowise/server/routers/graph/community.py
index dff1c7d15..a74e1f327 100644
--- a/packages/server/src/repowise/server/routers/graph/community.py
+++ b/packages/server/src/repowise/server/routers/graph/community.py
@@ -3,25 +3,43 @@
from __future__ import annotations
from fastapi import APIRouter, Depends, HTTPException, Query
-from sqlalchemy import select
+from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from repowise.core.persistence import crud
from repowise.core.persistence.models import GraphEdge, GraphNode
from repowise.server.deps import get_db_session
from repowise.server.mcp_server._graph_utils import community_cohesion, community_label
-from repowise.server.routers.graph._common import with_repo
-from repowise.server.routers.graph.signals import _EMPTY_SIGNALS, _collect_node_signals
+from repowise.server.routers.graph._common import _edge_response, with_repo
+from repowise.server.routers.graph.signals import (
+ _EMPTY_SIGNALS,
+ _collect_node_signals,
+ _node_to_response,
+)
from repowise.server.schemas import (
ArchitectureEdgeResponse,
ArchitectureGraphResponse,
ArchitectureNodeResponse,
CommunityDetailResponse,
CommunityMember,
+ CommunitySliceNodeResponse,
+ CommunitySliceResponse,
CommunitySummaryItem,
NeighboringCommunity,
)
+# Cap on slice member nodes. Communities are small relative to the repo, but a
+# few mega-clusters exist; this keeps the blossom payload in the 50-300 target
+# band and the satellite layout responsive.
+_SLICE_MEMBER_CAP = 300
+# Boundary stubs per slice: only the most-connected outside neighbors survive,
+# so a blossom shows its strongest cross-cluster ties instead of a dust cloud.
+_SLICE_BOUNDARY_CAP = 40
+# Chunk size for member-id IN lists. The slice edge filter ORs two IN clauses
+# (source + target) in one statement, so we cap each chunk well under SQLite's
+# 999-parameter limit to leave room for both lists plus the repo_id bind.
+_SLICE_IN_CHUNK = 400
+
router = APIRouter()
@@ -122,6 +140,118 @@ async def architecture_graph(
return ArchitectureGraphResponse(nodes=arch_nodes, edges=arch_edges)
+ "/{repo_id}/communities/{community_id}/slice",
+ response_model=CommunitySliceResponse,
+)
+async def community_slice(
+ repo_id: str,
+ community_id: int,
+ member_limit: int = Query(_SLICE_MEMBER_CAP, ge=1, le=600),
+ session: AsyncSession = Depends(get_db_session), # noqa: B008
+ _repo: object = Depends(with_repo),
+) -> CommunitySliceResponse:
+ """Return a single community's sub-graph for the constellation blossom.
+
+ Payload = the community's member file nodes, the edges among them, and a
+ thin ring of one-hop *boundary stubs*: neighbor nodes outside the community
+ that share an edge with a member, returned as minimal nodes flagged
+ ``is_boundary=true`` so cross-cluster edges can render without dragging the
+ whole neighbor cluster in. Sized to ~50-300 nodes.
+ """
+ members = await crud.get_community_members(
+ session, repo_id, community_id, node_type="file", limit=member_limit + 1
+ )
+ truncated = len(members) > member_limit
+ if truncated:
+ members = members[:member_limit]
+ member_ids = {m.node_id for m in members}
+
+ # Edges touching any member: among-members stay; member<->outside become
+ # cross-cluster links that pull in a boundary stub for the outside endpoint.
+ # The membership filter is pushed into SQL (source OR target in members) so
+ # we never load the whole repo's edge table into Python; the IN lists are
+ # chunked under SQLite's parameter limit. The Python filter below is kept
+ # as-is for correctness — the SQL only bounds the rows fetched (a
+ # superset-or-equal of what the Python filter keeps).
+ member_id_list = list(member_ids)
+ edge_rows: dict[str, GraphEdge] = {}
+ for start in range(0, len(member_id_list), _SLICE_IN_CHUNK):
+ chunk = member_id_list[start : start + _SLICE_IN_CHUNK]
+ chunk_result = await session.execute(
+ select(GraphEdge).where(
+ GraphEdge.repository_id == repo_id,
+ or_(
+ GraphEdge.source_node_id.in_(chunk),
+ GraphEdge.target_node_id.in_(chunk),
+ ),
+ )
+ )
+ # Dedup across chunks: an edge whose endpoints fall in different chunks
+ # matches twice. The PK keeps each edge once.
+ for e in chunk_result.scalars():
+ edge_rows[e.id] = e
+
+ kept_edges: list[GraphEdge] = []
+ boundary_degree: dict[str, int] = {}
+ for e in edge_rows.values():
+ src_in = e.source_node_id in member_ids
+ tgt_in = e.target_node_id in member_ids
+ if not src_in and not tgt_in:
+ continue
+ kept_edges.append(e)
+ if not src_in:
+ boundary_degree[e.source_node_id] = boundary_degree.get(e.source_node_id, 0) + 1
+ if not tgt_in:
+ boundary_degree[e.target_node_id] = boundary_degree.get(e.target_node_id, 0) + 1
+
+ # Cap boundary stubs to the most-connected neighbors: hub communities can
+ # touch thousands of outside files, which would flood the blossom with
+ # dust. Edges to dropped stubs are filtered by the visible_ids pass below.
+ boundary_ids = set(
+ sorted(boundary_degree, key=lambda n: (-boundary_degree[n], n))[:_SLICE_BOUNDARY_CAP]
+ )
+
+ # Resolve boundary stub rows (minimal: just need a node row to render).
+ boundary_nodes: list[GraphNode] = []
+ if boundary_ids:
+ stub_result = await session.execute(
+ select(GraphNode).where(
+ GraphNode.repository_id == repo_id,
+ GraphNode.node_id.in_(boundary_ids),
+ )
+ )
+ boundary_nodes = list(stub_result.scalars().all())
+ resolved_boundary = {n.node_id for n in boundary_nodes}
+
+ # Drop edges whose outside endpoint has no resolvable node (orphan ref).
+ visible_ids = member_ids | resolved_boundary
+ links = [
+ _edge_response(e)
+ for e in kept_edges
+ if e.source_node_id in visible_ids and e.target_node_id in visible_ids
+ ]
+
+ # Member signals only (boundary stubs stay minimal / all-false signals).
+ signals = await _collect_node_signals(session, repo_id, list(member_ids))
+ nodes = [
+ _node_to_response(m, signals.get(m.node_id, _EMPTY_SIGNALS), CommunitySliceNodeResponse)
+ for m in members
+ ]
+ nodes.extend(
+ _node_to_response(n, _EMPTY_SIGNALS, CommunitySliceNodeResponse, is_boundary=True)
+ for n in boundary_nodes
+ )
+
+ return CommunitySliceResponse(
+ nodes=nodes,
+ links=links,
+ community_id=community_id,
+ member_count=len(members),
+ truncated=truncated,
+ )
+
+
@router.get("/{repo_id}/communities", response_model=list[CommunitySummaryItem])
async def list_communities(
repo_id: str,
diff --git a/packages/server/src/repowise/server/routers/graph/full_graph.py b/packages/server/src/repowise/server/routers/graph/full_graph.py
index 02bff8a06..25828b933 100644
--- a/packages/server/src/repowise/server/routers/graph/full_graph.py
+++ b/packages/server/src/repowise/server/routers/graph/full_graph.py
@@ -17,8 +17,9 @@ from repowise.server.routers.graph.signals import (
from repowise.server.schemas import GraphExportResponse, NodeSearchResult
# Cap on full-graph export; above this we return top-N by PageRank with truncated=True.
-# Sized to fit a modern client-side force layout without hitching.
-_FULL_GRAPH_NODE_CAP = 5000
+# Sized to keep the client-side force layout responsive; clients can step the
+# limit up via the truncation banner.
+_FULL_GRAPH_NODE_CAP = 1500
router = APIRouter()
@@ -54,8 +55,8 @@ async def export_graph(
limit: int = Query(
_FULL_GRAPH_NODE_CAP,
ge=1,
- le=100_000,
- description="Maximum nodes to return (top-N by PageRank). Set very high to fetch all.",
+ le=6000,
+ description="Maximum nodes to return (top-N by PageRank). Stepped up by the client.",
),
session: AsyncSession = Depends(get_db_session), # noqa: B008
_repo: object = Depends(with_repo),
diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.py
index 2f4bae5ff..b9430e6f4 100644
--- a/packages/server/src/repowise/server/schemas/__init__.py
+++ b/packages/server/src/repowise/server/schemas/__init__.py
@@ -12,6 +12,7 @@ from .architecture import (
ArchitectureViewResponse,
ArchLayerResponse,
ArchNodeResponse,
+ ArchSubGroupResponse,
ArchTourStepResponse,
)
from .blast_radius import (
@@ -69,6 +70,8 @@ from .graph import (
ArchitectureEdgeResponse,
ArchitectureGraphResponse,
ArchitectureNodeResponse,
+ CommunitySliceNodeResponse,
+ CommunitySliceResponse,
DeadCodeGraphNodeResponse,
DeadCodeGraphResponse,
EgoGraphResponse,
@@ -163,6 +166,7 @@ __all__ = [
"ArchEdgeResponse",
"ArchLayerResponse",
"ArchNodeResponse",
+ "ArchSubGroupResponse",
"ArchTourStepResponse",
"ArchitectureEdgeResponse",
"ArchitectureGraphResponse",
@@ -188,6 +192,8 @@ __all__ = [
"CommitResponse",
"CommunityDetailResponse",
"CommunityMember",
+ "CommunitySliceNodeResponse",
+ "CommunitySliceResponse",
"CommunitySummaryItem",
"ConversationResponse",
"CoordinatorHealthResponse",
diff --git a/packages/server/src/repowise/server/schemas/architecture.py b/packages/server/src/repowise/server/schemas/architecture.py
index 30fd4e7d9..85d4ce2d1 100644
--- a/packages/server/src/repowise/server/schemas/architecture.py
+++ b/packages/server/src/repowise/server/schemas/architecture.py
@@ -7,6 +7,12 @@ from pydantic import BaseModel
from .c4 import C4ExternalSystemResponse
+class ArchSubGroupResponse(BaseModel):
+ id: str
+ name: str
+ node_ids: list[str]
+
+
class ArchLayerResponse(BaseModel):
id: str
name: str
@@ -15,6 +21,8 @@ class ArchLayerResponse(BaseModel):
file_count: int
complexity_distribution: dict[str, int]
health_score: float | None
+ sub_groups: list[ArchSubGroupResponse] = []
+ display_order: int = 0
class ArchNodeResponse(BaseModel):
@@ -57,6 +65,13 @@ class ArchTourStepResponse(BaseModel):
title: str
description: str
node_ids: list[str]
+ # Curated, layer-aware fields (None/empty for legacy LLM tours).
+ target_path: str | None = None
+ layer_id: str | None = None
+ reason: str = ""
+ depth: int | None = None
+ kind: str = ""
+ page_type: str | None = None
class ArchitectureViewResponse(BaseModel):
@@ -72,3 +87,6 @@ class ArchitectureViewResponse(BaseModel):
languages: list[str]
frameworks: list[str]
external_systems: list[C4ExternalSystemResponse]
+ # Curated, ranked entry points (repo-relative paths; empty when uncurated).
+ entry_points: list[str] = []
+ entry_candidates: list[str] = []
diff --git a/packages/server/src/repowise/server/schemas/graph.py b/packages/server/src/repowise/server/schemas/graph.py
index cb63124e0..821ff7539 100644
--- a/packages/server/src/repowise/server/schemas/graph.py
+++ b/packages/server/src/repowise/server/schemas/graph.py
@@ -69,6 +69,23 @@ class ArchitectureGraphResponse(BaseModel):
edges: list[ArchitectureEdgeResponse]
+class CommunitySliceNodeResponse(GraphNodeResponse):
+ # True for one-hop neighbor stubs outside the community: rendered tiny/dimmed
+ # so cross-cluster edges can draw, without pulling the whole neighbor cluster in.
+ is_boundary: bool = False
+
+
+class CommunitySliceResponse(BaseModel):
+ # Member nodes of the community plus minimal one-hop boundary stubs.
+ nodes: list[CommunitySliceNodeResponse]
+ # Edges among members, plus member<->boundary edges (cross-cluster links).
+ links: list[GraphEdgeResponse]
+ community_id: int
+ member_count: int
+ # True if members were capped (very large community).
+ truncated: bool = False
+
+
class EgoGraphResponse(BaseModel):
nodes: list[GraphNodeResponse]
links: list[GraphEdgeResponse]
diff --git a/packages/server/src/repowise/server/services/c4_builder/architecture.py b/packages/server/src/repowise/server/services/c4_builder/architecture.py
index 520df3f44..bd3576955 100644
--- a/packages/server/src/repowise/server/services/c4_builder/architecture.py
+++ b/packages/server/src/repowise/server/services/c4_builder/architecture.py
@@ -8,7 +8,8 @@ from bisect import bisect_left
from collections import defaultdict
from sqlalchemy import select
-from sqlalchemy.ext.asyncio import AsyncSession
+from sqlalchemy.exc import IntegrityError
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
from repowise.core.persistence import (
ExternalSystem,
@@ -16,9 +17,14 @@ from repowise.core.persistence import (
GraphNode,
)
from repowise.core.persistence.crud import (
+ file_node_meta_from_kg_nodes,
get_kg_layers,
+ get_kg_node_meta,
+ get_kg_project_meta,
get_kg_tour_steps,
upsert_kg_layers,
+ upsert_kg_node_meta,
+ upsert_kg_project_meta,
upsert_kg_tour_steps,
)
from repowise.core.persistence.models import DeadCodeFinding, GitMetadata, Page
@@ -28,35 +34,59 @@ from .models import (
ArchitectureView,
ArchLayer,
ArchNode,
+ ArchSubGroup,
ArchTourStep,
ExternalSystemView,
)
logger = logging.getLogger(__name__)
-_ENTRY_POINT_NAMES = frozenset({
- "main.py", "app.py", "cli.py", "index.ts", "index.js",
- "index.tsx", "index.jsx", "server.py", "server.ts",
- "__main__.py", "manage.py",
-})
+_ENTRY_POINT_NAMES = frozenset(
+ {
+ "main.py",
+ "app.py",
+ "cli.py",
+ "index.ts",
+ "index.js",
+ "index.tsx",
+ "index.jsx",
+ "server.py",
+ "server.ts",
+ "__main__.py",
+ "manage.py",
+ }
+)
-_SYMBOL_EDGE_TYPES = frozenset({
- "contains", "defines", "has_method",
-})
+_SYMBOL_EDGE_TYPES = frozenset(
+ {
+ "contains",
+ "defines",
+ "has_method",
+ }
+)
_EXT_MAP = {
- ".py": "python", ".pyx": "python",
- ".ts": "typescript", ".tsx": "typescript",
- ".js": "javascript", ".jsx": "javascript",
- ".go": "go", ".rs": "rust",
- ".java": "java", ".kt": "kotlin",
- ".cs": "csharp", ".rb": "ruby",
- ".swift": "swift", ".cpp": "cpp", ".c": "c",
+ ".py": "python",
+ ".pyx": "python",
+ ".ts": "typescript",
+ ".tsx": "typescript",
+ ".js": "javascript",
+ ".jsx": "javascript",
+ ".go": "go",
+ ".rs": "rust",
+ ".java": "java",
+ ".kt": "kotlin",
+ ".cs": "csharp",
+ ".rb": "ruby",
+ ".swift": "swift",
+ ".cpp": "cpp",
+ ".c": "c",
}
async def _external_views(
- session: AsyncSession, repo_id: str,
+ session: AsyncSession,
+ repo_id: str,
) -> list[ExternalSystemView]:
result = await session.execute(
select(ExternalSystem).where(ExternalSystem.repository_id == repo_id)
@@ -131,20 +161,42 @@ def _load_knowledge_graph(path: str) -> dict | None:
return json.load(f)
+def _sub_groups_from_raw(raw_sub_groups: list[dict] | None, node_ids: set[str]) -> list[dict]:
+ """Map curated subGroups to plain dicts, dropping ids absent from the graph."""
+ groups: list[dict] = []
+ for sg in raw_sub_groups or []:
+ mapped = [nid.removeprefix("file:") for nid in sg.get("nodeIds", sg.get("node_ids", []))]
+ matched = [nid for nid in mapped if nid in node_ids]
+ if matched:
+ groups.append(
+ {
+ "id": sg.get("id", ""),
+ "name": sg.get("name", ""),
+ "node_ids": matched,
+ }
+ )
+ return groups
+
+
def _layers_from_knowledge_graph(
- kg: dict, node_ids: set[str],
+ kg: dict,
+ node_ids: set[str],
) -> list[dict]:
layers = []
- for layer in kg.get("layers", []):
+ for i, layer in enumerate(kg.get("layers", [])):
raw_ids = layer.get("nodeIds", [])
mapped = [nid.removeprefix("file:") for nid in raw_ids]
matched = [nid for nid in mapped if nid in node_ids]
- layers.append({
- "id": layer.get("id", ""),
- "name": layer.get("name", ""),
- "description": layer.get("description", ""),
- "node_ids": matched,
- })
+ layers.append(
+ {
+ "id": layer.get("id", ""),
+ "name": layer.get("name", ""),
+ "description": layer.get("description", ""),
+ "node_ids": matched,
+ "display_order": layer.get("display_order", i),
+ "sub_groups": _sub_groups_from_raw(layer.get("subGroups"), node_ids),
+ }
+ )
return layers
@@ -165,12 +217,14 @@ def _layers_from_communities(
if cid in meta:
with contextlib.suppress(json.JSONDecodeError, TypeError):
cm = json.loads(meta[cid])
- layers.append({
- "id": f"layer:community-{cid}",
- "name": cm.get("name", f"Community {cid}"),
- "description": cm.get("description", ""),
- "node_ids": groups[cid],
- })
+ layers.append(
+ {
+ "id": f"layer:community-{cid}",
+ "name": cm.get("name", f"Community {cid}"),
+ "description": cm.get("description", ""),
+ "node_ids": groups[cid],
+ }
+ )
return layers
@@ -195,12 +249,22 @@ def _tour_from_knowledge_graph(kg: dict) -> list[ArchTourStep]:
steps = []
for entry in kg.get("tour", []):
node_ids = [nid.removeprefix("file:") for nid in entry.get("nodeIds", [])]
+ target_path = entry.get("target_path")
+ if not node_ids and target_path:
+ # Curated steps address one file by path, not a nodeIds list.
+ node_ids = [target_path]
steps.append(
ArchTourStep(
order=entry.get("order", 0),
title=entry.get("title", ""),
description=entry.get("description", ""),
node_ids=node_ids,
+ target_path=target_path,
+ layer_id=entry.get("layer_id"),
+ reason=entry.get("reason", ""),
+ depth=entry.get("depth"),
+ kind=entry.get("kind", ""),
+ page_type=entry.get("page_type"),
)
)
return steps
@@ -208,16 +272,22 @@ def _tour_from_knowledge_graph(kg: dict) -> list[ArchTourStep]:
def _layers_from_db(db_layers: list, node_ids: set[str]) -> list[dict]:
layers = []
- for row in db_layers:
+ for i, row in enumerate(db_layers):
raw_ids = json.loads(row.node_ids_json) if row.node_ids_json else []
mapped = [nid.removeprefix("file:") for nid in raw_ids]
matched = [nid for nid in mapped if nid in node_ids]
- layers.append({
- "id": row.layer_id,
- "name": row.name,
- "description": row.description or "",
- "node_ids": matched,
- })
+ raw_sub_groups_json = getattr(row, "sub_groups_json", None)
+ raw_sub_groups = json.loads(raw_sub_groups_json) if raw_sub_groups_json else []
+ layers.append(
+ {
+ "id": row.layer_id,
+ "name": row.name,
+ "description": row.description or "",
+ "node_ids": matched,
+ "display_order": getattr(row, "display_order", i),
+ "sub_groups": _sub_groups_from_raw(raw_sub_groups, node_ids),
+ }
+ )
return layers
@@ -226,26 +296,70 @@ def _tour_from_db(db_steps: list) -> list[ArchTourStep]:
for row in db_steps:
node_ids = json.loads(row.node_ids_json) if row.node_ids_json else []
node_ids = [nid.removeprefix("file:") for nid in node_ids]
+ target_path = getattr(row, "target_path", None)
+ if not node_ids and target_path:
+ node_ids = [target_path]
steps.append(
ArchTourStep(
order=row.step_order,
title=row.title,
description=row.description or "",
node_ids=node_ids,
+ target_path=target_path,
+ layer_id=getattr(row, "layer_id", None),
+ reason=getattr(row, "reason", "") or "",
+ depth=getattr(row, "depth", None),
+ kind=getattr(row, "kind", "") or "",
+ page_type=getattr(row, "page_type", None),
)
)
return steps
async def _migrate_kg_file_to_db(
- session: AsyncSession, repo_id: str, kg: dict,
+ caller_session: AsyncSession,
+ repo_id: str,
+ kg: dict,
) -> None:
- layers = kg.get("layers", [])
- if layers:
- await upsert_kg_layers(session, repo_id, layers)
- tour = kg.get("tour", [])
- if tour:
- await upsert_kg_tour_steps(session, repo_id, tour)
+ """Auto-migrate a file-based KG into the DB on first read.
+
+ Runs in its OWN session (a fresh sessionmaker bound to the caller's
+ engine) so a rollback here can never clobber writes that share the
+ request-scoped caller session. The migration is delete-then-insert and
+ carries no concurrency guard, so two concurrent first-readers can race to
+ the unique constraints; we treat an ``IntegrityError`` as "another request
+ migrated first" — the DB now holds the curated rows either way, so we
+ swallow it and let the caller fall back to reading those rows. Any other
+ failure propagates to the caller, which degrades to the file-based KG.
+ """
+ # ``caller_session.bind`` is the AsyncEngine; ``get_bind()`` would hand back
+ # the sync engine, which ``async_sessionmaker`` rejects.
+ migration_factory = async_sessionmaker(
+ caller_session.bind, expire_on_commit=False, class_=AsyncSession
+ )
+ async with migration_factory() as session:
+ try:
+ layers = kg.get("layers", [])
+ if layers:
+ await upsert_kg_layers(session, repo_id, layers)
+ tour = kg.get("tour", [])
+ if tour:
+ await upsert_kg_tour_steps(session, repo_id, tour)
+ project = kg.get("project") or {}
+ if project.get("entry_points"):
+ await upsert_kg_project_meta(
+ session,
+ repo_id,
+ entry_points=project["entry_points"],
+ entry_candidates=project.get("entry_candidates", []),
+ )
+ node_meta = file_node_meta_from_kg_nodes(kg.get("nodes", []))
+ if node_meta:
+ await upsert_kg_node_meta(session, repo_id, node_meta)
+ await session.commit()
+ except IntegrityError:
+ # Concurrent first-reader already migrated; their rows win.
+ await session.rollback()
async def build_architecture_view(
@@ -254,14 +368,22 @@ async def build_architecture_view(
include_symbols: bool = False,
) -> ArchitectureView:
from . import load_repo
+
repo = await load_repo(session, repo_id)
empty = ArchitectureView(
project_name=repo.name if repo else repo_id,
project_description="",
- layers=[], nodes=[], edges=[], tour=[],
- total_files=0, total_symbols=0, total_edges=0,
- languages=[], frameworks=[], external_systems=[],
+ layers=[],
+ nodes=[],
+ edges=[],
+ tour=[],
+ total_files=0,
+ total_symbols=0,
+ total_edges=0,
+ languages=[],
+ frameworks=[],
+ external_systems=[],
)
if repo is None:
return empty
@@ -279,9 +401,7 @@ async def build_architecture_view(
file_nodes = [n for n in all_nodes if n.node_type == "file"]
# -- Load edges --
- edge_result = await session.execute(
- select(GraphEdge).where(GraphEdge.repository_id == repo_id)
- )
+ edge_result = await session.execute(select(GraphEdge).where(GraphEdge.repository_id == repo_id))
all_edges: list[GraphEdge] = list(edge_result.scalars())
in_degree: dict[str, int] = defaultdict(int)
@@ -297,9 +417,7 @@ async def build_architecture_view(
git_result = await session.execute(
select(GitMetadata).where(GitMetadata.repository_id == repo_id)
)
- git_by_path: dict[str, GitMetadata] = {
- gm.file_path: gm for gm in git_result.scalars()
- }
+ git_by_path: dict[str, GitMetadata] = {gm.file_path: gm for gm in git_result.scalars()}
# -- Enrichment: dead code --
dead_result = await session.execute(
@@ -350,45 +468,60 @@ async def build_architecture_view(
kg = _load_knowledge_graph(candidate)
break
if kg and kg.get("layers"):
+ # Migration runs in its own session and commits there; a failure
+ # cannot roll back the caller's session. On failure we degrade to
+ # serving this read from the already-loaded file-based KG.
try:
await _migrate_kg_file_to_db(session, repo_id, kg)
- await session.flush()
except Exception:
logger.warning("kg_file_to_db_migration_failed", exc_info=True)
- await session.rollback()
raw_layers = _layers_from_knowledge_graph(kg, node_id_set)
elif any(n.community_id and n.community_id > 0 for n in file_nodes):
raw_layers = _layers_from_communities(file_nodes)
else:
raw_layers = _layers_from_directories(file_nodes)
+ # -- Curated node meta (type/summary/tags) — file if just loaded, else DB --
+ # node_id -> (node_type, summary, tags)
+ curated_meta: dict[str, tuple[str, str, list[str]]] = {}
+ if kg:
+ for meta in file_node_meta_from_kg_nodes(kg.get("nodes", [])):
+ curated_meta[meta["node_id"]] = (meta["node_type"], meta["summary"], meta["tags"])
+ else:
+ for row in await get_kg_node_meta(session, repo_id):
+ row_tags = json.loads(row.tags_json) if row.tags_json else []
+ curated_meta[row.node_id] = (row.node_type, row.summary, row_tags)
+
# -- Build ArchNodes --
arch_nodes: list[ArchNode] = []
for i, n in enumerate(all_nodes):
gm = git_by_path.get(n.node_id) or git_by_path.get(n.file_path or "")
page_summary = _find_page_summary(n.node_id)
+ curated_type, curated_summary, curated_tags = curated_meta.get(n.node_id, ("", "", []))
if n.node_type == "file":
name = n.node_id.rsplit("/", 1)[-1]
file_path = n.node_id
line_range = None
- summary = page_summary or f"Handles {_top_dir(n.node_id)} logic"
+ summary = curated_summary or page_summary or f"Handles {_top_dir(n.node_id)} logic"
else:
name = n.name or n.node_id.rsplit("::", 1)[-1]
file_path = n.file_path
line_range = (n.start_line, n.end_line) if n.start_line and n.end_line else None
- summary = page_summary or ""
+ summary = curated_summary or page_summary or ""
arch_nodes.append(
ArchNode(
id=n.node_id,
- node_type=n.node_type,
+ node_type=curated_type or n.node_type,
name=name,
file_path=file_path,
line_range=line_range,
summary=summary,
- complexity=_classify_complexity(n.symbol_count, (n.end_line or 0) - (n.start_line or 0)),
- tags=_tags_for(n.node_id, n.node_type, n.language),
+ complexity=_classify_complexity(
+ n.symbol_count, (n.end_line or 0) - (n.start_line or 0)
+ ),
+ tags=curated_tags or _tags_for(n.node_id, n.node_type, n.language),
language=n.language or None,
pagerank=n.pagerank,
pagerank_percentile=round(pr_pcts.get(i, 0.0), 1),
@@ -433,10 +566,25 @@ async def build_architecture_view(
elif kg:
tour = _tour_from_knowledge_graph(kg)
+ # -- Curated entry points (file if just loaded, else DB; empty otherwise) --
+ entry_points: list[str] = []
+ entry_candidates: list[str] = []
+ if kg:
+ project = kg.get("project") or {}
+ entry_points = list(project.get("entry_points", []))
+ entry_candidates = list(project.get("entry_candidates", []))
+ else:
+ project_meta = await get_kg_project_meta(session, repo_id)
+ if project_meta:
+ entry_points = json.loads(project_meta.entry_points_json or "[]")
+ entry_candidates = json.loads(project_meta.entry_candidates_json or "[]")
+ entry_points = [p for p in entry_points if p in node_id_set]
+ entry_candidates = [p for p in entry_candidates if p in node_id_set]
+
# -- Finalize layers with complexity distribution --
node_complexity: dict[str, str] = {an.id: an.complexity for an in arch_nodes}
arch_layers: list[ArchLayer] = []
- for rl in raw_layers:
+ for idx, rl in enumerate(raw_layers):
dist: dict[str, int] = {"simple": 0, "moderate": 0, "complex": 0}
for nid in rl["node_ids"]:
c = node_complexity.get(nid, "simple")
@@ -450,6 +598,11 @@ async def build_architecture_view(
file_count=len(rl["node_ids"]),
complexity_distribution=dist,
health_score=None,
+ sub_groups=[
+ ArchSubGroup(id=sg["id"], name=sg["name"], node_ids=sg["node_ids"])
+ for sg in rl.get("sub_groups", [])
+ ],
+ display_order=rl.get("display_order", idx),
)
)
@@ -474,4 +627,6 @@ async def build_architecture_view(
languages=sorted(langs),
frameworks=sorted(fw_names),
external_systems=externals,
+ entry_points=entry_points,
+ entry_candidates=entry_candidates,
)
diff --git a/packages/server/src/repowise/server/services/c4_builder/mermaid.py b/packages/server/src/repowise/server/services/c4_builder/mermaid.py
index 4d4ca4b81..49b34dad9 100644
--- a/packages/server/src/repowise/server/services/c4_builder/mermaid.py
+++ b/packages/server/src/repowise/server/services/c4_builder/mermaid.py
@@ -9,12 +9,24 @@ Mermaid's C4 plugin syntax: https://mermaid.js.org/syntax/c4.html
from __future__ import annotations
import re
+from collections import defaultdict
from .models import C4L1, C4L2, C4L3, Container, ExternalSystemView
-
_SAFE = re.compile(r"[^a-zA-Z0-9_]")
+# Beyond this many external systems the L1/L2 diagram groups them into labelled
+# category boundaries ("Frameworks", "Services & Infrastructure", …) instead of
+# rendering N loose boxes, so the context view stays legible (plan §Phase 5).
+_EXTERNAL_GROUP_THRESHOLD = 8
+_CATEGORY_TITLES: dict[str, str] = {
+ "framework": "Frameworks",
+ "service": "Services & Infrastructure",
+ "tool": "Tools",
+ "library": "Libraries",
+}
+_CATEGORY_ORDER = ("framework", "service", "tool", "library")
+
def _sid(node_id: str) -> str:
"""Mermaid identifiers must be alnum/underscore."""
@@ -46,13 +58,7 @@ def to_mermaid_l1(view: C4L1) -> str:
f'"{_q(view.system.description or "System under analysis")}")'
)
- for ext in view.external_systems:
- kind = _ext_kind(ext.category)
- version = f" {ext.version}" if ext.version else ""
- lines.append(
- f' {kind}({_sid(ext.id)}, "{_q(ext.display_name)}", '
- f'"{_q(ext.ecosystem + version)}")'
- )
+ lines.extend(_emit_externals(view.external_systems))
if view.relations:
lines.append("")
@@ -69,8 +75,7 @@ def to_mermaid_l2(view: C4L2, system_name: str) -> str:
lines.append(_container_line(c, indent=" "))
lines.append(" }")
- for ext in view.external_systems:
- lines.append(_external_line(ext))
+ lines.extend(_emit_externals(view.external_systems))
if view.relations:
lines.append("")
@@ -113,6 +118,33 @@ def _container_line(c: Container, indent: str = " ") -> str:
)
+def _emit_externals(externals: list[ExternalSystemView]) -> list[str]:
+ """Render external systems, grouping by category once there are many.
+
+ Below the threshold they stay as flat boxes (today's behaviour). Above it,
+ each non-empty category is wrapped in a labelled ``Boundary`` so the diagram
+ reads as a handful of buckets rather than a wall of dependency boxes.
+ """
+ if len(externals) <= _EXTERNAL_GROUP_THRESHOLD:
+ return [_external_line(ext) for ext in externals]
+
+ by_cat: dict[str, list[ExternalSystemView]] = defaultdict(list)
+ for ext in externals:
+ by_cat[ext.category].append(ext)
+
+ ordered = [c for c in _CATEGORY_ORDER if c in by_cat]
+ ordered += sorted(c for c in by_cat if c not in _CATEGORY_ORDER)
+
+ lines: list[str] = []
+ for cat in ordered:
+ title = _CATEGORY_TITLES.get(cat, f"{cat.title()}s")
+ lines.append(f' Boundary(extgrp_{_sid(cat)}, "{_q(title)}") {{')
+ for ext in sorted(by_cat[cat], key=lambda e: e.name):
+ lines.append(" " + _external_line(ext))
+ lines.append(" }")
+ return lines
+
+
def _external_line(ext: ExternalSystemView) -> str:
kind = _ext_kind(ext.category)
version = f" {ext.version}" if ext.version else ""
diff --git a/packages/server/src/repowise/server/services/c4_builder/models.py b/packages/server/src/repowise/server/services/c4_builder/models.py
index 6af5ed726..b4a52b0aa 100644
--- a/packages/server/src/repowise/server/services/c4_builder/models.py
+++ b/packages/server/src/repowise/server/services/c4_builder/models.py
@@ -110,6 +110,16 @@ class C4L3:
# ---------------------------------------------------------------------------
+@dataclass(frozen=True)
+class ArchSubGroup:
+ """A curated sub-group inside a layer (drill-down tier between layer
+ cards and file cards). Produced by the KG curation pass."""
+
+ id: str
+ name: str
+ node_ids: list[str]
+
+
@dataclass(frozen=True)
class ArchLayer:
id: str
@@ -119,6 +129,8 @@ class ArchLayer:
file_count: int
complexity_distribution: dict[str, int]
health_score: float | None
+ sub_groups: list[ArchSubGroup] = field(default_factory=list)
+ display_order: int = 0
@dataclass(frozen=True)
@@ -164,6 +176,13 @@ class ArchTourStep:
title: str
description: str
node_ids: list[str]
+ # Curated, layer-aware fields (None/empty for legacy LLM tours).
+ target_path: str | None = None
+ layer_id: str | None = None
+ reason: str = ""
+ depth: int | None = None
+ kind: str = ""
+ page_type: str | None = None
@dataclass(frozen=True)
@@ -180,3 +199,6 @@ class ArchitectureView:
languages: list[str]
frameworks: list[str]
external_systems: list[ExternalSystemView]
+ # Curated, ranked entry points (repo-relative paths; empty when uncurated).
+ entry_points: list[str] = field(default_factory=list)
+ entry_candidates: list[str] = field(default_factory=list)
diff --git a/tests/integration/test_commonjs_dead_code.py b/tests/integration/test_commonjs_dead_code.py
index 08efbd74a..48f03c7a6 100644
--- a/tests/integration/test_commonjs_dead_code.py
+++ b/tests/integration/test_commonjs_dead_code.py
@@ -78,3 +78,56 @@ def test_resolution_is_targeted_not_whole_module(graph_and_report):
graph, _ = graph_and_report
assert "svc.js::reallyDead" in graph
assert not _calls_to(graph, "svc.js::reallyDead")
+
+
+# ---------------------------------------------------------------------------
+# Chained CJS re-exports: index.js -> lib/api.js -> lib/impl.js
+# ---------------------------------------------------------------------------
+
+INDEX_JS = """'use strict';
+module.exports = require('./lib/api');
+"""
+
+API_JS = """'use strict';
+Object.assign(module.exports, require('./impl'));
+"""
+
+IMPL_JS = """function realWork() {
+ return 42;
+}
+
+module.exports = { realWork };
+"""
+
+
[email protected](scope="module")
+def chained_graph(tmp_path_factory):
+ repo = tmp_path_factory.mktemp("cjs_chain")
+ (repo / "index.js").write_text(INDEX_JS, encoding="utf-8")
+ lib = repo / "lib"
+ lib.mkdir()
+ (lib / "api.js").write_text(API_JS, encoding="utf-8")
+ (lib / "impl.js").write_text(IMPL_JS, encoding="utf-8")
+
+ traverser = FileTraverser(repo)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=repo)
+ for fi in traverser.traverse():
+ source = Path(fi.abs_path).read_bytes()
+ builder.add_file(parser.parse_file(fi, source))
+ return builder.build()
+
+
+def test_reexport_chain_produces_import_edges(chained_graph):
+ """module.exports = require(...) / Object.assign(module.exports, ...)
+ must produce real import edges (express's 2.0-edges/file gap)."""
+ assert chained_graph.has_edge("index.js", "lib/api.js")
+ assert chained_graph["index.js"]["lib/api.js"]["edge_type"] == "imports"
+ assert chained_graph.has_edge("lib/api.js", "lib/impl.js")
+
+
+def test_reexport_chain_reaches_the_implementation(chained_graph):
+ """BFS from the package root must transit the whole a -> b -> c chain."""
+ import networkx as nx
+
+ assert nx.has_path(chained_graph, "index.js", "lib/impl.js")
diff --git a/tests/unit/analysis/kg_fixtures.py b/tests/unit/analysis/kg_fixtures.py
new file mode 100644
index 000000000..499930ef4
--- /dev/null
+++ b/tests/unit/analysis/kg_fixtures.py
@@ -0,0 +1,137 @@
+"""Shared synthetic-repo builders for KG curation/invariant tests.
+
+Not a test module (no ``test_`` prefix → not collected). Builds parsed files +
+a mock ``GraphBuilder`` and runs the real skeleton + curation, so invariant
+tests exercise the production code paths.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+from repowise.core.analysis.kg_curation import curate_knowledge_graph
+from repowise.core.analysis.knowledge_graph import (
+ KnowledgeGraphResult,
+ build_knowledge_graph_skeleton,
+)
+
+
+@dataclass
+class FakeFileInfo:
+ path: str
+ language: str = "python"
+ size_bytes: int = 1000
+ is_test: bool = False
+ is_config: bool = False
+ is_api_contract: bool = False
+ is_entry_point: bool = False
+ line_count: int = 100
+
+
+@dataclass
+class FakeSymbol:
+ name: str = "thing"
+ kind: str = "function"
+ start_line: int = 1
+ end_line: int = 10
+
+
+@dataclass
+class FakeParsedFile:
+ file_info: FakeFileInfo
+ symbols: list = field(default_factory=list)
+ imports: list = field(default_factory=list)
+ exports: list = field(default_factory=list)
+
+
+def _community_info(cid: int, label: str, members: list[str]):
+ return SimpleNamespace(
+ community_id=cid,
+ label=label,
+ members=members,
+ size=len(members),
+ cohesion=0.8,
+ dominant_language="python",
+ )
+
+
+def build_repo(
+ paths: list[str],
+ *,
+ tests: set[str] | None = None,
+ entries: set[str] | None = None,
+ edges: list[tuple[str, str]] | None = None,
+ barrels: set[str] | None = None,
+):
+ """Build a synthetic repo: parsed files + a mock GraphBuilder."""
+ import networkx as nx
+
+ tests = tests or set()
+ entries = entries or set()
+ barrels = barrels or set()
+
+ parsed = []
+ g = nx.DiGraph()
+ for p in paths:
+ is_test, is_entry = p in tests, p in entries
+ if p in barrels:
+ pf = FakeParsedFile(
+ FakeFileInfo(p, is_test=is_test, is_entry_point=is_entry),
+ symbols=[],
+ imports=[SimpleNamespace(is_reexport=True)],
+ exports=["A"],
+ )
+ else:
+ pf = FakeParsedFile(
+ FakeFileInfo(p, is_test=is_test, is_entry_point=is_entry),
+ symbols=[FakeSymbol()],
+ )
+ parsed.append(pf)
+ attrs = {"node_type": "file", "language": "python"}
+ if is_test:
+ attrs["is_test"] = True
+ if is_entry:
+ attrs["is_entry_point"] = True
+ g.add_node(p, **attrs)
+ for u, v in edges or []:
+ g.add_edge(u, v, edge_type="imports", confidence=1.0)
+
+ # One community per file → the "103 layers" pathology curation must absorb.
+ communities = {p: i for i, p in enumerate(paths)}
+ infos = {i: _community_info(i, f"cluster_{i}", [p]) for i, p in enumerate(paths)}
+ pagerank = {p: 1.0 / max(len(paths), 1) for p in paths}
+
+ builder = MagicMock()
+ builder.graph.return_value = g
+ builder.pagerank.return_value = pagerank
+ builder.betweenness_centrality.return_value = {}
+ builder.community_detection.return_value = communities
+ builder.community_info.return_value = infos
+ repo_structure = SimpleNamespace(
+ is_monorepo=True, total_files=len(paths), entry_points=sorted(entries)
+ )
+ return SimpleNamespace(parsed=parsed, builder=builder, repo_structure=repo_structure)
+
+
+def build_skeleton(repo) -> KnowledgeGraphResult:
+ return build_knowledge_graph_skeleton(
+ parsed_files=repo.parsed,
+ graph_builder=repo.builder,
+ repo_structure=repo.repo_structure,
+ tech_stack=[],
+ external_systems=[],
+ )
+
+
+def curate(repo, **kw) -> KnowledgeGraphResult:
+ return curate_knowledge_graph(
+ build_skeleton(repo),
+ parsed_files=repo.parsed,
+ graph_builder=repo.builder,
+ repo_structure=repo.repo_structure,
+ community_info=repo.builder.community_info(),
+ enabled=kw.pop("enabled", True),
+ **kw,
+ )
diff --git a/tests/unit/analysis/test_community_labels.py b/tests/unit/analysis/test_community_labels.py
new file mode 100644
index 000000000..1eeff6943
--- /dev/null
+++ b/tests/unit/analysis/test_community_labels.py
@@ -0,0 +1,115 @@
+"""Community label hygiene: repo-dominant namespace segments never become labels.
+
+The legacy failure mode: a namespace dir present in ~every path (the repo's
+own name, ``src``, ``packages``) is not in the hardcoded ``_GENERIC_SEGMENTS``
+list, so labels degrade to ``repowise (161)`` and flipped twins like
+``ingestion/repowise`` / ``repowise/ingestion``. Labeling now strips
+data-driven dominant segments (shared with module naming in kg_curation).
+"""
+
+from __future__ import annotations
+
+import itertools
+
+import networkx as nx
+
+from repowise.core.analysis.communities import (
+ CommunityInfo,
+ _deduplicate_labels,
+ _heuristic_label,
+ detect_file_communities,
+)
+from repowise.core.analysis.kg_curation import dominant_segments
+
+
+def _graph(paths: list[str], edges: list[tuple[str, str]]) -> nx.DiGraph:
+ g = nx.DiGraph()
+ for p in paths:
+ g.add_node(p, node_type="file", language="python")
+ for u, v in edges:
+ g.add_edge(u, v, edge_type="imports")
+ return g
+
+
+class TestHeuristicLabelStripping:
+ def test_dominant_segment_never_becomes_label(self):
+ # Dominance is repo-wide: "acme"/"src" appear in every path,
+ # "ingestion" only in this community's slice.
+ members = [f"acme/src/ingestion/file{i}.py" for i in range(5)]
+ repo_paths = members + [f"acme/src/web/w{i}.py" for i in range(5)]
+ generic = frozenset(s.lower() for s in dominant_segments(repo_paths))
+ assert generic == {"acme", "src"}
+ label = _heuristic_label(members, 0, generic)
+ assert label == "ingestion"
+
+ def test_flipped_twins_collapse(self):
+ # Without stripping these two communities label as "acme/ingestion"
+ # and "ingestion/acme" — flipped twins. With stripping both reduce
+ # to their informative segment.
+ ingest = [f"acme/src/ingestion/p{i}.py" for i in range(4)]
+ persist = [f"acme/src/persistence/p{i}.py" for i in range(4)]
+ generic = frozenset(
+ s.lower() for s in dominant_segments(ingest + persist)
+ )
+ assert "acme" in generic and "src" in generic
+ assert _heuristic_label(ingest, 0, generic) == "ingestion"
+ assert _heuristic_label(persist, 1, generic) == "persistence"
+
+ def test_no_extra_generic_preserves_legacy_behavior(self):
+ # Default empty set: byte-identical to the pre-change heuristic.
+ paths = [f"web/components/c{i}.tsx" for i in range(4)]
+ assert _heuristic_label(paths, 0) == _heuristic_label(
+ paths, 0, frozenset()
+ )
+
+ def test_stem_fallback_skips_dominant_segment(self):
+ # Strategy 3 (filename stems) must not resurrect a stripped segment.
+ paths = ["acme/acme.py", "acme/acme.pyi"]
+ label = _heuristic_label(paths, 7, frozenset({"acme"}))
+ assert label == "cluster_7"
+
+
+class TestDeduplicateLabels:
+ def test_sub_label_disambiguation_skips_generic(self):
+ a = CommunityInfo(
+ community_id=0,
+ label="ingestion",
+ members=[f"acme/src/ingestion/resolvers/r{i}.py" for i in range(4)],
+ size=4,
+ cohesion=0.5,
+ dominant_language="python",
+ )
+ b = CommunityInfo(
+ community_id=1,
+ label="ingestion",
+ members=[f"acme/src/ingestion/parsing/p{i}.py" for i in range(4)],
+ size=4,
+ cohesion=0.5,
+ dominant_language="python",
+ )
+ info = {0: a, 1: b}
+ _deduplicate_labels(info, frozenset({"acme", "src"}))
+ labels = {info[0].label, info[1].label}
+ # Disambiguated by informative sub-segments, never by "acme"/"src".
+ assert labels == {"ingestion/resolvers", "ingestion/parsing"}
+ for label in labels:
+ assert "acme" not in label and "src" not in label
+
+
+class TestDetectFileCommunitiesLabels:
+ def test_end_to_end_labels_strip_repo_namespace(self):
+ # Two clusters under a shared monorepo namespace.
+ ingest = [f"acme/src/acmepkg/ingestion/m{i}.py" for i in range(6)]
+ web = [f"acme/src/acmepkg/web/w{i}.py" for i in range(6)]
+ edges = list(itertools.pairwise(ingest)) + list(itertools.pairwise(web))
+ g = _graph(ingest + web, edges)
+ _, info, _ = detect_file_communities(g)
+ labels = [ci.label for ci in info.values()]
+ for label in labels:
+ for noise in ("acme", "src", "acmepkg"):
+ assert noise not in label.split("/"), (
+ f"dominant segment {noise!r} leaked into label {label!r}"
+ )
+ # The informative segments survive somewhere in the labels.
+ joined = " ".join(labels)
+ assert "ingestion" in joined and "web" in joined
diff --git a/tests/unit/analysis/test_kg_curation.py b/tests/unit/analysis/test_kg_curation.py
new file mode 100644
index 000000000..846ee253b
--- /dev/null
+++ b/tests/unit/analysis/test_kg_curation.py
@@ -0,0 +1,1241 @@
+"""Tests for the KG curation/presentation pass (``kg_curation``).
+
+Grows phase-by-phase. Phase 0 locks the seam: a no-op when the flag is off, a
+flag reader, and the AST-graph-untouched guard.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+
+from repowise.core.analysis.kg_curation import (
+ _dominant_language,
+ curate_knowledge_graph,
+ curation_enabled,
+)
+from repowise.core.analysis.knowledge_graph import (
+ KnowledgeGraphResult,
+ build_knowledge_graph_skeleton,
+)
+
+# ---------------------------------------------------------------------------
+# Fixtures / fakes
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class FakeFileInfo:
+ path: str
+ language: str = "python"
+ size_bytes: int = 1000
+ is_test: bool = False
+ is_config: bool = False
+ is_api_contract: bool = False
+ is_entry_point: bool = False
+ line_count: int = 100
+
+
+@dataclass
+class FakeSymbol:
+ name: str = "my_func"
+ kind: str = "function"
+ start_line: int = 1
+ end_line: int = 10
+ is_reexport: bool = False
+
+
+@dataclass
+class FakeParsedFile:
+ file_info: FakeFileInfo
+ symbols: list = field(default_factory=list)
+ imports: list = field(default_factory=list)
+ exports: list = field(default_factory=list)
+
+
+def _make_graph_builder(
+ nodes: dict[str, dict],
+ edges: list[tuple[str, str, dict]],
+ communities: dict[str, int],
+ community_infos: dict[int, Any],
+ pagerank: dict[str, float],
+ betweenness: dict[str, float] | None = None,
+):
+ import networkx as nx
+
+ g = nx.DiGraph()
+ for nid, data in nodes.items():
+ g.add_node(nid, **data)
+ for u, v, data in edges:
+ g.add_edge(u, v, **data)
+
+ builder = MagicMock()
+ builder.graph.return_value = g
+ builder.pagerank.return_value = pagerank
+ builder.betweenness_centrality.return_value = betweenness or {}
+ builder.community_detection.return_value = communities
+ builder.community_info.return_value = community_infos
+ return builder
+
+
+def _community_info(cid: int, label: str, members: list[str]):
+ return SimpleNamespace(
+ community_id=cid,
+ label=label,
+ members=members,
+ size=len(members),
+ cohesion=0.8,
+ dominant_language="python",
+ )
+
+
+def simple_repo():
+ """A tiny three-file repo: entry, core, test."""
+ parsed = [
+ FakeParsedFile(
+ FakeFileInfo("src/main.py", is_entry_point=True), symbols=[FakeSymbol("main")]
+ ),
+ FakeParsedFile(FakeFileInfo("src/core.py"), symbols=[FakeSymbol("Core", "class")]),
+ FakeParsedFile(
+ FakeFileInfo("tests/test_main.py", is_test=True), symbols=[FakeSymbol("test_main")]
+ ),
+ ]
+ nodes = {
+ "src/main.py": {"node_type": "file", "language": "python", "is_entry_point": True},
+ "src/core.py": {"node_type": "file", "language": "python"},
+ "tests/test_main.py": {"node_type": "file", "language": "python", "is_test": True},
+ }
+ edges = [
+ ("src/main.py", "src/core.py", {"edge_type": "imports", "confidence": 1.0}),
+ ("tests/test_main.py", "src/main.py", {"edge_type": "imports", "confidence": 1.0}),
+ ]
+ communities = {"src/main.py": 0, "src/core.py": 0, "tests/test_main.py": 1}
+ infos = {
+ 0: _community_info(0, "src/core", ["src/main.py", "src/core.py"]),
+ 1: _community_info(1, "tests", ["tests/test_main.py"]),
+ }
+ pagerank = {"src/main.py": 0.5, "src/core.py": 0.3, "tests/test_main.py": 0.2}
+ builder = _make_graph_builder(nodes, edges, communities, infos, pagerank)
+ repo_structure = SimpleNamespace(
+ is_monorepo=False,
+ total_files=3,
+ entry_points=["src/main.py"],
+ )
+ return SimpleNamespace(parsed=parsed, builder=builder, repo_structure=repo_structure)
+
+
+def _build_skeleton(repo) -> KnowledgeGraphResult:
+ return build_knowledge_graph_skeleton(
+ parsed_files=repo.parsed,
+ graph_builder=repo.builder,
+ repo_structure=repo.repo_structure,
+ tech_stack=[],
+ external_systems=[],
+ )
+
+
+def _curate(repo, **kw) -> KnowledgeGraphResult:
+ return curate_knowledge_graph(
+ _build_skeleton(repo),
+ parsed_files=repo.parsed,
+ graph_builder=repo.builder,
+ repo_structure=repo.repo_structure,
+ community_info=repo.builder.community_info(),
+ **kw,
+ )
+
+
+def build_repo(
+ paths: list[str],
+ *,
+ tests: set[str] | None = None,
+ entries: set[str] | None = None,
+ edges: list[tuple[str, str]] | None = None,
+ barrels: set[str] | None = None,
+ pagerank: dict[str, float] | None = None,
+ betweenness: dict[str, float] | None = None,
+):
+ """Build a synthetic repo (parsed files + mock graph builder) from paths."""
+ tests = tests or set()
+ entries = entries or set()
+ barrels = barrels or set()
+
+ parsed = []
+ nodes: dict[str, dict] = {}
+ for p in paths:
+ is_test = p in tests
+ is_entry = p in entries
+ # Language follows the extension (registry truth) so polyglot
+ # fixtures behave like real repos; bare paths default to python.
+ from pathlib import PurePosixPath
+
+ from repowise.core.ingestion.languages.registry import REGISTRY
+
+ lang = REGISTRY.from_extension(PurePosixPath(p).suffix)
+ if lang == "unknown":
+ lang = "python"
+ if p in barrels:
+ # A re-export shell: no runtime symbols, exports names only.
+ pf = FakeParsedFile(
+ FakeFileInfo(p, language=lang, is_test=is_test, is_entry_point=is_entry),
+ symbols=[],
+ imports=[SimpleNamespace(is_reexport=True)],
+ exports=["A", "B"],
+ )
+ else:
+ pf = FakeParsedFile(
+ FakeFileInfo(p, language=lang, is_test=is_test, is_entry_point=is_entry),
+ symbols=[FakeSymbol(name="thing", kind="function")],
+ )
+ parsed.append(pf)
+ nodes[p] = {"node_type": "file", "language": lang}
+ if is_test:
+ nodes[p]["is_test"] = True
+ if is_entry:
+ nodes[p]["is_entry_point"] = True
+
+ graph_edges = [(u, v, {"edge_type": "imports", "confidence": 1.0}) for u, v in (edges or [])]
+ communities = {p: 0 for p in paths}
+ infos = {0: _community_info(0, "all", list(paths))}
+ pr = pagerank or {p: 1.0 / max(len(paths), 1) for p in paths}
+ builder = _make_graph_builder(nodes, graph_edges, communities, infos, pr, betweenness)
+ repo_structure = SimpleNamespace(
+ is_monorepo=True, total_files=len(paths), entry_points=sorted(entries)
+ )
+ return SimpleNamespace(parsed=parsed, builder=builder, repo_structure=repo_structure)
+
+
+def large_repo():
+ """A realistically-shaped monorepo: several layers, two mega-layers."""
+ paths: list[str] = []
+ # Service mega-layer (core/*) spanning sub-dirs → should sub-split.
+ for sub in ("ingestion", "analysis", "generation"):
+ paths += [f"packages/core/src/repowise/core/{sub}/mod{i}.py" for i in range(24)]
+ # UI mega-layer, spanning sub-dirs → should also sub-split.
+ for sub in ("buttons", "forms", "layout"):
+ paths += [f"packages/ui/src/components/{sub}/C{i}.tsx" for i in range(24)]
+ # CLI (edge case A — must not be Application).
+ paths += [f"packages/cli/src/repowise/cli/commands/cmd{i}.py" for i in range(20)]
+ # API, Data, Config, Test, Utility — smaller named layers.
+ paths += [f"src/api/route{i}.py" for i in range(12)]
+ paths += [f"src/models/model{i}.py" for i in range(10)]
+ paths += [f"src/utils/util{i}.py" for i in range(8)]
+ paths += [f"config/conf{i}.yaml" for i in range(6)]
+ tests = {f"tests/unit/test_{i}.py" for i in range(30)}
+ paths += sorted(tests)
+ # A realistic monorepo HAS imports: wire a dense chain so the honest-
+ # degradation detector classifies it as flow, not structural.
+ code = [p for p in paths if not p.endswith(".yaml") and p not in tests]
+ edges = [
+ (code[i], code[i + step])
+ for step in (1, 2, 3)
+ for i in range(len(code) - step)
+ ]
+ return build_repo(paths, tests=tests, edges=edges)
+
+
+# ---------------------------------------------------------------------------
+# Phase 0 — the seam
+# ---------------------------------------------------------------------------
+
+
+class TestCurationFlag:
+ def test_default_on(self, monkeypatch):
+ # Flipped at the cross-language acceptance gate: the 38-repo matrix
+ # is the evidence; the env var is an opt-out now.
+ monkeypatch.delenv("REPOWISE_KG_CURATION", raising=False)
+ assert curation_enabled() is True
+
+ @pytest.mark.parametrize("val", ["1", "true", "TRUE", "yes", "on"])
+ def test_truthy_values_enable(self, monkeypatch, val):
+ monkeypatch.setenv("REPOWISE_KG_CURATION", val)
+ assert curation_enabled() is True
+
+ @pytest.mark.parametrize("val", ["0", "false", "FALSE", "no", "off"])
+ def test_falsy_values_disable(self, monkeypatch, val):
+ monkeypatch.setenv("REPOWISE_KG_CURATION", val)
+ assert curation_enabled() is False
+
+
+class TestIdentityPass:
+ def test_noop_returns_input_unchanged(self, simple_repo):
+ kg = _build_skeleton(simple_repo)
+ before = kg.to_dict()
+ out = curate_knowledge_graph(
+ kg,
+ parsed_files=simple_repo.parsed,
+ graph_builder=simple_repo.builder,
+ repo_structure=simple_repo.repo_structure,
+ community_info=simple_repo.builder.community_info(),
+ enabled=False,
+ )
+ assert out is kg
+ assert out.to_dict() == before
+
+ def test_ast_graph_untouched(self, simple_repo):
+ """The §4D guard: graph node/edge counts identical pre/post curation."""
+ g = simple_repo.builder.graph()
+ before = (g.number_of_nodes(), g.number_of_edges())
+ _curate(simple_repo, enabled=True)
+ g = simple_repo.builder.graph()
+ assert (g.number_of_nodes(), g.number_of_edges()) == before
+
+
+# ---------------------------------------------------------------------------
+# Phase 1 — curated layers
+# ---------------------------------------------------------------------------
+
+
+def _layer_names(kg) -> set[str]:
+ return {layer["name"] for layer in kg.layers}
+
+
+def _file_node_count(kg) -> int:
+ return sum(1 for n in kg.nodes if n["id"].startswith("file:"))
+
+
+class TestCuratedLayers:
+ def test_flag_off_keeps_community_layers(self, large_repo):
+ kg = _curate(large_repo, enabled=False)
+ # The skeleton's community layers: one community "all" → one layer.
+ assert _layer_names(kg) == {"all"}
+
+ def test_layer_count_bounded(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ assert 6 <= len(kg.layers) <= 15
+
+ def test_partition_invariant(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ seen: set[str] = set()
+ for layer in kg.layers:
+ for nid in layer["nodeIds"]:
+ assert nid not in seen, "a file appears in two layers"
+ seen.add(nid)
+ assert len(seen) == _file_node_count(kg), "every file in exactly one layer"
+
+ def test_no_singleton_spam(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ singletons = sum(1 for layer in kg.layers if len(layer["nodeIds"]) == 1)
+ assert singletons / len(kg.layers) < 0.10
+
+ def test_cli_is_its_own_layer(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ assert "CLI" in _layer_names(kg)
+ assert "Application" not in _layer_names(kg) # nothing falls through here
+
+ def test_mega_layers_sub_split(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ by_name = {layer["name"]: layer for layer in kg.layers}
+ for mega in ("Service", "UI"):
+ sub = by_name[mega].get("subGroups")
+ assert sub and len(sub) >= 2, f"{mega} should sub-split"
+ # Sub-groups partition their parent layer.
+ sub_ids = [nid for grp in sub for nid in grp["nodeIds"]]
+ assert sorted(sub_ids) == sorted(by_name[mega]["nodeIds"])
+
+ def test_largest_primary_layer_within_bound(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ total = _file_node_count(kg)
+ largest = max(len(layer["nodeIds"]) for layer in kg.layers)
+ assert largest / total <= 0.35
+
+ def test_layers_are_dependency_ordered(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ orders = [layer["display_order"] for layer in kg.layers]
+ assert orders == list(range(len(kg.layers)))
+
+ def test_deterministic(self, large_repo):
+ a = _curate(large_repo, enabled=True)
+ b = _curate(large_repo, enabled=True)
+ assert a.layers == b.layers
+
+
+class TestDominantLanguageDeterminism:
+ def test_empty_input_returns_empty(self):
+ assert _dominant_language([]) == ""
+
+ def test_clear_majority_wins(self):
+ assert _dominant_language(["python", "python", "go"]) == "python"
+
+ def test_tie_is_order_independent(self):
+ # Counter.most_common breaks count ties by insertion order, which is
+ # ingestion-completion-order nondeterministic and reaches persisted
+ # output (graph_mode + tour prose). The same multiset must yield the
+ # same dominant language whatever order it was accumulated in.
+ forward = _dominant_language(["go", "go", "python", "python"])
+ reverse = _dominant_language(["python", "python", "go", "go"])
+ assert forward == reverse
+
+
+# ---------------------------------------------------------------------------
+# Phase 2 — entry-point precision
+# ---------------------------------------------------------------------------
+
+
+def entry_repo():
+ """Real runtime entries plus re-export barrels, all flagged entry_point."""
+ reals = [f"src/app{i}/main.py" for i in range(12)]
+ barrels = {f"packages/p{i}/index.ts" for i in range(5)}
+ paths = reals + sorted(barrels)
+ entries = set(reals) | barrels
+ # Give barrels deliberately high PageRank — they must still be demoted.
+ pagerank = {p: (12 - i) / 100.0 for i, p in enumerate(reals)}
+ for b in barrels:
+ pagerank[b] = 0.9
+ return build_repo(paths, entries=entries, barrels=barrels, pagerank=pagerank)
+
+
+def _project(kg) -> dict:
+ return kg.project
+
+
+class TestEntryPointPrecision:
+ def test_barrels_demoted_in_presentation(self, entry_repo):
+ kg = _curate(entry_repo, enabled=True)
+ for node in kg.nodes:
+ if node.get("filePath", "").endswith("index.ts"):
+ assert "entry_point" not in node["tags"]
+ assert "barrel" in node["tags"]
+
+ def test_no_barrel_in_surfaced_set(self, entry_repo):
+ kg = _curate(entry_repo, enabled=True)
+ assert all(not p.endswith("index.ts") for p in _project(kg)["entry_points"])
+ assert all(not p.endswith("index.ts") for p in _project(kg)["entry_candidates"])
+
+ def test_surfaced_set_capped(self, entry_repo):
+ kg = _curate(entry_repo, enabled=True)
+ assert len(_project(kg)["entry_points"]) <= 8
+
+ def test_ranked_by_centrality(self, entry_repo):
+ kg = _curate(entry_repo, enabled=True)
+ # app0 has the highest PageRank among reals → ranks first.
+ assert _project(kg)["entry_points"][0] == "src/app0/main.py"
+
+ def test_full_candidate_list_kept(self, entry_repo):
+ kg = _curate(entry_repo, enabled=True)
+ # All 12 real entries survive as candidates; 5 barrels excluded.
+ assert len(_project(kg)["entry_candidates"]) == 12
+
+ def test_ast_is_entry_point_flag_untouched(self, entry_repo):
+ """Demotion is presentation-only — the graph flag stays for dead-code."""
+ _curate(entry_repo, enabled=True)
+ g = entry_repo.builder.graph()
+ for path, data in g.nodes(data=True):
+ if path.endswith("index.ts"):
+ assert data.get("is_entry_point") is True
+
+ def test_deterministic(self, entry_repo):
+ a = _curate(entry_repo, enabled=True)
+ b = _curate(entry_repo, enabled=True)
+ assert a.project["entry_points"] == b.project["entry_points"]
+ assert a.project["entry_candidates"] == b.project["entry_candidates"]
+
+ def test_flag_off_leaves_entry_points_untouched(self, entry_repo):
+ kg = _curate(entry_repo, enabled=False)
+ assert "entry_candidates" not in kg.project
+
+ def test_ruby_spec_dir_entry_excluded_via_language(self):
+ # A Ruby file under spec/ is RSpec material whatever its name; ruby
+ # declares spec/ as an unambiguous test-dir token, so the entry-point
+ # guards must pass language to infer_layer. Without it, config.rb
+ # classifies as a runtime layer and (flagged entry_point) leaks into
+ # the surfaced entry set.
+ repo = build_repo(
+ ["src/main.rb", "spec/dummy/config.rb"],
+ entries={"src/main.rb", "spec/dummy/config.rb"},
+ )
+ kg = _curate(repo, enabled=True)
+ assert "spec/dummy/config.rb" not in kg.project["entry_points"]
+ assert "spec/dummy/config.rb" not in kg.project["entry_candidates"]
+ assert "src/main.rb" in kg.project["entry_candidates"]
+
+
+# ---------------------------------------------------------------------------
+# Phase 3 — canonical, layer-aware tour
+# ---------------------------------------------------------------------------
+
+
+def readme_repo():
+ """large_repo shape plus a real root README to anchor the tour."""
+ paths = ["README.md", "src/api/route0.py", "src/api/route1.py"]
+ paths += [f"src/models/model{i}.py" for i in range(4)]
+ paths += [f"src/utils/util{i}.py" for i in range(3)]
+ paths += [f"packages/cli/src/cli/commands/cmd{i}.py" for i in range(3)]
+ return build_repo(paths)
+
+
+def flow_repo():
+ """A repo with a real entry point, an import chain, and a test suite."""
+ paths = [
+ "README.md",
+ "src/cli/main.py",
+ "src/api/route.py",
+ "src/services/svc.py",
+ "src/models/model.py",
+ "src/utils/helpers.py",
+ "tests/conftest.py",
+ "tests/test_svc.py",
+ ]
+ edges = [
+ ("src/cli/main.py", "src/api/route.py"),
+ ("src/api/route.py", "src/services/svc.py"),
+ ("src/services/svc.py", "src/models/model.py"),
+ ("tests/test_svc.py", "src/services/svc.py"),
+ ("tests/conftest.py", "src/cli/main.py"),
+ ]
+ return build_repo(paths, entries={"src/cli/main.py"}, edges=edges)
+
+
+def _layer_ids(kg) -> set[str]:
+ return {layer["id"] for layer in kg.layers}
+
+
+class TestCuratedTour:
+ def test_within_step_budget(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ assert 0 < len(kg.tour) <= 12
+
+ def test_opens_with_overview(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ assert kg.tour[0]["kind"] == "overview"
+ assert kg.tour[0]["order"] == 1
+
+ def test_every_step_maps_to_a_curated_layer(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ ids = _layer_ids(kg)
+ for step in kg.tour:
+ if step["kind"] == "overview":
+ continue # overview maps to a layer only when a README exists
+ assert step["layer_id"] in ids
+
+ def test_covers_most_layers(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ covered = {s["layer_id"] for s in kg.tour if s["kind"] != "overview"}
+ assert len(covered) / len(_layer_ids(kg)) >= 0.90
+
+ def test_orders_are_contiguous(self, large_repo):
+ kg = _curate(large_repo, enabled=True)
+ assert [s["order"] for s in kg.tour] == list(range(1, len(kg.tour) + 1))
+
+ def test_readme_is_first_stop(self, readme_repo):
+ kg = _curate(readme_repo, enabled=True)
+ assert kg.tour[0]["kind"] == "overview"
+ assert kg.tour[0]["target_path"] == "README.md"
+
+ def test_deterministic(self, large_repo):
+ a = _curate(large_repo, enabled=True)
+ b = _curate(large_repo, enabled=True)
+ assert a.tour == b.tour
+
+ def test_flag_off_leaves_tour_empty(self, large_repo):
+ kg = _curate(large_repo, enabled=False)
+ assert kg.tour == []
+
+ def test_entry_point_leads_the_walk(self, flow_repo):
+ # Execution-flow order: right after the overview comes a real entry
+ # point, never a test fixture or an arbitrary "top layer" file.
+ kg = _curate(flow_repo, enabled=True)
+ assert kg.tour[0]["kind"] == "overview"
+ assert kg.tour[1]["target_path"] == "src/cli/main.py"
+ assert "entry point" in kg.tour[1]["reason"]
+
+ def test_walk_follows_import_depth(self, flow_repo):
+ # main -> route -> svc -> model: the chain appears in BFS order.
+ kg = _curate(flow_repo, enabled=True)
+ pos = {s["target_path"]: i for i, s in enumerate(kg.tour)}
+ assert (
+ pos["src/cli/main.py"]
+ < pos["src/api/route.py"]
+ < pos["src/services/svc.py"]
+ < pos["src/models/model.py"]
+ )
+
+ def test_tests_take_one_closing_stop(self, flow_repo):
+ # The Test layer never competes for walk slots — exactly one closing
+ # stop, after every runtime code stop.
+ kg = _curate(flow_repo, enabled=True)
+ test_steps = [s for s in kg.tour if s["layer_id"] == "layer:test"]
+ assert len(test_steps) == 1
+ last_runtime = max(
+ i
+ for i, s in enumerate(kg.tour)
+ if s["kind"] == "code" and s["layer_id"] != "layer:test"
+ )
+ assert kg.tour.index(test_steps[0]) > last_runtime
+ assert "verified" in test_steps[0]["reason"]
+
+ def test_no_stack_position_claims(self, flow_repo, large_repo):
+ # Reasons state evidence, never sort position ("Top of the stack"
+ # branded conftest.py the start of the control flow).
+ for repo in (flow_repo, large_repo):
+ kg = _curate(repo, enabled=True)
+ for step in kg.tour:
+ assert "Top of the stack" not in step["reason"]
+ assert "mid-stack" not in step["reason"]
+
+ def test_readme_never_visited_twice(self, flow_repo):
+ # The overview retargets to the root README — it must not reappear
+ # as a code stop later in the walk.
+ kg = _curate(flow_repo, enabled=True)
+ readme_steps = [s for s in kg.tour if s["target_path"] == "README.md"]
+ assert len(readme_steps) == 1
+ assert readme_steps[0]["kind"] == "overview"
+
+ def test_codeless_layers_get_no_manufactured_stop(self):
+ # A "plugins" dir of JSON manifests mints a Middleware layer with no
+ # code — the tour must not manufacture an anchor stop for it. The
+ # code files exceed the walk budget so a manifest could only appear
+ # via diversification.
+ code = ["src/cli/main.py"] + [f"src/services/svc{i}.py" for i in range(14)]
+ paths = code + [f"plugins/p{i}/plugin.json" for i in range(3)]
+ repo = build_repo(
+ paths,
+ entries={"src/cli/main.py"},
+ edges=[("src/cli/main.py", p) for p in code[1:]],
+ )
+ kg = _curate(repo, enabled=True)
+ for step in kg.tour:
+ assert not step["target_path"].endswith("plugin.json")
+
+ def test_example_programs_never_take_tour_slots(self):
+ # examples/ are documentation-by-code: no walk slots, no layer faces.
+ code = ["src/cli/main.py"] + [f"src/services/svc{i}.py" for i in range(3)]
+ paths = code + [f"examples/demo{i}/main.py" for i in range(5)]
+ paths += ["examples/versions/data/errors.py"] # would front Data otherwise
+ repo = build_repo(
+ paths,
+ entries={"src/cli/main.py"},
+ edges=[("src/cli/main.py", p) for p in code[1:]],
+ )
+ kg = _curate(repo, enabled=True)
+ for step in kg.tour:
+ assert not step["target_path"].startswith("examples/")
+
+ def test_barrel_steps_never_claim_entry_point(self):
+ # An index.ts barrel may legitimately seed the walk, but its reason
+ # must say re-export hub, not execution entry point.
+ barrel = "packages/types/src/index.ts"
+ repo = build_repo(
+ [barrel, "src/services/svc.py"],
+ entries={barrel},
+ barrels={barrel},
+ edges=[(barrel, "src/services/svc.py")],
+ )
+ kg = _curate(repo, enabled=True)
+ barrel_steps = [s for s in kg.tour if s["target_path"] == barrel]
+ assert barrel_steps, "barrel should still appear on the walk"
+ for s in barrel_steps:
+ assert "An entry point" not in s["reason"]
+ assert "re-export hub" in s["reason"]
+
+
+class TestEntryPointFallback:
+ def test_filename_scorers_fill_in_when_nothing_is_flagged(self):
+ # No ingestion entry flags at all: the entry-style filename (main.py)
+ # still surfaces, so the orientation panel never opens empty.
+ repo = build_repo(
+ ["src/cli/main.py", "src/services/svc.py", "tests/test_svc.py"],
+ edges=[("src/cli/main.py", "src/services/svc.py")],
+ )
+ kg = _curate(repo, enabled=True)
+ assert kg.project["entry_points"] == ["src/cli/main.py"]
+
+ def test_fallback_skips_test_files(self):
+ # A test named like an entry must not be surfaced by the fallback.
+ repo = build_repo(["tests/main.py", "src/services/svc.py"])
+ kg = _curate(repo, enabled=True)
+ assert kg.project["entry_points"] == []
+
+ def test_code_files_never_typed_infra_by_name(self):
+ # A Python module that *parses* Dockerfiles is code, not infra.
+ repo = build_repo(
+ ["core/ingestion/languages/specs/dockerfile.py", "Dockerfile"]
+ )
+ kg = _curate(repo, enabled=True)
+ by_path = {
+ n["filePath"]: n
+ for n in kg.nodes
+ if n.get("filePath") and str(n.get("id", "")).startswith("file:")
+ }
+ spec = by_path["core/ingestion/languages/specs/dockerfile.py"]
+ assert spec.get("type") != "service"
+ assert "infra" not in (spec.get("tags") or [])
+ assert by_path["Dockerfile"].get("type") == "service" # real one still promoted
+
+ def test_flagged_test_fixtures_not_surfaced(self):
+ # Ingestion may flag a wsgi.py inside tests/ as an entry point; the
+ # presentation surface must keep it out (a reader enters via src/).
+ repo = build_repo(
+ ["src/app/wsgi.py", "tests/test_apps/helloworld/wsgi.py"],
+ entries={"src/app/wsgi.py", "tests/test_apps/helloworld/wsgi.py"},
+ )
+ kg = _curate(repo, enabled=True)
+ assert kg.project["entry_points"] == ["src/app/wsgi.py"]
+
+
+# ---------------------------------------------------------------------------
+# Phase 4 — node typing & never-empty summaries
+# ---------------------------------------------------------------------------
+
+
+def typed_repo():
+ """A repo exercising infra/CI/data typing plus a barrel and a test."""
+ barrel = "packages/p/index.ts"
+ paths = [
+ ".github/workflows/ci.yml",
+ "Dockerfile",
+ "infra/main.tf",
+ "db/migrations/001_init.sql",
+ "config/app.yaml",
+ "README.md",
+ "src/api/route.py",
+ "tests/unit/test_route.py",
+ barrel,
+ ]
+ return build_repo(
+ paths,
+ tests={"tests/unit/test_route.py"},
+ entries={barrel},
+ barrels={barrel},
+ )
+
+
+def _node_by_path(kg, path):
+ return next(n for n in kg.nodes if n.get("filePath") == path)
+
+
+class TestNodeTyping:
+ def test_ci_workflow_is_pipeline(self, typed_repo):
+ kg = _curate(typed_repo, enabled=True)
+ n = _node_by_path(kg, ".github/workflows/ci.yml")
+ assert n["type"] == "pipeline"
+ assert "ci" in n["tags"]
+
+ def test_dockerfile_and_terraform_are_infra(self, typed_repo):
+ kg = _curate(typed_repo, enabled=True)
+ for p in ("Dockerfile", "infra/main.tf"):
+ n = _node_by_path(kg, p)
+ assert n["type"] == "service"
+ assert "infra" in n["tags"]
+
+ def test_migration_sql_is_schema(self, typed_repo):
+ kg = _curate(typed_repo, enabled=True)
+ n = _node_by_path(kg, "db/migrations/001_init.sql")
+ assert n["type"] == "schema"
+ assert "data" in n["tags"]
+
+
+class TestSummaryFloor:
+ def test_no_empty_file_summary(self, typed_repo, large_repo):
+ for repo in (typed_repo, large_repo):
+ kg = _curate(repo, enabled=True)
+ for n in kg.nodes:
+ if n["id"].startswith("file:"):
+ assert n["summary"], f"empty summary for {n['filePath']}"
+
+ def test_barrel_summary_is_honest(self, typed_repo):
+ kg = _curate(typed_repo, enabled=True)
+ n = _node_by_path(kg, "packages/p/index.ts")
+ assert "barrel" in n["summary"].lower()
+
+ def test_test_summary_names_target(self, typed_repo):
+ kg = _curate(typed_repo, enabled=True)
+ n = _node_by_path(kg, "tests/unit/test_route.py")
+ assert n["summary"].lower().startswith("tests for")
+
+ def test_flag_off_leaves_summaries_empty(self, typed_repo):
+ kg = _curate(typed_repo, enabled=False)
+ assert all(n["summary"] == "" for n in kg.nodes if n["id"].startswith("file:"))
+
+ def test_deterministic(self, typed_repo):
+ a = _curate(typed_repo, enabled=True)
+ b = _curate(typed_repo, enabled=True)
+ assert [n.get("summary") for n in a.nodes] == [n.get("summary") for n in b.nodes]
+
+
+class TestSummaryFloorDeferral:
+ def test_defer_leaves_summaries_for_later(self, typed_repo):
+ # Generate mode defers the floor so page backfill can win first.
+ kg = curate_knowledge_graph(
+ _build_skeleton(typed_repo),
+ parsed_files=typed_repo.parsed,
+ graph_builder=typed_repo.builder,
+ repo_structure=typed_repo.repo_structure,
+ community_info=typed_repo.builder.community_info(),
+ enabled=True,
+ defer_summary_floor=True,
+ )
+ assert any(n["summary"] == "" for n in kg.nodes if n["id"].startswith("file:"))
+
+ def test_apply_floor_fills_only_empties(self, typed_repo):
+ from repowise.core.analysis.kg_curation import apply_summary_floor
+
+ kg = _build_skeleton(typed_repo)
+ # Simulate a rich page summary already backfilled onto one node.
+ _node_by_path(kg, "src/api/route.py")["summary"] = "Rich page summary."
+ apply_summary_floor(kg, typed_repo.parsed)
+ assert _node_by_path(kg, "src/api/route.py")["summary"] == "Rich page summary."
+ assert all(n["summary"] for n in kg.nodes if n["id"].startswith("file:"))
+
+
+# ---------------------------------------------------------------------------
+# Closing-stop selection (suite anchors, descriptors, polyglot)
+# ---------------------------------------------------------------------------
+
+
+def _closing_stops(kg) -> list[dict]:
+ return [s for s in kg.tour if "test suite" in s["reason"]]
+
+
+class TestClosingStopParity:
+ def test_descriptor_never_faces_the_suite(self):
+ # gson regression: a shallow JPMS module-info.java sits in the Test
+ # layer; the closing stop must face a real camel test instead.
+ repo = build_repo(
+ [
+ "src/main/java/com/x/App.java",
+ "src/main/java/com/x/Core.java",
+ "jpms/src/test/java/module-info.java",
+ "src/test/java/com/x/core/AppTest.java",
+ ],
+ entries={"src/main/java/com/x/App.java"},
+ edges=[("src/main/java/com/x/App.java", "src/main/java/com/x/Core.java")],
+ )
+ kg = _curate(repo, enabled=True)
+ closing = _closing_stops(kg)
+ assert len(closing) == 1
+ assert closing[0]["target_path"] == "src/test/java/com/x/core/AppTest.java"
+
+ def test_fixture_file_never_faces_the_suite(self):
+ # gson regression: same-package edges gave the test tree's
+ # ParameterizedTypeFixtures.java the highest pagerank — but a
+ # fixtures file holds test data, it doesn't verify behavior.
+ repo = build_repo(
+ [
+ "src/main/java/com/x/App.java",
+ "src/main/java/com/x/Core.java",
+ "src/test/java/com/x/TypeFixtures.java",
+ "src/test/java/com/x/CoreTest.java",
+ ],
+ entries={"src/main/java/com/x/App.java"},
+ edges=[
+ ("src/main/java/com/x/App.java", "src/main/java/com/x/Core.java"),
+ # Tests lean on the fixture file — its rank dwarfs the test's.
+ ("src/test/java/com/x/CoreTest.java", "src/test/java/com/x/TypeFixtures.java"),
+ ],
+ pagerank={"src/test/java/com/x/TypeFixtures.java": 0.9},
+ )
+ kg = _curate(repo, enabled=True)
+ closing = _closing_stops(kg)
+ assert len(closing) == 1
+ assert closing[0]["target_path"] == "src/test/java/com/x/CoreTest.java"
+
+ def test_fixture_convention_does_not_leak_to_other_languages(self):
+ # The Fixture/Fixtures camel rule is declared by java — a python
+ # file with the same shape stays an eligible suite face.
+ repo = build_repo(
+ [
+ "src/app.py",
+ "src/core.py",
+ "tests/DataFixtures.py",
+ ],
+ entries={"src/app.py"},
+ edges=[("src/app.py", "src/core.py")],
+ )
+ kg = _curate(repo, enabled=True)
+ closing = _closing_stops(kg)
+ assert len(closing) == 1
+ assert closing[0]["target_path"] == "tests/DataFixtures.py"
+
+ def test_ruby_suite_anchor_wins(self):
+ repo = build_repo(
+ [
+ "lib/app.rb",
+ "lib/core.rb",
+ "test/test_helper.rb",
+ "test/app_test.rb",
+ ],
+ entries={"lib/app.rb"},
+ edges=[("lib/app.rb", "lib/core.rb")],
+ )
+ kg = _curate(repo, enabled=True)
+ closing = _closing_stops(kg)
+ assert len(closing) == 1
+ assert closing[0]["target_path"] == "test/test_helper.rb"
+
+ def test_runner_face_preserved_without_anchor(self):
+ # django-style: no conftest, the suite runner is the shallowest
+ # dominant-language file — it must keep facing the suite.
+ repo = build_repo(
+ [
+ "src/app.py",
+ "src/core.py",
+ "tests/runtests.py",
+ "tests/test_deep/test_one.py",
+ ],
+ entries={"src/app.py"},
+ edges=[("src/app.py", "src/core.py")],
+ )
+ kg = _curate(repo, enabled=True)
+ closing = _closing_stops(kg)
+ assert len(closing) == 1
+ assert closing[0]["target_path"] == "tests/runtests.py"
+
+ def test_polyglot_closing_reason_mentions_other_suites(self):
+ # 6 python + 4 ts code files (40% ts) with a ts test tree: the stop
+ # faces the python suite but names the TypeScript one.
+ repo = build_repo(
+ [
+ "src/a.py", "src/b.py", "src/c.py", "src/d.py", "src/e.py", "src/f.py",
+ "web/x.ts", "web/y.ts", "web/z.ts", "web/w.ts",
+ "tests/conftest.py",
+ "web/__tests__/x.test.ts",
+ ],
+ entries={"src/a.py"},
+ edges=[("src/a.py", "src/b.py")],
+ )
+ kg = _curate(repo, enabled=True)
+ closing = _closing_stops(kg)
+ assert len(closing) == 1
+ assert closing[0]["target_path"] == "tests/conftest.py"
+ assert "TypeScript test suite lives alongside it" in closing[0]["reason"]
+
+ def test_monoglot_reason_unchanged(self):
+ repo = build_repo(
+ ["src/app.py", "src/core.py", "tests/conftest.py"],
+ entries={"src/app.py"},
+ edges=[("src/app.py", "src/core.py")],
+ )
+ kg = _curate(repo, enabled=True)
+ closing = _closing_stops(kg)
+ assert closing[0]["reason"] == "The test suite — how the system's behavior is verified."
+
+
+class TestNonInfraCodeTyping:
+ def test_tier3_code_never_typed_infra_by_name(self):
+ # Equivalents of the dockerfile.py guard for every code language:
+ # code that *handles* infra formats is code, not infra.
+ from repowise.core.analysis.kg_curation import _enrich_type
+
+ assert _enrich_type("k8s/dockerfile.nim", "file") == ("file", None)
+ assert _enrich_type("build/makefile.clj", "file") == ("file", None)
+ assert _enrich_type("ci/.github/workflows/helpers.hs", "file") == ("file", None)
+ assert _enrich_type("tools/docker-compose.dart", "file") == ("file", None)
+
+ def test_infra_languages_still_promote(self):
+ from repowise.core.analysis.kg_curation import _enrich_type
+
+ assert _enrich_type("deploy/k8s/deploy.sh", "file") == ("service", "infra")
+ assert _enrich_type("infra/main.tf", "file") == ("service", "infra")
+ assert _enrich_type(".github/workflows/ci.yml", "config") == ("pipeline", "ci")
+
+
+# ---------------------------------------------------------------------------
+# Honest degradation (flow / sparse / structural)
+# ---------------------------------------------------------------------------
+
+# Vocabulary that claims an execution flow. Structural tours must never use
+# it — "named like an entry file" is the one sanctioned entry phrasing.
+_FLOW_CLAIMS = (
+ "entry point",
+ "imports fan out",
+ "imports deep",
+ "import path",
+ "directly used by the entry",
+ "widely-imported",
+)
+
+
+def _edgeless_zig_repo():
+ """A Tier-3 repo: real code files, import_support='none', zero edges.
+
+ Zig stays on the structural (no-resolver) tier — elixir, the previous
+ fixture language, was promoted to the lightweight regex tier.
+ """
+ paths = [
+ "src/shop.zig",
+ "src/application.zig",
+ "src/checkout.zig",
+ "src/cart.zig",
+ "src/billing/invoice.zig",
+ "tools/seeds.zig",
+ "test/shop_test.zig",
+ "test/helper.zig",
+ "README.md",
+ ]
+ return build_repo(paths, tests={"test/shop_test.zig", "test/helper.zig"})
+
+
+class TestHonestDegradation:
+ def test_structural_mode_for_unsupported_language(self):
+ repo = _edgeless_zig_repo()
+ kg = _curate(repo, enabled=True)
+ assert kg.project["graph_mode"] == "structural"
+
+ def test_structural_tour_makes_no_flow_claims(self):
+ repo = _edgeless_zig_repo()
+ kg = _curate(repo, enabled=True)
+ assert kg.tour, "structural repos still get a tour"
+ for step in kg.tour:
+ low = step["reason"].lower()
+ for claim in _FLOW_CLAIMS:
+ assert claim not in low, (step["target_path"], step["reason"])
+
+ def test_structural_anchor_states_the_evidence_and_the_gap(self):
+ repo = _edgeless_zig_repo()
+ kg = _curate(repo, enabled=True)
+ code_steps = [s for s in kg.tour if s["kind"] == "code" and "test" not in s["reason"].lower()]
+ assert code_steps, kg.tour
+ anchor = code_steps[0]
+ assert "isn't supported for Zig yet" in anchor["reason"]
+ assert anchor["depth"] == 0
+
+ def test_structural_layers_labeled_canonical(self):
+ repo = _edgeless_zig_repo()
+ kg = _curate(repo, enabled=True)
+ assert kg.layers
+ assert all(layer.get("order_basis") == "canonical" for layer in kg.layers)
+
+ def test_flow_layers_labeled_imports(self, flow_repo):
+ kg = _curate(flow_repo, enabled=True)
+ assert any(layer.get("order_basis") == "imports" for layer in kg.layers)
+
+ def test_flow_repo_stays_flow(self, flow_repo):
+ kg = _curate(flow_repo, enabled=True)
+ assert kg.project["graph_mode"] == "flow"
+
+ def test_sparse_mode_for_low_density_weak_resolution(self):
+ # 30 python files (over the small-repo floor), thin internal chain
+ # and most import targets landing on external nodes: low density
+ # AND weak resolution is the broken-resolver signature -> sparse.
+ paths = [f"src/m{i}.py" for i in range(30)]
+ edges = [(paths[i], paths[i + 1]) for i in range(29)]
+ edges += [(paths[i], f"external:mystery{i}") for i in range(5, 30)]
+ repo = build_repo(paths, entries={"src/m0.py"}, edges=edges)
+ kg = _curate(repo, enabled=True)
+ assert kg.project["graph_mode"] == "sparse"
+
+ def test_flow_mode_for_low_density_strong_resolution(self):
+ # Same thin chain but almost every target resolves internally: a
+ # require-light, well-resolved graph (sinatra after stdlib
+ # filtering: 1.31 edges/file at 0.77 resolution) narrates honestly
+ # -> flow, not sparse. Low density alone no longer indicts the
+ # resolver.
+ paths = [f"src/m{i}.py" for i in range(30)]
+ edges = [(paths[i], paths[i + 1]) for i in range(29)]
+ edges += [(paths[0], "external:gem:rack")]
+ repo = build_repo(paths, entries={"src/m0.py"}, edges=edges)
+ kg = _curate(repo, enabled=True)
+ assert kg.project["graph_mode"] == "flow"
+
+ def test_sparse_unreached_reason_blames_the_graph(self):
+ # Files off the walk in sparse mode cite incomplete resolution, not
+ # the file ("standalone or supporting" would blame the file).
+ paths = [f"src/m{i}.py" for i in range(30)]
+ # Density in the sparse band with weak resolution, edges
+ # concentrated in m0..m5: the walk's later slots fill with
+ # unreached files, whose reasons are under test.
+ edges = [
+ (paths[i], paths[j]) for i in range(6) for j in range(i + 1, 6)
+ ][:12]
+ edges += [(paths[i], f"external:mystery{i}") for i in range(6, 30)]
+ repo = build_repo(paths, entries={"src/m0.py"}, edges=edges)
+ kg = _curate(repo, enabled=True)
+ unreached_reasons = [
+ s["reason"] for s in kg.tour if "import resolution is incomplete" in s["reason"]
+ ]
+ assert unreached_reasons, [s["reason"] for s in kg.tour]
+ assert not any("standalone or supporting" in s["reason"] for s in kg.tour)
+
+ def test_small_repo_density_is_not_evidence(self):
+ # 7 healthy python files (mini-taskq shape): low density on a tiny
+ # repo must not demote a full-support language out of flow mode.
+ paths = [f"src/m{i}.py" for i in range(6)] + ["tests/test_m.py"]
+ edges = [("src/m0.py", "src/m1.py")]
+ repo = build_repo(paths, entries={"src/m0.py"}, edges=edges, tests={"tests/test_m.py"})
+ kg = _curate(repo, enabled=True)
+ assert kg.project["graph_mode"] == "flow"
+
+
+class TestClosingStopHarnessExclusion:
+ def test_shared_harness_never_faces_the_suite(self):
+ # okio/Alamofire/scopt regression: the base class or helper every
+ # test imports (AbstractFileSystemTest, BaseTestCase, SpecUtil)
+ # carries the suite's highest pagerank — but it is what the suite
+ # runs ON, not where tests start.
+ repo = build_repo(
+ [
+ "src/app.py",
+ "src/core.py",
+ "tests/harness.py",
+ "tests/test_one.py",
+ "tests/test_two.py",
+ ],
+ entries={"src/app.py"},
+ edges=[
+ ("src/app.py", "src/core.py"),
+ ("tests/test_one.py", "tests/harness.py"),
+ ("tests/test_two.py", "tests/harness.py"),
+ ],
+ pagerank={"tests/harness.py": 0.9},
+ )
+ kg = _curate(repo, enabled=True)
+ closing = _closing_stops(kg)
+ assert len(closing) == 1
+ assert closing[0]["target_path"] in ("tests/test_one.py", "tests/test_two.py")
+
+ def test_single_importer_helper_excluded(self):
+ # okio's CipherFactory.kt: even ONE test-file importer marks a
+ # helper — leaf tests import helpers, nothing imports leaf tests.
+ repo = build_repo(
+ [
+ "src/app.py",
+ "tests/util.py",
+ "tests/test_one.py",
+ ],
+ entries={"src/app.py"},
+ edges=[("tests/test_one.py", "tests/util.py")],
+ pagerank={"tests/util.py": 0.9},
+ )
+ kg = _curate(repo, enabled=True)
+ closing = _closing_stops(kg)
+ assert len(closing) == 1
+ assert closing[0]["target_path"] == "tests/test_one.py"
+
+ def test_test_project_dir_wins_over_shared_helpers(self):
+ # Polly regression: test/Shared/TestCancellation.cs is shallower
+ # than the .Specs project files, but the declared test-project
+ # convention (.Tests/.Specs) is where the suite lives.
+ repo = build_repo(
+ [
+ "src/Core/App.cs",
+ "src/Core/Core.cs",
+ "test/Shared/TestCancellation.cs",
+ "test/Acme.Specs/RetrySpecs.cs",
+ ],
+ entries={"src/Core/App.cs"},
+ edges=[("src/Core/App.cs", "src/Core/Core.cs")],
+ pagerank={"test/Shared/TestCancellation.cs": 0.9},
+ )
+ kg = _curate(repo, enabled=True)
+ closing = _closing_stops(kg)
+ assert len(closing) == 1
+ assert closing[0]["target_path"] == "test/Acme.Specs/RetrySpecs.cs"
+
+
+class TestSupportDirExclusion:
+ def test_doc_site_entries_never_surface(self):
+ # libuv/Polly regression: docs/code/*/main.c snippets and docfx
+ # template main.js flooded the entry surface and the whole tour.
+ repo = build_repo(
+ [
+ "docs/code/spawn/main.c",
+ "docs/template/public/main.js",
+ "website/theme/index.ts",
+ "src/core.c",
+ "src/run.c",
+ ],
+ entries={
+ "docs/code/spawn/main.c",
+ "docs/template/public/main.js",
+ "website/theme/index.ts",
+ },
+ edges=[("src/run.c", "src/core.c")],
+ )
+ kg = _curate(repo, enabled=True)
+ entries = kg.project.get("entry_points", [])
+ assert all(not e.startswith(("docs/", "website/")) for e in entries)
+ tour_paths = {s["target_path"] for s in (kg.tour or [])}
+ assert not any(p.startswith(("docs/", "website/")) for p in tour_paths)
+
+
+class TestFanoutCollapse:
+ def _gb(self):
+ from types import SimpleNamespace
+
+ import networkx as nx
+
+ g = nx.DiGraph()
+ # One Go-style package import fanned out to 3 sibling targets…
+ for t in ("pkg/a.py", "pkg/b.py", "pkg/c.py"):
+ g.add_edge("tests/test_x.py", t, edge_type="imports", imported_names=["pkg"])
+ # …and one explicit single-target import.
+ g.add_edge(
+ "tests/test_x.py", "tests/harness.py",
+ edge_type="imports", imported_names=["Harness"],
+ )
+ g.add_edge(
+ "tests/test_y.py", "tests/harness.py",
+ edge_type="imports", imported_names=["Harness"],
+ )
+ return SimpleNamespace(graph=lambda: g)
+
+ def test_fanout_groups_excluded_from_pairs(self):
+ from repowise.core.analysis.kg_curation import _import_pairs_excluding_fanout
+
+ pairs = set(_import_pairs_excluding_fanout(self._gb()))
+ # chi regression: a package fan-out is not evidence that each
+ # sibling file is individually referenced.
+ assert ("tests/test_x.py", "pkg/a.py") not in pairs
+ assert ("tests/test_x.py", "tests/harness.py") in pairs
+ assert ("tests/test_y.py", "tests/harness.py") in pairs
+
+ def test_anchor_rank_counts_relationships_not_edges(self):
+ from repowise.core.analysis.kg_curation import _anchor_fanout_rank
+
+ rank = _anchor_fanout_rank(self._gb())
+ # 4 raw out-edges from test_x, but only 2 import relationships
+ # (the fan-out collapses to one).
+ assert rank["tests/test_x.py"] == 2
+ assert rank["tests/test_y.py"] == 1
+
+
+class TestPartialTierGraphMode:
+ """Regex-tier (partial) languages run flow/sparse per REAL density and
+ resolution — partial support alone no longer pins sparse."""
+
+ def test_well_resolved_partial_repo_flows(self):
+ # 30 elixir files, thin but cleanly-resolved alias chain → flow:
+ # blaming "incomplete import resolution" at 0.97 resolution is a lie.
+ paths = [f"lib/m{i}.ex" for i in range(30)]
+ edges = [(paths[i], paths[i + 1]) for i in range(29)]
+ edges += [(paths[0], "external:Phoenix")]
+ repo = build_repo(paths, edges=edges)
+ kg = _curate(repo, enabled=True)
+ assert kg.project["graph_mode"] == "flow"
+
+ def test_weakly_resolved_partial_repo_stays_sparse(self):
+ paths = [f"lib/m{i}.ex" for i in range(30)]
+ edges = [(paths[i], paths[i + 1]) for i in range(9)]
+ edges += [(paths[i], f"external:Dep{i}") for i in range(10, 30)]
+ repo = build_repo(paths, edges=edges)
+ kg = _curate(repo, enabled=True)
+ assert kg.project["graph_mode"] == "sparse"
+
+ def test_small_partial_repo_with_clean_resolution_flows(self):
+ # Density is unmeasurable on tiny repos but resolution is not: a
+ # 24-file Elixir repo resolving 0.9 of its aliases must not have
+ # its tour blame "incomplete import resolution" for being small.
+ paths = [f"lib/m{i}.ex" for i in range(8)]
+ edges = [(paths[i], paths[i + 1]) for i in range(7)]
+ repo = build_repo(paths, edges=edges)
+ kg = _curate(repo, enabled=True)
+ assert kg.project["graph_mode"] == "flow"
+
+ def test_small_partial_repo_with_weak_resolution_stays_sparse(self):
+ paths = [f"lib/m{i}.ex" for i in range(8)]
+ edges = [(paths[0], paths[1])]
+ edges += [(paths[i], f"external:Dep{i}") for i in range(2, 8)]
+ repo = build_repo(paths, edges=edges)
+ kg = _curate(repo, enabled=True)
+ assert kg.project["graph_mode"] == "sparse"
diff --git a/tests/unit/analysis/test_kg_export_determinism.py b/tests/unit/analysis/test_kg_export_determinism.py
new file mode 100644
index 000000000..c5186beb8
--- /dev/null
+++ b/tests/unit/analysis/test_kg_export_determinism.py
@@ -0,0 +1,64 @@
+"""Canonical ordering of the exported knowledge-graph artifact.
+
+File-traversal and graph-insertion order vary run to run (parallel parsing,
+thread-completion order); ``KnowledgeGraphResult.to_dict`` must therefore
+emit byte-stable output regardless of the in-memory list order it was
+handed. Pinned after the 2026-06 discovery that identical re-runs produced
+different knowledge-graph.json bytes on every validation repo.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.knowledge_graph import KnowledgeGraphResult
+
+
+def _result(node_order: list[str], edge_order: list[tuple[str, str]]) -> KnowledgeGraphResult:
+ return KnowledgeGraphResult(
+ project={"name": "x"},
+ nodes=[{"id": n, "type": "file"} for n in node_order],
+ edges=[
+ {"source": s, "target": t, "type": "imports", "direction": "forward", "weight": 1.0}
+ for s, t in edge_order
+ ],
+ layers=[
+ {
+ "id": "layer:application",
+ "name": "Application",
+ "nodeIds": list(node_order),
+ "display_order": 0,
+ "subGroups": [
+ {"id": "layer:application:root", "name": "(root)", "nodeIds": list(node_order)}
+ ],
+ }
+ ],
+ tour=[],
+ )
+
+
+class TestCanonicalExport:
+ def test_shuffled_inputs_export_identically(self) -> None:
+ a = _result(["file:b", "file:a", "file:c"], [("file:b", "file:a"), ("file:a", "file:c")])
+ b = _result(["file:c", "file:b", "file:a"], [("file:a", "file:c"), ("file:b", "file:a")])
+ assert a.to_dict() == b.to_dict()
+
+ def test_nodes_sorted_by_id(self) -> None:
+ d = _result(["file:b", "file:a"], []).to_dict()
+ assert [n["id"] for n in d["nodes"]] == ["file:a", "file:b"]
+
+ def test_edges_sorted_by_source_target_type(self) -> None:
+ d = _result(["file:a", "file:b"], [("file:b", "file:a"), ("file:a", "file:b")]).to_dict()
+ assert [(e["source"], e["target"]) for e in d["edges"]] == [
+ ("file:a", "file:b"),
+ ("file:b", "file:a"),
+ ]
+
+ def test_layer_node_ids_and_subgroups_sorted(self) -> None:
+ d = _result(["file:b", "file:a"], []).to_dict()
+ layer = d["layers"][0]
+ assert layer["nodeIds"] == ["file:a", "file:b"]
+ assert layer["subGroups"][0]["nodeIds"] == ["file:a", "file:b"]
+
+ def test_tour_order_untouched(self) -> None:
+ r = _result(["file:a"], [])
+ r.tour = [{"order": 1, "target_path": "z"}, {"order": 2, "target_path": "a"}]
+ assert [s["target_path"] for s in r.to_dict()["tour"]] == ["z", "a"]
diff --git a/tests/unit/analysis/test_kg_invariants.py b/tests/unit/analysis/test_kg_invariants.py
new file mode 100644
index 000000000..3f33d5414
--- /dev/null
+++ b/tests/unit/analysis/test_kg_invariants.py
@@ -0,0 +1,147 @@
+"""Phase 7 — KG intuitiveness invariants locked across structurally different
+repos (many-isolates regression, flat single-package, deep monorepo) plus the
+portable artifact and the AST-untouched guard."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.core.analysis.kg_curation import build_portable_kg, validate_kg
+
+from .kg_fixtures import build_repo, build_skeleton, curate
+
+# ---------------------------------------------------------------------------
+# Structurally different repos
+# ---------------------------------------------------------------------------
+
+
+def many_isolates_repo():
+ """Many weakly-connected files — the historical 103-layers / 73-singletons
+ pathology. Curated layers must collapse to a bounded named set."""
+ paths: list[str] = []
+ for layer_dir in ("api", "services", "models", "ui", "utils", "config"):
+ paths += [f"pkg{layer_dir}/{layer_dir}/f{i}.py" for i in range(14)]
+ tests = {f"tests/test_{i}.py" for i in range(14)}
+ paths += sorted(tests)
+ return build_repo(paths, tests=tests) # no edges → every file an isolate
+
+
+def flat_repo():
+ """A single flat package — few layers, but must stay partitioned/valid."""
+ return build_repo([f"src/mod{i}.py" for i in range(40)])
+
+
+def deep_monorepo():
+ """A realistically layered monorepo with two mega-layers."""
+ paths: list[str] = []
+ for sub in ("ingestion", "analysis", "generation"):
+ paths += [f"packages/core/src/repowise/core/{sub}/m{i}.py" for i in range(24)]
+ for sub in ("buttons", "forms", "layout"):
+ paths += [f"packages/ui/src/components/{sub}/c{i}.tsx" for i in range(24)]
+ paths += [f"packages/cli/src/cli/commands/cmd{i}.py" for i in range(20)]
+ paths += [f"src/api/r{i}.py" for i in range(12)]
+ paths += [f"src/models/m{i}.py" for i in range(10)]
+ paths += [f"src/utils/u{i}.py" for i in range(8)]
+ paths += [f"config/c{i}.yaml" for i in range(6)]
+ tests = {f"tests/unit/test_{i}.py" for i in range(30)}
+ paths += sorted(tests)
+ return build_repo(paths, tests=tests)
+
+
+ALL_REPOS = ["many_isolates_repo", "flat_repo", "deep_monorepo"]
+
+
[email protected]("repo_fixture", ALL_REPOS)
+class TestInvariantsAcrossRepos:
+ def test_layer_count_never_explodes(self, repo_fixture, request):
+ kg = curate(request.getfixturevalue(repo_fixture))
+ assert len(kg.layers) <= 15 # the 103→bounded guarantee
+
+ def test_partition_holds(self, repo_fixture, request):
+ kg = curate(request.getfixturevalue(repo_fixture))
+ v = validate_kg(kg)
+ assert "partition" not in " ".join(v.errors)
+ seen: set[str] = set()
+ for layer in kg.layers:
+ for nid in layer["nodeIds"]:
+ assert nid not in seen
+ seen.add(nid)
+ file_count = sum(1 for n in kg.nodes if n["id"].startswith("file:"))
+ assert len(seen) == file_count
+
+ def test_no_empty_summaries(self, repo_fixture, request):
+ kg = curate(request.getfixturevalue(repo_fixture))
+ assert all(n["summary"] for n in kg.nodes if n["id"].startswith("file:"))
+
+ def test_entry_points_capped(self, repo_fixture, request):
+ kg = curate(request.getfixturevalue(repo_fixture))
+ assert len(kg.project.get("entry_points", [])) <= 8
+
+ def test_tour_within_budget_and_opens_overview(self, repo_fixture, request):
+ kg = curate(request.getfixturevalue(repo_fixture))
+ assert len(kg.tour) <= 12
+ if kg.tour:
+ assert kg.tour[0]["kind"] == "overview"
+
+ def test_no_hard_validation_errors(self, repo_fixture, request):
+ kg = curate(request.getfixturevalue(repo_fixture))
+ v = validate_kg(kg)
+ assert v.ok, v.errors
+
+ def test_deterministic(self, repo_fixture, request):
+ a = curate(request.getfixturevalue(repo_fixture))
+ b = curate(request.getfixturevalue(repo_fixture))
+ assert a.layers == b.layers
+ assert a.tour == b.tour
+ assert a.project.get("entry_points") == b.project.get("entry_points")
+
+ def test_ast_graph_untouched(self, repo_fixture, request):
+ repo = request.getfixturevalue(repo_fixture)
+ g = repo.builder.graph()
+ before = (g.number_of_nodes(), g.number_of_edges())
+ curate(repo)
+ g = repo.builder.graph()
+ assert (g.number_of_nodes(), g.number_of_edges()) == before
+
+
+class TestManyIsolatesRegression:
+ def test_does_not_produce_one_layer_per_file(self, many_isolates_repo):
+ # Skeleton (community) layers = one per file (the pathology).
+ skel = build_skeleton(many_isolates_repo)
+ file_count = sum(1 for n in skel.nodes if n["id"].startswith("file:"))
+ assert len(skel.layers) == file_count
+ # Curated layers collapse to a bounded named set.
+ kg = curate(many_isolates_repo)
+ assert len(kg.layers) <= 15
+ assert len(kg.layers) < file_count
+
+
+# ---------------------------------------------------------------------------
+# Portable artifact (Phase 6)
+# ---------------------------------------------------------------------------
+
+
+class TestPortableArtifact:
+ def test_self_contained_and_validated(self, deep_monorepo):
+ kg = curate(deep_monorepo)
+ data, validation = build_portable_kg(kg)
+ for key in ("version", "project", "nodes", "edges", "layers", "tour", "meta"):
+ assert key in data
+ assert data["meta"]["validation"]["ok"] is validation.ok
+ assert data["meta"]["layer_count"] == len(kg.layers)
+ assert validation.ok, validation.errors
+
+ def test_default_to_dict_has_no_meta(self, deep_monorepo):
+ # The bare export stays byte-identical-shaped (no meta leakage).
+ kg = curate(deep_monorepo)
+ assert "meta" not in kg.to_dict()
+
+ def test_metrics_block_populated(self, deep_monorepo):
+ kg = curate(deep_monorepo)
+ m = validate_kg(kg).metrics
+ assert m["layer_count"] >= 6
+ assert m["summary_completeness_pct"] == 100.0
+ assert 0 <= m["largest_layer_pct"] <= 35
diff --git a/tests/unit/analysis/test_kg_modules.py b/tests/unit/analysis/test_kg_modules.py
new file mode 100644
index 000000000..982c7a63a
--- /dev/null
+++ b/tests/unit/analysis/test_kg_modules.py
@@ -0,0 +1,420 @@
+"""Tests for curated wiki modules (``derive_modules`` in ``kg_curation``).
+
+Acceptance gates: partition/coverage invariants, determinism, naming
+(generic-segment stripping, no size suffixes, collision handling), the
+granularity window, stable path-derived ids, and the artifact export seam
+(``modules`` key present only when curation derived modules).
+"""
+
+from __future__ import annotations
+
+import json
+
+from repowise.core.analysis.kg_curation import derive_modules, validate_kg
+from repowise.core.analysis.knowledge_graph import KnowledgeGraphResult
+
+from .kg_fixtures import build_repo, curate
+
+# ---------------------------------------------------------------------------
+# Pure derive_modules fixtures
+# ---------------------------------------------------------------------------
+
+
+def _layer(name: str, paths: list[str]) -> dict:
+ return {
+ "id": f"layer:{name.lower()}",
+ "name": name,
+ "nodeIds": [f"file:{p}" for p in paths],
+ }
+
+
+def _id_map(*path_lists: list[str]) -> dict[str, str]:
+ return {f"file:{p}": p for paths in path_lists for p in paths}
+
+
+def _monorepo():
+ """Synthetic monorepo where ``packages``/``acme``/``src`` are generic.
+
+ 175 files total; the namespace dirs appear in 140 (80% > 60% → generic)
+ while ``core`` stays at 100/175 (57% → informative).
+ """
+ ns = "packages/acme/src/acme"
+ service = (
+ [f"{ns}/core/ingestion/resolvers/r{i}.py" for i in range(30)]
+ + [f"{ns}/core/ingestion/parsers/p{i}.py" for i in range(18)]
+ + [f"{ns}/core/ingestion/root{i}.py" for i in range(2)]
+ + [f"{ns}/core/analysis/a{i}.py" for i in range(30)]
+ + [f"{ns}/core/generation/g{i}.py" for i in range(20)]
+ )
+ ui = [f"{ns}/ui/components/c{i}.tsx" for i in range(40)]
+ tests = [f"tests/unit/test_{i}.py" for i in range(20)] + [
+ f"tests/integration/test_{i}.py" for i in range(10)
+ ]
+ config = [f"conf{i}.yaml" for i in range(5)]
+ layers = [
+ _layer("Service", service),
+ _layer("UI", ui),
+ _layer("Test", tests),
+ _layer("Config", config),
+ ]
+ return layers, _id_map(service, ui, tests, config)
+
+
+def _derive(layers, id_to_path, **kw):
+ kw.setdefault("target_min", 4)
+ kw.setdefault("target_max", 40)
+ return derive_modules(layers, id_to_path, **kw)
+
+
+# ---------------------------------------------------------------------------
+# Invariants — partition, coverage, determinism
+# ---------------------------------------------------------------------------
+
+
+class TestInvariants:
+ def test_partition_within_each_layer(self):
+ layers, id_to_path = _monorepo()
+ modules = _derive(layers, id_to_path)
+ covered = [nid for m in modules for nid in m["nodeIds"]]
+ assert len(covered) == len(set(covered)), "a file appears in two modules"
+ # Every layer is ≥ the module floor, so coverage is total.
+ all_ids = {nid for layer in layers for nid in layer["nodeIds"]}
+ assert set(covered) == all_ids
+
+ def test_never_merges_across_layers(self):
+ layers, id_to_path = _monorepo()
+ modules = _derive(layers, id_to_path)
+ layer_of = {
+ nid: layer["id"] for layer in layers for nid in layer["nodeIds"]
+ }
+ for m in modules:
+ assert {layer_of[nid] for nid in m["nodeIds"]} == {m["layerId"]}
+
+ def test_deterministic_byte_equal(self):
+ layers, id_to_path = _monorepo()
+ a = json.dumps(_derive(layers, id_to_path), sort_keys=True)
+ # Re-derive from shuffled inputs: dict/list order must not leak.
+ shuffled_layers = [
+ {**layer, "nodeIds": list(reversed(layer["nodeIds"]))}
+ for layer in layers
+ ]
+ shuffled_map = dict(reversed(list(id_to_path.items())))
+ b = json.dumps(_derive(shuffled_layers, shuffled_map), sort_keys=True)
+ assert a == b
+
+ def test_tiny_layer_yields_no_module(self):
+ layers, id_to_path = _monorepo()
+ tiny = _layer("Data", ["db/schema.sql", "db/seed.sql"])
+ id_to_path = {**id_to_path, **_id_map(["db/schema.sql", "db/seed.sql"])}
+ modules = _derive([*layers, tiny], id_to_path, min_module_size=3)
+ assert not [m for m in modules if m["layerId"] == "layer:data"]
+
+ def test_external_node_ids_ignored(self):
+ layers, id_to_path = _monorepo()
+ layers[0]["nodeIds"].append("external:@radix-ui/react-progress")
+ modules = _derive(layers, id_to_path)
+ all_member_ids = {nid for m in modules for nid in m["nodeIds"]}
+ assert "external:@radix-ui/react-progress" not in all_member_ids
+
+
+# ---------------------------------------------------------------------------
+# Granularity window
+# ---------------------------------------------------------------------------
+
+
+class TestGranularity:
+ def test_window_respected(self):
+ layers, id_to_path = _monorepo()
+ modules = _derive(layers, id_to_path)
+ sizes = {m["name"]: len(m["nodeIds"]) for m in modules}
+ # Single-module layers may sit below target_min (rule 3); split
+ # products must respect the window.
+ assert all(s <= 40 for s in sizes.values()), sizes
+ # Mega-layer split landed at the expected granularity.
+ assert sizes["ingestion/resolvers"] == 32 # 30 + 2 merged-up root files
+ assert sizes["ingestion/parsers"] == 18
+ assert sizes["core/analysis"] == 30
+ assert sizes["core/generation"] == 20
+
+ def test_flat_dir_stays_one_honest_module(self):
+ paths = [f"src/lib/f{i}.py" for i in range(60)]
+ modules = _derive([_layer("Service", paths)], _id_map(paths))
+ assert len(modules) == 1
+ assert len(modules[0]["nodeIds"]) == 60 # > target_max, but flat
+
+ def test_small_remnant_merges_up_not_confetti(self):
+ layers, id_to_path = _monorepo()
+ modules = _derive(layers, id_to_path)
+ # The 2 root files of core/ingestion folded into the biggest
+ # ingestion sibling instead of minting a 2-file module.
+ split_modules = [m for m in modules if m["layerId"] == "layer:service"]
+ assert all(len(m["nodeIds"]) >= 4 for m in split_modules)
+
+ def test_surviving_root_group_named_top_level(self):
+ paths = (
+ [f"pkg/sub1/f{i}.py" for i in range(10)]
+ + [f"pkg/sub2/f{i}.py" for i in range(10)]
+ + [f"pkg/r{i}.py" for i in range(6)]
+ )
+ modules = _derive(
+ [_layer("Application", paths)], _id_map(paths), target_max=12
+ )
+ names = {m["name"] for m in modules}
+ assert "Application (top-level)" in names
+ assert {"sub1", "sub2"} <= names
+
+
+# ---------------------------------------------------------------------------
+# Naming
+# ---------------------------------------------------------------------------
+
+
+class TestNaming:
+ def test_generic_segments_never_in_names(self):
+ layers, id_to_path = _monorepo()
+ modules = _derive(layers, id_to_path)
+ for m in modules:
+ for seg in m["name"].split("/"):
+ assert seg not in {"packages", "acme", "src"}, m["name"]
+
+ def test_expected_names(self):
+ layers, id_to_path = _monorepo()
+ names = {m["name"] for m in _derive(layers, id_to_path)}
+ assert names == {
+ "ingestion/resolvers",
+ "ingestion/parsers",
+ "core/analysis",
+ "core/generation",
+ "UI",
+ "Test",
+ "Config",
+ }
+
+ def test_names_unique_and_never_size_suffixed(self):
+ layers, id_to_path = _monorepo()
+ names = [m["name"] for m in _derive(layers, id_to_path)]
+ assert len(names) == len(set(names))
+ assert not any(n.rstrip().endswith(")") and "(" in n and n.split("(")[-1].rstrip(") ").isdigit() for n in names)
+
+ def test_collision_extends_path_leftward(self):
+ paths = (
+ [f"a/x/utils/f{i}.py" for i in range(8)]
+ + [f"b/x/utils/g{i}.py" for i in range(8)]
+ + [f"c/api/h{i}.py" for i in range(12)]
+ )
+ modules = _derive([_layer("Service", paths)], _id_map(paths), target_max=10)
+ names = {m["name"] for m in modules}
+ # Both dirs end x/utils — disambiguated by the parent segment,
+ # NOT by a size suffix.
+ assert {"a/x/utils", "b/x/utils"} <= names
+ assert not any("(" in n for n in names)
+
+ def test_single_module_layer_named_after_layer(self):
+ # Flat-library shape (requests-like): one dir → one module.
+ paths = [f"src/requests/m{i}.py" for i in range(12)]
+ modules = _derive([_layer("Service", paths)], _id_map(paths))
+ assert len(modules) == 1
+ assert modules[0]["name"] == "Service"
+ assert modules[0]["path"] == "src/requests"
+
+ def test_dominant_language_tag(self):
+ layers, id_to_path = _monorepo()
+ lang_by_id = {
+ nid: ("typescript" if p.endswith(".tsx") else "python")
+ for nid, p in id_to_path.items()
+ }
+ modules = _derive(layers, id_to_path, lang_by_id=lang_by_id)
+ by_name = {m["name"]: m for m in modules}
+ assert by_name["UI"]["language"] == "typescript"
+ assert by_name["core/analysis"]["language"] == "python"
+
+
+# ---------------------------------------------------------------------------
+# Ids — stable, path-derived
+# ---------------------------------------------------------------------------
+
+
+class TestIds:
+ def test_ids_are_dir_path_slugs(self):
+ layers, id_to_path = _monorepo()
+ by_name = {m["name"]: m for m in _derive(layers, id_to_path)}
+ m = by_name["ingestion/resolvers"]
+ assert m["id"] == "module:packages-acme-src-acme-core-ingestion-resolvers"
+ assert m["path"] == "packages/acme/src/acme/core/ingestion/resolvers"
+
+ def test_id_stable_under_file_adds(self):
+ layers, id_to_path = _monorepo()
+ before = {m["id"] for m in _derive(layers, id_to_path)}
+ extra = "packages/acme/src/acme/core/ingestion/resolvers/r_new.py"
+ layers2 = [dict(layer) for layer in layers]
+ layers2[0] = {
+ **layers[0],
+ "nodeIds": layers[0]["nodeIds"] + [f"file:{extra}"],
+ }
+ after = {m["id"] for m in _derive(layers2, {**id_to_path, f"file:{extra}": extra})}
+ assert "module:packages-acme-src-acme-core-ingestion-resolvers" in before & after
+ assert before == after
+
+ def test_ids_unique(self):
+ layers, id_to_path = _monorepo()
+ ids = [m["id"] for m in _derive(layers, id_to_path)]
+ assert len(ids) == len(set(ids))
+
+ def test_root_path_module_has_empty_path(self):
+ layers, id_to_path = _monorepo()
+ by_name = {m["name"]: m for m in _derive(layers, id_to_path)}
+ assert by_name["Config"]["path"] == ""
+ assert by_name["Config"]["id"] == "module:config"
+
+
+# ---------------------------------------------------------------------------
+# Artifact seam — curation populates kg.modules; export key is conditional
+# ---------------------------------------------------------------------------
+
+
+def _curated_repo():
+ paths: list[str] = []
+ for sub in ("ingestion", "analysis", "generation"):
+ paths += [f"packages/core/src/repowise/core/{sub}/mod{i}.py" for i in range(24)]
+ paths += [f"packages/cli/src/repowise/cli/commands/cmd{i}.py" for i in range(20)]
+ paths += [f"src/api/route{i}.py" for i in range(12)]
+ paths += [f"src/utils/util{i}.py" for i in range(8)]
+ tests = {f"tests/unit/test_{i}.py" for i in range(30)}
+ paths += sorted(tests)
+ code = [p for p in paths if p not in tests]
+ edges = [
+ (code[i], code[i + step]) for step in (1, 2, 3) for i in range(len(code) - step)
+ ]
+ return build_repo(paths, tests=tests, edges=edges)
+
+
+class TestArtifactSeam:
+ def test_curation_derives_modules(self):
+ kg = curate(_curated_repo())
+ assert kg.modules, "curated KG should carry derived modules"
+ covered = [nid for m in kg.modules for nid in m["nodeIds"]]
+ assert len(covered) == len(set(covered))
+
+ def test_flag_off_exports_no_modules_key(self):
+ kg = curate(_curated_repo(), enabled=False)
+ assert kg.modules == []
+ assert "modules" not in kg.to_dict()
+
+ def test_curated_export_carries_modules_key(self):
+ kg = curate(_curated_repo())
+ data = kg.to_dict()
+ assert data["modules"] == kg.to_dict()["modules"] # deterministic
+ assert all(m["nodeIds"] == sorted(m["nodeIds"]) for m in data["modules"])
+
+ def test_from_file_roundtrip(self, tmp_path):
+ kg = curate(_curated_repo())
+ f = tmp_path / "knowledge-graph.json"
+ f.write_text(json.dumps(kg.to_dict()), encoding="utf-8")
+ loaded = KnowledgeGraphResult.from_file(f)
+ assert loaded is not None
+ assert loaded.modules == kg.to_dict()["modules"]
+
+ def test_validate_kg_flags_module_violations(self):
+ kg = curate(_curated_repo())
+ assert validate_kg(kg).ok
+ # Duplicate membership → hard error.
+ kg.modules[0]["nodeIds"].append(kg.modules[1]["nodeIds"][0])
+ report = validate_kg(kg)
+ assert not report.ok
+ assert any("more than one module" in e for e in report.errors)
+
+ def test_validate_kg_flags_size_suffix_names(self):
+ kg = curate(_curated_repo())
+ kg.modules[0]["name"] = "ingestion (32)"
+ kg.modules[1]["name"] = "ingestion (18)"
+ report = validate_kg(kg)
+ assert any("size-suffixed" in e for e in report.errors)
+
+ def test_validate_kg_reports_module_metrics(self):
+ kg = curate(_curated_repo())
+ metrics = validate_kg(kg).metrics
+ assert metrics["module_count"] == len(kg.modules)
+ assert metrics["module_coverage_pct"] > 0
+
+
+class TestMatrixSurfacedShapes:
+ """Regression shapes surfaced by the 38-repo validation matrix."""
+
+ def test_fixture_dominated_repo_keeps_real_dir_names(self):
+ # aeson shape: one fixture subtree IS >60% of the repo, so every one
+ # of its segments is "dominant". Naming must fall back to the raw
+ # dir tail — the old "<Layer> (top-level)" fallback collided across
+ # sibling groups and tripped the export degradation guard (0 modules).
+ parsing = [f"tests/JSONTestSuite/test_parsing/case{i}.json" for i in range(300)]
+ transform = [f"tests/JSONTestSuite/test_transform/case{i}.json" for i in range(22)]
+ unit = [f"tests/UnitTests/u{i}.hs" for i in range(13)]
+ src = [f"src/Data/Aeson/m{i}.hs" for i in range(40)]
+ layers = [
+ _layer("Application", src),
+ _layer("Test", parsing + transform + unit),
+ ]
+ modules = _derive(layers, _id_map(parsing, transform, unit, src))
+ names = [m["name"] for m in modules]
+ assert len(names) == len(set(names)), names # no collision → no degradation
+ joined = " ".join(names)
+ assert "test_parsing" in joined and "test_transform" in joined
+ assert "(top-level)" not in joined
+
+ def test_small_siblings_fuse_into_parent_dir_module(self):
+ # django/conf/locale shape: ~30 tiny per-locale dirs. They must fuse
+ # into ONE module at the parent dir — not fold into the
+ # alphabetically-first locale and misname 170 files as "locale/ar".
+ locales = [
+ f"django/conf/locale/{loc}/f{i}.py"
+ for loc in ("ar", "be", "cs", "da", "de", "el", "es", "fi", "fr", "he")
+ for i in range(3)
+ ]
+ core = [f"django/core/c{i}.py" for i in range(20)]
+ layers = [_layer("Application", locales + core)]
+ modules = _derive(layers, _id_map(locales, core))
+ by_path = {m["path"]: m for m in modules}
+ assert "django/conf/locale" in by_path, sorted(by_path)
+ assert len(by_path["django/conf/locale"]["nodeIds"]) == 30
+ assert by_path["django/conf/locale"]["name"].endswith("locale")
+
+ def test_healthy_module_keeps_identity_absorbing_small_sibling(self):
+ # The sibling fuse must not generalise a big module's dir upward:
+ # core/providers absorbing a 2-file sibling stays core/providers.
+ providers = [f"acme/core/providers/p{i}.py" for i in range(20)]
+ stray = [f"acme/core/stray/s{i}.py" for i in range(2)]
+ other = [f"acme/web/w{i}.py" for i in range(20)]
+ layers = [_layer("Service", providers + stray + other)]
+ # target_max=20 forces core(22) to split into providers(20)+stray(2)
+ modules = _derive(layers, _id_map(providers, stray, other), target_max=20)
+ paths = {m["path"] for m in modules}
+ assert "acme/core/providers" in paths, sorted(paths)
+
+ def test_two_all_org_groups_in_one_layer_get_unique_names(self):
+ # repowise shape: a root remnant AND a "packages" container group in
+ # the same layer both strip to nothing. The container takes its raw
+ # tail; only the true root group reads "(top-level)".
+ root = ["Makefile.py", "conftest.py", "setup.py", "tasks.py", "noxfile.py"]
+ pkgs = [f"packages/p{i}.py" for i in range(6)]
+ deep = [f"packages/acme/src/acme/core/d{i}.py" for i in range(40)]
+ layers = [_layer("Application", root + pkgs + deep)]
+ modules = _derive(layers, _id_map(root, pkgs, deep), target_max=20)
+ names = [m["name"] for m in modules]
+ assert len(names) == len(set(names)), names
+
+ def test_whole_layer_modules_flagged_for_page_dedupe(self):
+ # Single-module layers are 1:1 with their layer page; the flag lets
+ # selection skip the duplicate doc while the artifact keeps coverage.
+ flat = [f"lib/f{i}.py" for i in range(10)]
+ deep_a = [f"acme/web/a{i}.py" for i in range(10)]
+ deep_b = [f"acme/api/b{i}.py" for i in range(10)]
+ layers = [
+ _layer("Service", flat),
+ _layer("Application", deep_a + deep_b),
+ ]
+ modules = _derive(layers, _id_map(flat, deep_a, deep_b), target_max=12)
+ by_layer = {}
+ for m in modules:
+ by_layer.setdefault(m["layerId"], []).append(m)
+ assert all(m.get("wholeLayer") for m in by_layer["layer:service"])
+ assert len(by_layer["layer:application"]) > 1
+ assert not any(m.get("wholeLayer") for m in by_layer["layer:application"])
diff --git a/tests/unit/cli/test_doctor_vector_decisions.py b/tests/unit/cli/test_doctor_vector_decisions.py
new file mode 100644
index 000000000..a3795d3bd
--- /dev/null
+++ b/tests/unit/cli/test_doctor_vector_decisions.py
@@ -0,0 +1,185 @@
+"""Regression tests for the doctor SQL<->vector reconciliation.
+
+The page vector store also holds *decision* embeddings under the
+``decision:<record_id>`` namespace. The drift / orphan check used to compare
+vector ids against ``wiki_pages`` only, so every decision embedding was counted
+as an orphan vector — a false "Coordinator drift FAIL" on a consistent store,
+and (with ``--repair``) a *destructive* deletion of valid decision vectors.
+
+These tests pin the corrected behavior:
+ * the SQL-side id set used for vector reconciliation is
+ ``page_ids | {"decision:<id>"}``;
+ * a genuinely orphaned vector (id in neither table) is still detected;
+ * the repair deletion targets only the genuine orphan, never a decision.
+"""
+
+from __future__ import annotations
+
+import pytest
+from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
+from sqlalchemy.pool import StaticPool
+
+from repowise.cli.commands.doctor_cmd import _decision_vector_ids
+from repowise.core.analysis.decisions.semantic_match import DECISION_VECTOR_PREFIX
+from repowise.core.persistence.database import init_db
+from repowise.core.persistence.models import DecisionRecord
+from repowise.core.persistence.vector_store import InMemoryVectorStore
+from repowise.core.providers.embedding.base import MockEmbedder
+
+
+async def _setup_session() -> tuple[object, AsyncSession]:
+ engine = create_async_engine(
+ "sqlite+aiosqlite:///:memory:",
+ connect_args={"check_same_thread": False},
+ poolclass=StaticPool,
+ )
+ await init_db(engine)
+ factory = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession)
+ session = factory()
+ return engine, session
+
+
+async def _insert_repo(session: AsyncSession):
+ from repowise.core.persistence.crud import upsert_repository
+
+ repo = await upsert_repository(
+ session,
+ name="taskq",
+ local_path="/tmp/taskq",
+ url="https://github.com/example/taskq",
+ )
+ await session.commit()
+ return repo
+
+
+async def _insert_page(session: AsyncSession, repo_id: str, page_id: str) -> None:
+ from repowise.core.persistence.crud import upsert_page
+
+ await upsert_page(
+ session,
+ page_id=page_id,
+ repository_id=repo_id,
+ page_type="file_page",
+ title=page_id,
+ content="body",
+ target_path=page_id,
+ source_hash="h",
+ model_name="mock",
+ provider_name="mock",
+ input_tokens=1,
+ output_tokens=1,
+ )
+ await session.commit()
+
+
+async def _insert_decision(session: AsyncSession, repo_id: str, title: str) -> str:
+ rec = DecisionRecord(repository_id=repo_id, title=title, decision="because")
+ session.add(rec)
+ await session.commit()
+ return rec.id
+
+
+async def test_decision_vector_ids_returns_namespaced_ids():
+ engine, session = await _setup_session()
+ try:
+ repo = await _insert_repo(session)
+ d1 = await _insert_decision(session, repo.id, "Adopt Redis")
+ d2 = await _insert_decision(session, repo.id, "Use Postgres")
+
+ ids = await _decision_vector_ids(session, repo.id)
+ assert ids == {f"{DECISION_VECTOR_PREFIX}{d1}", f"{DECISION_VECTOR_PREFIX}{d2}"}
+ finally:
+ await session.close()
+ await engine.dispose()
+
+
+async def test_decisions_not_counted_as_orphans():
+ """Consistent store: pages + decisions both embedded => zero orphan/drift."""
+ engine, session = await _setup_session()
+ try:
+ repo = await _insert_repo(session)
+ await _insert_page(session, repo.id, "file_page:a.py")
+ await _insert_page(session, repo.id, "file_page:b.py")
+ d1 = await _insert_decision(session, repo.id, "Adopt Redis")
+
+ vs = InMemoryVectorStore(MockEmbedder())
+ await vs.embed_and_upsert("file_page:a.py", "a", {})
+ await vs.embed_and_upsert("file_page:b.py", "b", {})
+ await vs.embed_and_upsert(f"{DECISION_VECTOR_PREFIX}{d1}", "redis", {})
+
+ page_ids = {"file_page:a.py", "file_page:b.py"}
+ vector_sql_ids = page_ids | await _decision_vector_ids(session, repo.id)
+ vs_ids = await vs.list_page_ids()
+
+ # This mirrors the doctor reconciliation arithmetic.
+ orphaned = vs_ids - vector_sql_ids
+ missing = vector_sql_ids - vs_ids
+ assert orphaned == set()
+ assert missing == set()
+
+ # Coordinator-style drift: SQL (pages + decisions) vs vector count.
+ adjusted_sql = len(page_ids) + len(await _decision_vector_ids(session, repo.id))
+ drift = abs(adjusted_sql - len(vs_ids)) / max(adjusted_sql, 1)
+ assert drift == 0.0
+ finally:
+ await session.close()
+ await engine.dispose()
+
+
+async def test_genuine_orphan_still_detected():
+ engine, session = await _setup_session()
+ try:
+ repo = await _insert_repo(session)
+ await _insert_page(session, repo.id, "file_page:a.py")
+ d1 = await _insert_decision(session, repo.id, "Adopt Redis")
+
+ vs = InMemoryVectorStore(MockEmbedder())
+ await vs.embed_and_upsert("file_page:a.py", "a", {})
+ await vs.embed_and_upsert(f"{DECISION_VECTOR_PREFIX}{d1}", "redis", {})
+ # A vector whose id is in neither wiki_pages nor decision_records.
+ await vs.embed_and_upsert("file_page:ghost.py", "ghost", {})
+
+ page_ids = {"file_page:a.py"}
+ vector_sql_ids = page_ids | await _decision_vector_ids(session, repo.id)
+ vs_ids = await vs.list_page_ids()
+
+ orphaned = vs_ids - vector_sql_ids
+ assert orphaned == {"file_page:ghost.py"}
+ finally:
+ await session.close()
+ await engine.dispose()
+
+
+async def test_repair_deletes_only_genuine_orphan_not_decisions():
+ engine, session = await _setup_session()
+ try:
+ repo = await _insert_repo(session)
+ await _insert_page(session, repo.id, "file_page:a.py")
+ d1 = await _insert_decision(session, repo.id, "Adopt Redis")
+ decision_vid = f"{DECISION_VECTOR_PREFIX}{d1}"
+
+ vs = InMemoryVectorStore(MockEmbedder())
+ await vs.embed_and_upsert("file_page:a.py", "a", {})
+ await vs.embed_and_upsert(decision_vid, "redis", {})
+ await vs.embed_and_upsert("file_page:ghost.py", "ghost", {})
+
+ page_ids = {"file_page:a.py"}
+ vector_sql_ids = page_ids | await _decision_vector_ids(session, repo.id)
+ vs_ids = await vs.list_page_ids()
+ orphaned = vs_ids - vector_sql_ids
+
+ # Repair deletes exactly the orphan set (doctor's --repair loop).
+ for pid in orphaned:
+ await vs.delete(pid)
+
+ surviving = await vs.list_page_ids()
+ assert decision_vid in surviving, "decision embedding must survive repair"
+ assert "file_page:a.py" in surviving
+ assert "file_page:ghost.py" not in surviving
+ finally:
+ await session.close()
+ await engine.dispose()
diff --git a/tests/unit/cli/test_persist_result_sweep.py b/tests/unit/cli/test_persist_result_sweep.py
new file mode 100644
index 000000000..f8e4ff57e
--- /dev/null
+++ b/tests/unit/cli/test_persist_result_sweep.py
@@ -0,0 +1,227 @@
+"""End-to-end sweep behaviour of the CLI ``persist_result`` path.
+
+The normal single-repo ``repowise init`` persists the INDEX phase
+incrementally during the run, so ``persist_result`` takes the
+``index_persisted_incrementally=True`` branch. Before the fix that branch
+called ``persist_analysis`` + ``persist_generation`` but never swept stale
+structurally-keyed pages (community-N / scc / layer), so they survived every
+re-index forever — and their FTS + vector embeddings leaked with them.
+
+These tests drive ``persist_result`` against a real repo-local SQLite DB with
+a pre-seeded stale ``module_page`` and assert it is swept from the DB, the FTS
+index, and an attached vector store, while the run's current page survives.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from types import SimpleNamespace
+
+import pytest
+from sqlalchemy import select
+
+from repowise.cli._repo_session import open_repo_db
+from repowise.cli.commands.init_cmd.persistence import persist_result
+from repowise.core.generation.models import GeneratedPage
+from repowise.core.persistence import FullTextSearch, get_session
+from repowise.core.persistence.models import Page
+from repowise.core.persistence.vector_store.in_memory import InMemoryVectorStore
+from repowise.core.providers.embedding.base import MockEmbedder
+
+
+def _generated_page(page_type: str, target: str) -> GeneratedPage:
+ now = datetime.now(UTC).isoformat()
+ pid = f"{page_type}:{target}"
+ return GeneratedPage(
+ page_id=pid,
+ page_type=page_type,
+ title=target,
+ content=f"content for {target}",
+ source_hash="x" * 64,
+ model_name="mock",
+ provider_name="mock",
+ input_tokens=1,
+ output_tokens=1,
+ cached_tokens=0,
+ generation_level=1,
+ target_path=target,
+ created_at=now,
+ updated_at=now,
+ )
+
+
+def _result(
+ repo_name: str,
+ generated_pages: list[GeneratedPage],
+ *,
+ vector_store=None,
+ authoritative_page_types: set[str] | None = None,
+) -> SimpleNamespace:
+ """A minimal PipelineResult stand-in for the ``index_done`` branch.
+
+ persist_analysis / persist_generation read these attributes; everything is
+ falsy so they no-op except the page upsert + the sweep.
+ """
+ return SimpleNamespace(
+ repo_name=repo_name,
+ index_persisted_incrementally=True,
+ generated_pages=generated_pages,
+ tech_stack=None,
+ vector_store=vector_store,
+ dead_code_report=None,
+ health_report=None,
+ decision_report=None,
+ git_metadata_list=[],
+ knowledge_graph_result=None,
+ authoritative_page_types=authoritative_page_types or set(),
+ )
+
+
+async def _seed_stale_module_page(repo_path, page_id: str) -> str:
+ """Insert a stale module_page directly and return the repo id."""
+ engine, sf, repo_id = await open_repo_db(repo_path, repo_name="r")
+ try:
+ now = datetime.now(UTC)
+ async with get_session(sf) as session:
+ session.add(
+ Page(
+ id=page_id,
+ repository_id=repo_id,
+ page_type="module_page",
+ title="stale",
+ content="stale body",
+ target_path="community-155",
+ source_hash="x" * 64,
+ model_name="mock",
+ provider_name="mock",
+ created_at=now,
+ updated_at=now,
+ )
+ )
+ finally:
+ await engine.dispose()
+ return repo_id
+
+
+async def test_persist_result_index_done_sweeps_stale_module_page(tmp_path):
+ """The incremental-index branch must sweep stale structural pages.
+
+ Pre-fix this fails: the ``index_done`` branch never called the sweep, so
+ the pre-seeded ``module_page:community-155`` survived alongside the new
+ ``module_page:community-75``.
+ """
+ repo_path = tmp_path / "repo"
+ repo_path.mkdir()
+ stale_id = "module_page:community-155"
+ await _seed_stale_module_page(repo_path, stale_id)
+
+ current = _generated_page("module_page", "community-75")
+ await persist_result(_result("r", [current]), repo_path)
+
+ engine, sf, _ = await open_repo_db(repo_path, repo_name="r")
+ try:
+ async with get_session(sf) as session:
+ ids = (
+ (await session.execute(select(Page.id).where(Page.page_type == "module_page")))
+ .scalars()
+ .all()
+ )
+ assert set(ids) == {"module_page:community-75"}
+ assert stale_id not in ids
+ finally:
+ await engine.dispose()
+
+
+async def test_persist_result_index_done_sweeps_fts_and_vector(tmp_path):
+ """Swept ids are removed from FTS + vector store; current ids survive."""
+ repo_path = tmp_path / "repo"
+ repo_path.mkdir()
+ stale_id = "module_page:community-155"
+ await _seed_stale_module_page(repo_path, stale_id)
+
+ # Seed the FTS index for the stale page through the same engine
+ # persist_result will reuse.
+ engine, _sf, _ = await open_repo_db(repo_path, repo_name="r")
+ fts = FullTextSearch(engine)
+ await fts.ensure_index()
+ await fts.index(stale_id, "stale", "stale body about widgets")
+ await engine.dispose()
+
+ # Seed the vector store with both the stale page and the page the run keeps.
+ store = InMemoryVectorStore(MockEmbedder())
+ current = _generated_page("module_page", "community-75")
+ await store.embed_batch(
+ [
+ (stale_id, "stale body about widgets", {}),
+ (current.page_id, "current body", {}),
+ ]
+ )
+
+ await persist_result(_result("r", [current], vector_store=store), repo_path)
+
+ # Vector store: stale gone, current survives.
+ assert await store.list_page_ids() == {"module_page:community-75"}
+
+ # FTS: the stale page is no longer searchable; the current page is indexed.
+ engine, _sf, _ = await open_repo_db(repo_path, repo_name="r")
+ fts = FullTextSearch(engine)
+ await fts.ensure_index()
+ hits = {r.page_id for r in await fts.search("widgets", limit=10)}
+ assert stale_id not in hits
+ # The run's current page is freshly FTS-indexed (its content mentions its
+ # target_path "community-75").
+ current_hits = {r.page_id for r in await fts.search("community-75", limit=10)}
+ assert current.page_id in current_hits
+ await engine.dispose()
+
+
+async def test_persist_result_index_done_keeps_pages_when_no_module_run(tmp_path):
+ """A run with no module pages must not wipe existing module pages."""
+ repo_path = tmp_path / "repo"
+ repo_path.mkdir()
+ stale_id = "module_page:community-1"
+ await _seed_stale_module_page(repo_path, stale_id)
+
+ # Run produces only a file_page — module pages are an unproduced type.
+ current = _generated_page("file_page", "src/app.py")
+ await persist_result(_result("r", [current]), repo_path)
+
+ engine, sf, _ = await open_repo_db(repo_path, repo_name="r")
+ try:
+ async with get_session(sf) as session:
+ ids = (await session.execute(select(Page.id))).scalars().all()
+ assert stale_id in ids
+ assert "file_page:src/app.py" in ids
+ finally:
+ await engine.dispose()
+
+
+async def test_persist_result_curated_zero_modules_sweeps_stale(tmp_path):
+ """Live mini-taskq regression through the CLI path.
+
+ A curated run authoritative for ``module_page`` that emitted ZERO module
+ pages (every module collapsed into its layer via wholeLayer) must still
+ sweep the pre-curated ``module_page:community-0``.
+ """
+ repo_path = tmp_path / "repo"
+ repo_path.mkdir()
+ stale_id = "module_page:community-0"
+ await _seed_stale_module_page(repo_path, stale_id)
+
+ # Run emits only a layer page but is authoritative for module_page too.
+ current = _generated_page("layer_page", "layer:Data")
+ await persist_result(
+ _result("r", [current], authoritative_page_types={"module_page", "layer_page"}),
+ repo_path,
+ )
+
+ engine, sf, _ = await open_repo_db(repo_path, repo_name="r")
+ try:
+ async with get_session(sf) as session:
+ ids = (await session.execute(select(Page.id))).scalars().all()
+ assert stale_id not in ids
+ assert "layer_page:layer:Data" in ids
+ finally:
+ await engine.dispose()
diff --git a/tests/unit/cli/test_workspace_curated_grouping.py b/tests/unit/cli/test_workspace_curated_grouping.py
new file mode 100644
index 000000000..26d1538f6
--- /dev/null
+++ b/tests/unit/cli/test_workspace_curated_grouping.py
@@ -0,0 +1,91 @@
+"""Tests for curated-grouping wiring in ``repowise workspace add``.
+
+``module_grouping="curated"`` is the default. Doc generation can only engage
+curated module grouping if (a) the KG artifact (``.repowise/knowledge-graph.json``)
+was saved during indexing and (b) the generator is told the ``repo_path`` so it
+can load that artifact. These tests pin both seams so a regression to community
+grouping is caught.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+
+from repowise.cli.commands.workspace_cmd import _generate_docs_for_added_repo
+
+
+def test_do_index_save_idiom_writes_artifact(tmp_path):
+ """The ``_do_index`` save idiom must persist the curated KG artifact.
+
+ ``_do_index`` is a nested closure, so we exercise the exact save call it
+ performs: when the pipeline result carries a ``knowledge_graph_result``,
+ ``save_knowledge_graph_json`` writes ``.repowise/knowledge-graph.json``.
+ """
+ from repowise.cli.state_persistence import save_knowledge_graph_json
+
+ kg = SimpleNamespace(to_dict=lambda: {"nodes": [], "layers": []})
+ result = SimpleNamespace(knowledge_graph_result=kg)
+
+ saved = getattr(result, "knowledge_graph_result", None)
+ assert saved is not None
+ save_knowledge_graph_json(tmp_path, saved)
+
+ assert (tmp_path / ".repowise" / "knowledge-graph.json").is_file()
+
+
+def test_generate_docs_for_added_repo_passes_repo_path(tmp_path):
+ """``generate_all`` must receive ``repo_path`` so the curated KG loads."""
+ repo_path = tmp_path
+
+ generator = MagicMock()
+ generator.generate_all = AsyncMock(return_value=[])
+
+ traverser = MagicMock()
+ traverser.traverse.return_value = []
+ traverser.get_repo_structure.return_value = object()
+
+ fts = MagicMock()
+ fts.ensure_index = AsyncMock()
+ fts.index = AsyncMock()
+
+ engine = MagicMock()
+ engine.dispose = AsyncMock()
+
+ class _SessionCtx:
+ async def __aenter__(self):
+ return MagicMock()
+
+ async def __aexit__(self, *a):
+ return False
+
+ def _fake_get_session(_sf):
+ return _SessionCtx()
+
+ with (
+ patch("repowise.cli.helpers.get_db_url_for_repo", return_value="sqlite://"),
+ patch("repowise.core.generation.PageGenerator", return_value=generator),
+ patch("repowise.core.generation.ContextAssembler"),
+ patch("repowise.core.generation.GenerationConfig"),
+ patch("repowise.core.ingestion.FileTraverser", return_value=traverser),
+ patch("repowise.core.ingestion.ASTParser"),
+ patch("repowise.core.ingestion.GraphBuilder", return_value=MagicMock()),
+ patch("repowise.core.persistence.create_engine", return_value=engine),
+ patch("repowise.core.persistence.create_session_factory", return_value=MagicMock()),
+ patch("repowise.core.persistence.init_db", AsyncMock()),
+ patch("repowise.core.persistence.get_session", _fake_get_session),
+ patch("repowise.core.persistence.upsert_repository", AsyncMock()),
+ patch("repowise.core.persistence.upsert_page_from_generated", AsyncMock()),
+ patch("repowise.core.persistence.FullTextSearch", return_value=fts),
+ ):
+ _generate_docs_for_added_repo(
+ repo_path=repo_path,
+ provider=object(),
+ embedder_name="fake",
+ concurrency=1,
+ reasoning="low",
+ exclude_patterns=[],
+ )
+
+ generator.generate_all.assert_awaited_once()
+ assert generator.generate_all.await_args.kwargs["repo_path"] == repo_path
diff --git a/tests/unit/generation/test_kg_context.py b/tests/unit/generation/test_kg_context.py
index d1b5b35e4..3895fbefb 100644
--- a/tests/unit/generation/test_kg_context.py
+++ b/tests/unit/generation/test_kg_context.py
@@ -212,3 +212,57 @@ class TestInterLayerEdges:
deps_out, deps_in = ctx.get_inter_layer_edges(ctx.get_layers()[0])
assert deps_out == []
assert deps_in == []
+
+
+class TestCuratedTourShape:
+ """The curated export's tour steps carry target_path + reason (no nodeIds)."""
+
+ @pytest.fixture
+ def curated_kg_json(self, tmp_path):
+ kg = {
+ "version": "1.0.0",
+ "project": {"name": "test", "graph_mode": "flow"},
+ "nodes": [
+ {"id": "file:src/main.py", "type": "file", "filePath": "src/main.py"},
+ ],
+ "edges": [],
+ "layers": [
+ {"id": "layer:app", "name": "Application",
+ "nodeIds": ["file:src/main.py"]},
+ ],
+ "tour": [
+ {"order": 1, "target_path": "src/main.py", "page_type": "file_page",
+ "title": "main.py", "depth": 1, "kind": "code",
+ "reason": "An entry point — execution and imports fan out from here.",
+ "layer_id": "layer:app"},
+ ],
+ }
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "main.py").touch()
+ kg_path = tmp_path / ".repowise" / "knowledge-graph.json"
+ kg_path.parent.mkdir()
+ kg_path.write_text(json.dumps(kg))
+ return kg_path
+
+ def test_target_path_steps_map_to_files(self, curated_kg_json):
+ ctx = KnowledgeGraphContext(curated_kg_json)
+ fc = ctx.get_file_context("src/main.py")
+ assert fc is not None and fc.tour_step is not None
+ assert fc.tour_step["order"] == 1
+
+ def test_tour_step_description_falls_back_to_reason(self, curated_kg_json):
+ ctx = KnowledgeGraphContext(curated_kg_json)
+ fc = ctx.get_file_context("src/main.py")
+ assert fc.tour_step["description"].startswith("An entry point")
+
+ def test_get_graph_mode(self, curated_kg_json):
+ ctx = KnowledgeGraphContext(curated_kg_json)
+ assert ctx.get_graph_mode() == "flow"
+
+ def test_graph_mode_absent_on_uncurated(self, sample_kg_json):
+ ctx = KnowledgeGraphContext(sample_kg_json)
+ assert ctx.get_graph_mode() is None
+
+ def test_graph_mode_unavailable(self):
+ ctx = KnowledgeGraphContext(None)
+ assert ctx.get_graph_mode() is None
diff --git a/tests/unit/generation/test_knowledge_graph_enrichment.py b/tests/unit/generation/test_knowledge_graph_enrichment.py
index 61c84a046..64e6cecea 100644
--- a/tests/unit/generation/test_knowledge_graph_enrichment.py
+++ b/tests/unit/generation/test_knowledge_graph_enrichment.py
@@ -4,7 +4,6 @@ from __future__ import annotations
from dataclasses import dataclass, field
from types import SimpleNamespace
-from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -16,7 +15,6 @@ from repowise.core.generation.knowledge_graph import (
enrich_knowledge_graph,
)
-
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
@@ -85,8 +83,8 @@ class TestEnrichLayers:
@pytest.mark.asyncio
async def test_enriches_layer_names(self):
llm = _make_llm_client(
- '{"layers": [{"index": 0, "name": "Core Pipeline", "description": "Handles data flow"}, '
- '{"index": 1, "name": "CLI Interface", "description": "Command line entry"}]}'
+ '{"layers": [{"id": "layer:core", "name": "Core Pipeline", "description": "Handles data flow"}, '
+ '{"id": "layer:cli", "name": "CLI Interface", "description": "Command line entry"}]}'
)
skeleton = _make_kg_skeleton()
builder = _make_graph_builder({"src/core.py": 0.5, "src/main.py": 0.3})
@@ -97,6 +95,77 @@ class TestEnrichLayers:
assert result.layers[0]["description"] == "Handles data flow"
assert result.layers[1]["name"] == "CLI Interface"
+ @pytest.mark.asyncio
+ async def test_positional_index_responses_are_ignored(self):
+ # Regression: a model answering with list positions instead of layer
+ # ids must not rename anything (positional joins once shuffled every
+ # layer name when later batches restarted their indices at 0).
+ llm = _make_llm_client(
+ '{"layers": [{"index": 0, "name": "Wrong Name", "description": "wrong"}, '
+ '{"index": 1, "name": "Also Wrong", "description": "wrong"}]}'
+ )
+ skeleton = _make_kg_skeleton()
+ builder = _make_graph_builder()
+ repo = _make_repo_structure()
+
+ result = await enrich_knowledge_graph(skeleton, llm, builder, repo, [])
+ assert result.layers[0]["name"] == "src/core" # heuristic preserved
+ assert result.layers[1]["name"] == "cli"
+
+ @pytest.mark.asyncio
+ async def test_cross_batch_ids_do_not_clobber_other_layers(self):
+ # Eight layers → two batches of five and three. Batch 2's response
+ # echoes batch 1's ids; those answers must be dropped, not applied.
+ layers = [
+ {"id": f"layer:l{i}", "name": f"heuristic-{i}", "description": "",
+ "nodeIds": [f"file:src/f{i}.py"]}
+ for i in range(8)
+ ]
+ nodes = [
+ {"id": f"file:src/f{i}.py", "type": "file", "filePath": f"src/f{i}.py", "summary": ""}
+ for i in range(8)
+ ]
+ responses = [
+ # Batch 1 (l0..l4): correct ids.
+ '{"layers": [{"id": "layer:l0", "name": "Named Zero", "description": "d0"}]}',
+ # Batch 2 (l5..l7): answers with batch-1 ids — all must be skipped.
+ '{"layers": [{"id": "layer:l0", "name": "Clobbered", "description": "x"}, '
+ '{"id": "layer:l1", "name": "Clobbered", "description": "x"}]}',
+ # Tour call.
+ '{"tour": []}',
+ ]
+ call_count = 0
+
+ async def _side_effect(*args, **kwargs):
+ nonlocal call_count
+ content = responses[min(call_count, len(responses) - 1)]
+ call_count += 1
+ return SimpleNamespace(content=content, input_tokens=10, output_tokens=10)
+
+ llm = AsyncMock()
+ llm.generate.side_effect = _side_effect
+
+ skeleton = _make_kg_skeleton(layers=layers, nodes=nodes)
+ builder = _make_graph_builder()
+ repo = _make_repo_structure()
+
+ result = await enrich_knowledge_graph(skeleton, llm, builder, repo, [])
+ assert result.layers[0]["name"] == "Named Zero"
+ assert all(layer["name"] != "Clobbered" for layer in result.layers)
+ assert result.layers[5]["name"] == "heuristic-5" # untouched by bad batch
+
+ @pytest.mark.asyncio
+ async def test_unknown_id_is_skipped(self):
+ llm = _make_llm_client(
+ '{"layers": [{"id": "layer:nonexistent", "name": "Ghost", "description": "x"}]}'
+ )
+ skeleton = _make_kg_skeleton()
+ builder = _make_graph_builder()
+ repo = _make_repo_structure()
+
+ result = await enrich_knowledge_graph(skeleton, llm, builder, repo, [])
+ assert all(layer["name"] != "Ghost" for layer in result.layers)
+
@pytest.mark.asyncio
async def test_falls_back_on_llm_failure(self):
llm = AsyncMock()
diff --git a/tests/unit/generation/test_layer_pages.py b/tests/unit/generation/test_layer_pages.py
index d1280b630..a83f543e4 100644
--- a/tests/unit/generation/test_layer_pages.py
+++ b/tests/unit/generation/test_layer_pages.py
@@ -241,7 +241,8 @@ class TestBuildLevel5Coros:
run = self._make_run(tmp_path, layers)
coros = build_level5_coros(run)
assert len(coros) == 1
- assert coros[0][0] == "layer_page:layer:Core"
+ # Page keyed by the layer's stable slug id, not its display name.
+ assert coros[0][0] == "layer_page:layer:core"
def test_skips_small_layers(self, tmp_path):
from repowise.core.generation.page_generator.levels import build_level5_coros
@@ -279,7 +280,7 @@ class TestBuildLevel5Coros:
"nodeIds": ["file:a.py", "file:b.py", "file:c.py"]},
]
run = self._make_run(tmp_path, layers)
- run.completed_ids = {"layer_page:layer:Core"}
+ run.completed_ids = {"layer_page:layer:core"}
coros = build_level5_coros(run)
assert len(coros) == 0
@@ -298,5 +299,50 @@ class TestBuildLevel5Coros:
coros = build_level5_coros(run)
assert len(coros) == 2
page_ids = {c[0] for c in coros}
- assert "layer_page:layer:Core" in page_ids
- assert "layer_page:layer:API" in page_ids
+ assert "layer_page:layer:core" in page_ids
+ assert "layer_page:layer:api" in page_ids
+
+ def test_page_key_uses_slug_not_display_name(self, tmp_path):
+ """The page key derives from the stable slug id, never the mutable
+ display name — a layer named "Task Queue Core" with id ``layer:queue``
+ is keyed by ``layer:queue`` so an LLM rename can't churn the key."""
+ from repowise.core.generation.page_generator.levels import build_level5_coros
+
+ layers = [
+ {"id": "layer:queue", "name": "Task Queue Core",
+ "nodeIds": ["file:a.py", "file:b.py", "file:c.py"]},
+ ]
+ run = self._make_run(tmp_path, layers)
+ coros = build_level5_coros(run)
+ assert len(coros) == 1
+ assert coros[0][0] == "layer_page:layer:queue"
+
+
+# ---------------------------------------------------------------------------
+# Slug identity stability under enrichment
+# ---------------------------------------------------------------------------
+
+
+class TestLayerIdStability:
+ def test_enrichment_renames_name_not_id_so_page_key_is_stable(self, tmp_path):
+ """The LLM layer-name enrichment mutates ``name`` only; the slug ``id``
+ — and therefore the layer page key — is unchanged across the rename."""
+ from repowise.core.generation.page_generator.levels import build_level5_coros
+
+ node_ids = ["file:a.py", "file:b.py", "file:c.py"]
+
+ def key_for(name: str) -> str:
+ layers = [{"id": "layer:queue", "name": name, "nodeIds": node_ids}]
+ run = self._make_run(tmp_path, layers)
+ coros = build_level5_coros(run)
+ assert len(coros) == 1
+ return coros[0][0]
+
+ # Heuristic name -> page key.
+ before = key_for("Application")
+ # Enrichment rewrites the display name; id (and key) must not move.
+ after = key_for("Task Queue Core")
+ assert before == after == "layer_page:layer:queue"
+
+ # Reuse the level-5 fixture harness verbatim.
+ _make_run = TestBuildLevel5Coros._make_run
diff --git a/tests/unit/generation/test_layers.py b/tests/unit/generation/test_layers.py
index 669b238d7..91d9ee284 100644
--- a/tests/unit/generation/test_layers.py
+++ b/tests/unit/generation/test_layers.py
@@ -8,7 +8,6 @@ from repowise.core.generation.layers import (
infer_layer,
)
-
# ---------------------------------------------------------------------------
# infer_layer — every file maps to exactly one layer
# ---------------------------------------------------------------------------
@@ -26,6 +25,13 @@ def test_infer_layer_matches_directory_hints():
assert infer_layer("src/types/dtos.ts") == "Types"
+def test_infer_layer_recognizes_cli_command_surface():
+ # Edge case A: a CLI command surface must not fall through to Application.
+ assert infer_layer("packages/cli/src/repowise/cli/commands/init_cmd.py") == "CLI"
+ assert infer_layer("src/cli/main.py") == "CLI"
+ assert infer_layer("app/cmd/serve.py") == "CLI"
+
+
def test_infer_layer_uses_deepest_matching_directory():
# The closest directory wins over a shallower one.
assert infer_layer("services/api/handler.py") == "API"
@@ -36,6 +42,162 @@ def test_infer_layer_falls_back_for_unmatched_paths():
assert infer_layer("random/folder/thing.py") == DEFAULT_LAYER
+def test_infer_layer_spec_dirs_need_test_shaped_files():
+ # A "specs/" directory of ordinary modules is a specification folder —
+ # the scan continues outward instead of branding them tests.
+ assert infer_layer("core/ingestion/languages/specs/dockerfile.py") == "Service"
+ assert infer_layer("specs/openapi.py") == DEFAULT_LAYER
+ # With a test-shaped filename the same dirs DO mean tests.
+ assert infer_layer("specs/auth.spec.ts") == "Test"
+ assert infer_layer("spec/test_auth.py") == "Test"
+
+
+def test_infer_layer_unambiguous_test_dirs_take_any_file():
+ # tests/ and __tests__/ are test roots regardless of filename.
+ assert infer_layer("tests/helpers.py") == "Test"
+ assert infer_layer("tests/conftest.py") == "Test"
+ assert infer_layer("src/__tests__/render.tsx") == "Test"
+
+
+def test_infer_layer_colocated_test_files_are_test():
+ # Go and Jest colocate tests beside sources — the filename is the signal.
+ assert infer_layer("middleware/compress_test.go") == "Test"
+ assert infer_layer("src/components/Button.test.tsx") == "Test"
+ assert infer_layer("rack-protection/spec/spec_helper.rb") == "Test"
+
+
+def test_infer_layer_ambiguous_spec_dir_needs_language_corroboration():
+ # Ruby declares spec/ as an unambiguous test-dir token: a Ruby file under
+ # spec/ is RSpec material whatever its name, so config.ru is Test only when
+ # the language is supplied. Omitting language leaves the ambiguous "spec"
+ # token uncorroborated and the file falls through (not Test) — this
+ # divergence is exactly what the curation/tour guard sites must respect by
+ # passing language to infer_layer.
+ assert infer_layer("spec/dummy/config.ru", "ruby") == "Test"
+ assert infer_layer("spec/dummy/config.ru") != "Test"
+
+
+def test_infer_layer_root_dot_dirs_are_tooling_config():
+ # .agents/plugins/* must not mint a phantom Middleware layer.
+ assert infer_layer(".agents/plugins/marketplace.json") == "Config"
+ assert infer_layer(".github/workflows/ci.yml") == "Config"
+ assert infer_layer(".claude/CLAUDE.md") == "Config"
+
+
+def test_infer_layer_test_root_beats_deeper_hints():
+ # A fixture under tests/models/ is a test, not Data — the test root wins
+ # over any deeper directory hint.
+ assert infer_layer("tests/models/__init__.py") == "Test"
+ assert infer_layer("tests/test_apps/cliapp/app.py") == "Test"
+ assert infer_layer("test/api/fixtures.py") == "Test"
+
+
+# ---------------------------------------------------------------------------
+# Case-sensitive camel-suffix test conventions (per language)
+# ---------------------------------------------------------------------------
+
+
+def test_infer_layer_camel_suffix_tests_per_language():
+ # The convention's own case applies: FooTest.java is a test wherever it sits.
+ assert infer_layer("gson/src/main/java/com/google/gson/JsonParserTest.java") == "Test"
+ assert infer_layer("src/GsonTests.java") == "Test"
+ assert infer_layer("src/SplitFunctionalIT.java") == "Test"
+ assert infer_layer("app/PaymentServiceTest.kt") == "Test"
+ assert infer_layer("app/CheckoutSpec.kt") == "Test"
+ assert infer_layer("core/ParserSpec.scala") == "Test"
+ assert infer_layer("core/RouterSuite.scala") == "Test"
+ assert infer_layer("Billing/InvoiceTests.cs") == "Test"
+ assert infer_layer("Billing/InvoiceSpecs.cs") == "Test"
+ assert infer_layer("Sources/AppCore/RouterTests.swift") == "Test"
+ assert infer_layer("src/Service/MailerTest.php") == "Test"
+ assert infer_layer("src/ParserSpec.hs") == "Test"
+
+
+def test_infer_layer_camel_suffix_false_positive_guards():
+ # Lowercase boundaries and bare names never match (D-005): `latest`,
+ # `contest`, `Test.java` (no prefix), `MyTestimony` are not tests.
+ assert infer_layer("src/latest.java") != "Test"
+ assert infer_layer("src/contest.cs") != "Test"
+ assert infer_layer("src/Test.java") != "Test"
+ assert infer_layer("app/MyTestimony.kt") != "Test"
+ assert infer_layer("src/UNIT.java") != "Test" # uppercase boundary before IT
+ # Conventions don't leak across languages: Java's IT rule means nothing
+ # for Python; Haskell's Spec rule means nothing for Go.
+ assert infer_layer("src/SplitIT.py") != "Test"
+ assert infer_layer("pkg/HandlerSpec.go") != "Test"
+
+
+def test_infer_layer_camel_suffix_works_without_lowercase_filename_callers():
+ # sinatra's vendored spec/okjson.rb regression: an ambiguous spec/ dir
+ # with a non-test-shaped file stays non-test even with camel rules live.
+ assert infer_layer("rack-protection/spec/okjson.rb") != "Test"
+
+
+def test_infer_layer_multi_segment_test_roots():
+ # Maven/Gradle/sbt sourceset roots mark any file beneath them.
+ assert infer_layer("module/src/it/java/com/x/FlowVerifier.java") == "Test"
+ assert infer_layer("module/src/integrationTest/java/com/x/Flow.java") == "Test"
+ assert infer_layer("core/src/it/scala/com/x/Pipeline.scala") == "Test"
+ # src/test/java was already covered by the generic "test" token.
+ assert infer_layer("gson/src/test/java/com/google/gson/Helper.java") == "Test"
+ # "it" alone is NOT a test token — only the full sourceset shape matches.
+ assert infer_layer("docs/it/translation.md") != "Test"
+ assert infer_layer("src/it/locale.py") != "Test"
+
+
+def test_infer_layer_dotnet_test_project_dirs():
+ # Sibling Foo.Tests/ projects are test roots for everything inside.
+ assert infer_layer("Billing.Tests/InvoiceFixture.cs") == "Test"
+ assert infer_layer("src/Billing.Tests/data/sample.json") == "Test"
+ # Case matters: a lowercase "billing.tests" dir is not the convention.
+ assert infer_layer("billing.tests/notes.md") != "Test"
+
+
+# ---------------------------------------------------------------------------
+# Per-language layer-dir hints
+# ---------------------------------------------------------------------------
+
+
+def test_infer_layer_go_internal_pkg_hints():
+ assert infer_layer("internal/auth.go", "go") == "Service"
+ assert infer_layer("pkg/render/render.go", "go") == "Service"
+ # Without the language (or for another language) the hint never fires.
+ assert infer_layer("internal/auth.go") == DEFAULT_LAYER
+ assert infer_layer("internal/auth.py", "python") == DEFAULT_LAYER
+ # A deeper generic hint still wins over the language hint.
+ assert infer_layer("internal/handlers/auth.go", "go") == "API"
+
+
+def test_infer_layer_rust_cli_hints():
+ assert infer_layer("src/bin/extra.rs", "rust") == "CLI"
+ assert infer_layer("crates/typst-cli/src/main.rs", "rust") == "CLI"
+ assert infer_layer("src/bin/extra.rs") == DEFAULT_LAYER
+ # Case-sensitive suffix; an unrelated "Bin" or non-rust file never matches.
+ assert infer_layer("crates/typst-cli/src/main.py", "python") == DEFAULT_LAYER
+ # A dir literally named "-cli" is not the convention (proper suffix only).
+ assert infer_layer("-cli/main.rs", "rust") == DEFAULT_LAYER
+
+
+def test_infer_layer_ruby_rails_jobs():
+ assert infer_layer("app/jobs/cleanup_job.rb", "ruby") == "Service"
+ assert infer_layer("app/jobs/cleanup.py", "python") == DEFAULT_LAYER
+
+
+def test_infer_layer_dotnet_project_suffixes():
+ assert infer_layer("src/Billing.Api/Program.cs", "csharp") == "API"
+ assert infer_layer("Billing.Domain/Invoice.cs", "csharp") == "Service"
+ assert infer_layer("Billing.Infrastructure/Repo.cs", "csharp") == "Data"
+ # Generic deeper dirs still win; lowercase variants are not the convention.
+ assert infer_layer("src/Billing.Api/models/Dto.cs", "csharp") == "Data"
+ assert infer_layer("billing.api/Program.cs", "csharp") == DEFAULT_LAYER
+
+
+def test_infer_layer_test_rules_beat_language_hints():
+ # A camel test inside a hinted dir is still a test.
+ assert infer_layer("internal/AuthTest.java", "java") == "Test"
+ assert infer_layer("pkg/render/render_test.go", "go") == "Test"
+
+
# ---------------------------------------------------------------------------
# compute_layer_order — top→bottom by dependency direction
# ---------------------------------------------------------------------------
@@ -77,3 +239,84 @@ def test_compute_layer_order_stable_without_edges():
def test_compute_layer_order_single_layer():
assert compute_layer_order({"a.py": "API"}, []) == ["API"]
assert compute_layer_order({}, []) == []
+
+
+def test_compute_layer_order_tests_never_top_the_stack():
+ # Tests import everything and are imported by nothing — by raw import
+ # math they'd win "top consumer" in every codebase. They must be pinned
+ # after the runtime layers instead.
+ file_layers = {
+ "api/h.py": "API",
+ "services/s.py": "Service",
+ "tests/test_h.py": "Test",
+ "tests/test_s.py": "Test",
+ }
+ edges = [
+ ("api/h.py", "services/s.py"),
+ ("tests/test_h.py", "api/h.py"),
+ ("tests/test_h.py", "services/s.py"),
+ ("tests/test_s.py", "services/s.py"),
+ ("tests/test_s.py", "api/h.py"),
+ ]
+ order = compute_layer_order(file_layers, edges)
+ assert order[-1] == "Test"
+ # Test edges don't distort the runtime ordering either.
+ assert order.index("API") < order.index("Service")
+
+
+class TestRubySpecDirToken:
+ def test_ruby_file_under_spec_is_test_without_corroboration(self):
+ # RSpec convention: support helpers and vendored fixtures under
+ # spec/ are test material whatever their filename.
+ assert infer_layer("sinatra-contrib/spec/okjson.rb", language="ruby") == "Test"
+
+ def test_spec_dir_stays_ambiguous_for_other_languages(self):
+ # Polyglot fairness: ruby's rule never leaks to other languages.
+ assert infer_layer("specs/openapi.yaml", language="yaml") != "Test"
+ assert infer_layer("spec/helper.py", language="python") != "Test"
+
+
+def test_infer_layer_gradle_test_sourcesets():
+ # okio regression: multiplatform test sourcesets (src/jvmTest,
+ # src/commonTest) are test roots for any file beneath them.
+ assert infer_layer("okio/src/jvmTest/kotlin/okio/AsyncSocket.kt", "kotlin") == "Test"
+ assert infer_layer("okio/src/commonTest/kotlin/okio/util/Helpers.kt", "kotlin") == "Test"
+ assert infer_layer("m/src/integrationTest/kotlin/F.kt", "kotlin") == "Test"
+ # Main sourcesets and non-src camel dirs stay untouched.
+ assert infer_layer("okio/src/commonMain/kotlin/okio/Buffer.kt", "kotlin") != "Test"
+ assert infer_layer("okio/src/hashFunctions/kotlin/H.kt", "kotlin") != "Test"
+ # The wildcard requires the camel "Test" suffix — lowercase doesn't fire
+ # (src/test is its own exact rule via the generic token).
+ assert infer_layer("a/src/latest/kotlin/F.kt", "kotlin") != "Test"
+
+
+def test_infer_layer_dotnet_specs_project_dirs():
+ # Polly evidence: BDD-style sibling test projects named Foo.Specs/.
+ assert infer_layer("test/Polly.Specs/Retry/RetrySpecs.cs", "csharp") == "Test"
+
+
+def test_infer_layer_c_cpp_include_is_api():
+ # A C/C++ library's installed public headers are its API surface.
+ assert infer_layer("include/uv.h", "c") == "API"
+ assert infer_layer("include/uv/unix.h", "c") == "API"
+ assert infer_layer("include/fmt/format.h", "cpp") == "API"
+ # Polyglot fairness: the hint rides on the file's own language.
+ assert infer_layer("include/util.py", "python") != "API"
+ # Root-anchored: okio's vendored linux uapi headers must not mint an
+ # API layer from deep inside a Kotlin repo.
+ assert infer_layer("okio/src/linuxMain/headers/include/uapi/linux/stat.h", "cpp") != "API"
+
+
+def test_is_support_path_covers_doc_dirs():
+ from repowise.core.generation.layers import is_support_path
+
+ # Doc sites and runnable doc snippets are support material (libuv's
+ # docs/code/*/main.c, docfx templates, vitepress sites).
+ assert is_support_path("docs/code/spawn/main.c")
+ assert is_support_path("docs/template/public/main.js")
+ assert is_support_path("website/.vitepress/theme/index.ts")
+ assert is_support_path("doc/build.py")
+ assert is_support_path("examples/hello/main.go")
+ # Real code is not support — names containing "docs" don't fire.
+ assert not is_support_path("src/docs_generator.py")
+ assert not is_support_path("lib/init.lua")
diff --git a/tests/unit/generation/test_models.py b/tests/unit/generation/test_models.py
index e73ec8d66..90822daf2 100644
--- a/tests/unit/generation/test_models.py
+++ b/tests/unit/generation/test_models.py
@@ -153,7 +153,7 @@ def test_generation_config_defaults():
assert config.staleness_threshold_days == 7
assert config.expiry_threshold_days == 30
assert config.top_symbol_percentile == 0.20
- assert config.module_grouping == "community"
+ assert config.module_grouping == "curated"
assert config.min_module_size == 3
assert config.large_file_source_pct == 0.4
assert config.reasoning == "auto"
diff --git a/tests/unit/generation/test_onboarding.py b/tests/unit/generation/test_onboarding.py
index f3b8700b1..b2a38a8a0 100644
--- a/tests/unit/generation/test_onboarding.py
+++ b/tests/unit/generation/test_onboarding.py
@@ -610,3 +610,60 @@ def test_subkind_template_renders(subkind_slot: str, ctx_factory: Any) -> None:
rendered = template.render(ctx=ctx, slot=subkind_slot)
assert rendered.strip() # non-empty
assert "{{" not in rendered # no unrendered Jinja
+
+
+def test_how_it_works_renders_curated_tour_steps() -> None:
+ """Curated tour steps (target_path + reason, no nodeIds/description) must
+ normalize into the strict template's expected shape — regression for the
+ first docs run against a curated KG ('dict object' has no attribute
+ 'nodeIds')."""
+ import dataclasses
+
+ spec = onboarding.get_spec(SLOT_HOW_IT_WORKS)
+ assert spec is not None
+ sig = _signals(
+ files=[_file("src/main.py", is_entry_point=True)],
+ entry_points=["src/main.py"],
+ )
+ curated_steps = (
+ {"order": 1, "target_path": "README.md", "page_type": "repo_overview",
+ "title": "README.md", "depth": 0, "kind": "overview",
+ "reason": "Start here for the end-to-end picture."},
+ {"order": 2, "target_path": "src/main.py", "page_type": "file_page",
+ "title": "main.py", "depth": 1, "kind": "code",
+ "reason": "An entry point — execution and imports fan out from here."},
+ )
+ sig = dataclasses.replace(sig, kg_tour_steps=curated_steps)
+ ctx = spec.build_context(sig)
+ assert ctx is not None
+ # Normalized: description fed from reason, nodeIds synthesized from target_path.
+ assert ctx.kg_tour_steps[0]["description"].startswith("Start here")
+ assert ctx.kg_tour_steps[1]["nodeIds"] == ["file:src/main.py"]
+
+ rendered = _jinja_env().get_template("onboarding/how_it_works.j2").render(ctx=ctx)
+ assert "`src/main.py`" in rendered
+ assert "An entry point" in rendered
+
+
+def test_how_it_works_renders_legacy_tour_steps() -> None:
+ """The pre-curation step shape (nodeIds + description) keeps working."""
+ import dataclasses
+
+ spec = onboarding.get_spec(SLOT_HOW_IT_WORKS)
+ assert spec is not None
+ sig = _signals(
+ files=[_file("src/main.py", is_entry_point=True)],
+ entry_points=["src/main.py"],
+ )
+ legacy_steps = (
+ {"order": 1, "title": "Start Here",
+ "description": "Begin with the entry point.",
+ "nodeIds": ["file:src/main.py"]},
+ )
+ sig = dataclasses.replace(sig, kg_tour_steps=legacy_steps)
+ ctx = spec.build_context(sig)
+ assert ctx is not None
+ assert ctx.kg_tour_steps[0]["description"] == "Begin with the entry point."
+ assert ctx.kg_tour_steps[0]["nodeIds"] == ["file:src/main.py"]
+ rendered = _jinja_env().get_template("onboarding/how_it_works.j2").render(ctx=ctx)
+ assert "`src/main.py`" in rendered
diff --git a/tests/unit/generation/test_page_generator.py b/tests/unit/generation/test_page_generator.py
index b79c51248..b1326b006 100644
--- a/tests/unit/generation/test_page_generator.py
+++ b/tests/unit/generation/test_page_generator.py
@@ -448,3 +448,154 @@ def test_compute_cache_key_varies_by_language():
assert gen_en._compute_cache_key("file_page", "x") != gen_ru._compute_cache_key(
"file_page", "x"
)
+
+
+async def test_generate_all_uses_in_memory_kg_modules_without_artifact_file():
+ """Curated module pages must come from the IN-MEMORY pipeline modules.
+
+ The knowledge-graph.json artifact is written AFTER generation, so on a
+ fresh init it does not exist when selection runs — relying on the file
+ silently fell back to community grouping (caught live on repowise's own
+ wiki: 20 community-N module pages on a curated run).
+ """
+ config = GenerationConfig(
+ max_tokens=256,
+ token_budget=100_000,
+ max_concurrency=2,
+ module_grouping="curated",
+ min_module_size=2,
+ coverage_pct=1.0,
+ module_page_share=1.0,
+ dedupe_near_clones=False, # synthetic files are identical by design
+ )
+ provider = MockProvider()
+ assembler = ContextAssembler(config)
+ gen = PageGenerator(provider, assembler, config)
+
+ paths = [f"pkg/core/m{i}.py" for i in range(3)] + [f"pkg/web/w{i}.py" for i in range(3)]
+ parsed = []
+ for p in paths:
+ fi = _make_file_info(p, language="python")
+ sym = _make_symbol(file_path=p)
+ parsed.append(
+ ParsedFile(
+ file_info=fi, symbols=[sym], imports=[], exports=[],
+ docstring=None, parse_errors=[],
+ )
+ )
+ repo = RepoStructure(
+ is_monorepo=False,
+ packages=[],
+ root_language_distribution={"python": 1.0},
+ total_files=len(paths),
+ total_loc=100,
+ entry_points=[],
+ )
+ kg_modules = [
+ {
+ "id": "module:pkg-core",
+ "name": "core",
+ "path": "pkg/core",
+ "layerId": "layer:service",
+ "nodeIds": [f"file:{p}" for p in paths if "/core/" in p],
+ "language": "python",
+ },
+ {
+ "id": "module:pkg-web",
+ "name": "web",
+ "path": "pkg/web",
+ "layerId": "layer:ui",
+ "nodeIds": [f"file:{p}" for p in paths if "/web/" in p],
+ "language": "python",
+ },
+ ]
+
+ builder = _make_builder_with(parsed)
+ # repo_path deliberately omitted → no knowledge-graph.json on disk.
+ pages = await gen.generate_all(
+ parsed,
+ {p: b"pass" for p in paths},
+ builder,
+ repo,
+ "test-repo",
+ kg_modules=kg_modules,
+ )
+
+ module_pages = [p for p in pages if p.page_type == "module_page"]
+ targets = {p.target_path for p in module_pages}
+ assert targets, "no module pages generated"
+ assert targets <= {"pkg/core", "pkg/web"}, targets
+ assert not any(t.startswith("community-") for t in targets)
+
+
+async def test_generate_all_builds_kg_ctx_from_in_memory_kg_data():
+ """Layer pages must generate on a FRESH init via the in-memory KG.
+
+ kg_ctx previously only read knowledge-graph.json, which is written during
+ persistence — after generation — so first-run wikis silently had zero
+ layer pages (caught live: fresh repowise wiki had 37 module pages and no
+ Architecture layers).
+ """
+ config = GenerationConfig(
+ max_tokens=256,
+ token_budget=100_000,
+ max_concurrency=2,
+ coverage_pct=1.0,
+ dedupe_near_clones=False,
+ )
+ provider = MockProvider()
+ assembler = ContextAssembler(config)
+ gen = PageGenerator(provider, assembler, config)
+
+ paths = [f"pkg/core/m{i}.py" for i in range(4)]
+ parsed = []
+ for p in paths:
+ fi = _make_file_info(p, language="python")
+ sym = _make_symbol(file_path=p)
+ parsed.append(
+ ParsedFile(
+ file_info=fi, symbols=[sym], imports=[], exports=[],
+ docstring=None, parse_errors=[],
+ )
+ )
+ repo = RepoStructure(
+ is_monorepo=False,
+ packages=[],
+ root_language_distribution={"python": 1.0},
+ total_files=len(paths),
+ total_loc=100,
+ entry_points=[],
+ )
+ kg_data = {
+ "version": "1.0.0",
+ "project": {"name": "test-repo", "total_files": len(paths), "entry_points": []},
+ "nodes": [
+ {"id": f"file:{p}", "type": "file", "filePath": p, "language": "python"}
+ for p in paths
+ ],
+ "edges": [],
+ "layers": [
+ {
+ "id": "layer:service",
+ "name": "Service",
+ "nodeIds": [f"file:{p}" for p in paths],
+ "display_order": 0,
+ }
+ ],
+ "tour": [],
+ }
+
+ builder = _make_builder_with(parsed)
+ # repo_path deliberately omitted → no knowledge-graph.json on disk.
+ pages = await gen.generate_all(
+ parsed,
+ {p: b"pass" for p in paths},
+ builder,
+ repo,
+ "test-repo",
+ kg_data=kg_data,
+ )
+
+ layer_pages = [p for p in pages if p.page_type == "layer_page"]
+ assert layer_pages, "no layer pages generated from in-memory KG"
+ assert any("Service" in p.title for p in layer_pages)
diff --git a/tests/unit/generation/test_provenance.py b/tests/unit/generation/test_provenance.py
index 3ee8edcf1..b956f9134 100644
--- a/tests/unit/generation/test_provenance.py
+++ b/tests/unit/generation/test_provenance.py
@@ -31,6 +31,7 @@ def _ctx(**over):
base = dict(
file_path="pkg/foo.py",
kg_layer_name="",
+ kg_layer_id="",
kg_layer_role="",
dependencies=[],
decision_records=[],
@@ -41,17 +42,28 @@ def _ctx(**over):
def test_layer_metadata_attached():
page = _page()
- _attach_file_provenance(page, _ctx(kg_layer_name="Domain", kg_layer_role="entry_point"))
+ _attach_file_provenance(
+ page,
+ _ctx(
+ kg_layer_name="Domain",
+ kg_layer_id="layer:domain",
+ kg_layer_role="entry_point",
+ ),
+ )
assert page.metadata["layer_name"] == "Domain"
+ # Stable slug id is attached so the UI joins file -> layer page by id.
+ assert page.metadata["layer_id"] == "layer:domain"
assert page.metadata["layer_role"] == "entry_point"
def test_no_kg_layer_falls_back_to_inferred_layer():
# Every file page must carry a layer_name so the Architecture tree can
- # group it; with no KG layer it is inferred from the path.
+ # group it; with no KG layer it is inferred from the path, and the
+ # layer_id is the slug of that inferred name.
page = _page()
_attach_file_provenance(page, _ctx(file_path="src/api/users.py"))
assert page.metadata["layer_name"] == "API"
+ assert page.metadata["layer_id"] == "layer:api"
# No KG role is invented for the fallback path.
assert "layer_role" not in page.metadata
diff --git a/tests/unit/generation/test_selection_curated_modules.py b/tests/unit/generation/test_selection_curated_modules.py
new file mode 100644
index 000000000..43ff6c195
--- /dev/null
+++ b/tests/unit/generation/test_selection_curated_modules.py
@@ -0,0 +1,278 @@
+"""Curated module grouping in the selection layer.
+
+Covers the ``module_grouping="curated"`` source (key = real dir path,
+display = curated name, cohesion = None, Σ-PageRank ranking), every row of
+the fallback matrix, and the golden inertness contract: with the default
+``"community"`` grouping, passing ``kg_modules`` changes NOTHING — the
+ship-dark guarantee that every existing path stays byte-identical.
+"""
+
+from __future__ import annotations
+
+from repowise.core.generation.models import GenerationConfig
+from repowise.core.generation.selection import SelectionInputs, select_pages
+from repowise.core.generation.selection.selector import _build_module_groups
+from tests.unit.generation.test_selection_budget import (
+ FakeFileInfo,
+ FakeParsedFile,
+ FakeSymbol,
+ _build_synthetic_repo,
+)
+
+# ---------------------------------------------------------------------------
+# Fixtures
+# ---------------------------------------------------------------------------
+
+
+def _repo_with_modules():
+ """A synthetic repo plus a matching curated-modules artifact."""
+ paths = (
+ [f"packages/app/src/core/ingestion/f{i}.py" for i in range(8)]
+ + [f"packages/app/src/core/analysis/f{i}.py" for i in range(6)]
+ + [f"packages/app/src/ui/c4/f{i}.py" for i in range(5)]
+ + ["packages/app/src/ui/tiny/f0.py", "packages/app/src/ui/tiny/f1.py"]
+ )
+ parsed = [
+ FakeParsedFile(file_info=FakeFileInfo(path=p), symbols=[FakeSymbol(name="fn")])
+ for p in paths
+ ]
+ # ui/c4 members carry the highest PageRank so Σ-PageRank must rank that
+ # module first despite it being smaller than core/ingestion.
+ pagerank = {p: (1.0 if "/ui/c4/" in p else 0.1) for p in paths}
+ community = {p: (0 if "/core/" in p else 1) for p in paths}
+
+ modules = [
+ {
+ "id": "module:packages-app-src-core-ingestion",
+ "name": "core/ingestion",
+ "path": "packages/app/src/core/ingestion",
+ "layerId": "layer:service",
+ "nodeIds": [f"file:{p}" for p in paths if "/core/ingestion/" in p],
+ "language": "python",
+ },
+ {
+ "id": "module:packages-app-src-core-analysis",
+ "name": "core/analysis",
+ "path": "packages/app/src/core/analysis",
+ "layerId": "layer:service",
+ "nodeIds": [f"file:{p}" for p in paths if "/core/analysis/" in p],
+ "language": "python",
+ },
+ {
+ "id": "module:packages-app-src-ui-c4",
+ "name": "ui/c4",
+ "path": "packages/app/src/ui/c4",
+ "layerId": "layer:ui",
+ "nodeIds": [f"file:{p}" for p in paths if "/ui/c4/" in p],
+ "language": "python",
+ },
+ {
+ # Below min_module_size=3 → must be skipped, never a page.
+ "id": "module:packages-app-src-ui-tiny",
+ "name": "ui/tiny",
+ "path": "packages/app/src/ui/tiny",
+ "layerId": "layer:ui",
+ "nodeIds": [f"file:{p}" for p in paths if "/ui/tiny/" in p],
+ "language": "python",
+ },
+ ]
+ return parsed, pagerank, community, modules
+
+
+def _inputs(parsed, pagerank, community, *, cfg=None, kg_modules=None):
+ return SelectionInputs(
+ parsed_files=parsed,
+ pagerank=pagerank,
+ betweenness=dict.fromkeys(pagerank, 0.0),
+ community=community,
+ community_info=None,
+ sccs=[],
+ git_meta_map=None,
+ config=cfg or GenerationConfig(),
+ kg_modules=kg_modules,
+ )
+
+
+def _cfg(grouping: str) -> GenerationConfig:
+ return GenerationConfig(module_grouping=grouping)
+
+
+# ---------------------------------------------------------------------------
+# Curated grouping source
+# ---------------------------------------------------------------------------
+
+
+class TestCuratedGrouping:
+ def test_groups_keyed_by_dir_path_with_curated_names(self):
+ parsed, pr, comm, modules = _repo_with_modules()
+ groups = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("curated"), kg_modules=modules)
+ )
+ by_key = {g.key: g for _, g in groups}
+ assert "packages/app/src/core/ingestion" in by_key
+ g = by_key["packages/app/src/core/ingestion"]
+ assert g.display == "core/ingestion"
+ assert g.label == "core/ingestion"
+ assert g.cohesion is None
+ assert g.language == "python"
+ assert len(g.file_paths) == 8
+
+ def test_ranked_by_sum_pagerank_of_members(self):
+ parsed, pr, comm, modules = _repo_with_modules()
+ groups = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("curated"), kg_modules=modules)
+ )
+ # ui/c4: 5 x 1.0 = 5.0 beats core/ingestion: 8 x 0.1 = 0.8.
+ assert groups[0][1].display == "ui/c4"
+ scores = [s for s, _ in groups]
+ assert scores == sorted(scores, reverse=True)
+
+ def test_min_module_size_floor_kills_tiny_modules(self):
+ parsed, pr, comm, modules = _repo_with_modules()
+ groups = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("curated"), kg_modules=modules)
+ )
+ assert "packages/app/src/ui/tiny" not in {g.key for _, g in groups}
+
+ def test_members_restricted_to_parsed_code_files(self):
+ parsed, pr, comm, modules = _repo_with_modules()
+ modules[0]["nodeIds"].append("file:packages/app/src/core/ingestion/ghost.py")
+ groups = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("curated"), kg_modules=modules)
+ )
+ by_key = {g.key: g for _, g in groups}
+ assert not any(
+ "ghost" in p
+ for p in by_key["packages/app/src/core/ingestion"].file_paths
+ )
+
+ def test_no_community_ids_in_curated_keys(self):
+ parsed, pr, comm, modules = _repo_with_modules()
+ groups = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("curated"), kg_modules=modules)
+ )
+ assert not any(g.key.startswith("community-") for _, g in groups)
+
+
+# ---------------------------------------------------------------------------
+# Fallback matrix (one test per row)
+# ---------------------------------------------------------------------------
+
+
+class TestFallbackMatrix:
+ def test_curated_without_artifact_falls_back_to_community(self):
+ """curation off / degraded / no KG json → today's community path."""
+ parsed, pr, _bet, comm = _build_synthetic_repo(100)
+ curated_no_artifact = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("curated"), kg_modules=None)
+ )
+ community = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("community"))
+ )
+ assert curated_no_artifact == community
+
+ def test_curated_with_all_modules_below_floor_emits_none_not_community(self):
+ """A present-but-filtered artifact must not mix vocabularies."""
+ parsed, pr, comm, modules = _repo_with_modules()
+ tiny_only = [m for m in modules if m["name"] == "ui/tiny"]
+ groups = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("curated"), kg_modules=tiny_only)
+ )
+ assert groups == []
+
+ def test_explicit_community_honored_even_with_artifact(self):
+ parsed, pr, comm, modules = _repo_with_modules()
+ with_artifact = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("community"), kg_modules=modules)
+ )
+ without = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("community"))
+ )
+ assert with_artifact == without
+ assert not any(g.key.startswith("packages/") for _, g in with_artifact)
+
+ def test_explicit_top_dir_honored_even_with_artifact(self):
+ parsed, pr, comm, modules = _repo_with_modules()
+ with_artifact = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("top_dir"), kg_modules=modules)
+ )
+ without = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("top_dir"))
+ )
+ assert with_artifact == without
+ assert {g.key for _, g in with_artifact} == {"packages"}
+
+
+# ---------------------------------------------------------------------------
+# Golden inertness — the ship-dark contract
+# ---------------------------------------------------------------------------
+
+
+class TestGoldenByteIdentity:
+ def test_community_selection_identical_with_and_without_kg_modules(self):
+ """With the "community" escape hatch, kg_modules must change NOTHING.
+
+ This was the ship-dark rollout guarantee while "community" was the
+ default; post-flip it pins the revert story — setting
+ module_grouping="community" restores the pre-curation selection
+ byte-for-byte regardless of what the KG artifact carries.
+ """
+ parsed, pr, bet, comm = _build_synthetic_repo(300)
+ _, _, _, modules = _repo_with_modules()
+ cfg = GenerationConfig(module_grouping="community")
+
+ def run(kg_modules):
+ return select_pages(
+ SelectionInputs(
+ parsed_files=parsed,
+ pagerank=pr,
+ betweenness=bet,
+ community=comm,
+ community_info=None,
+ sccs=[],
+ git_meta_map=None,
+ config=cfg,
+ kg_modules=kg_modules,
+ )
+ )
+
+ assert run(None) == run(modules)
+
+ def test_curated_selection_is_deterministic(self):
+ parsed, pr, comm, modules = _repo_with_modules()
+ cfg = _cfg("curated")
+
+ def run():
+ return select_pages(
+ _inputs(parsed, pr, comm, cfg=cfg, kg_modules=modules)
+ )
+
+ a, b = run(), run()
+ assert a.module_groups == b.module_groups
+ assert a == b
+
+
+class TestWholeLayerDedupe:
+ """Modules 1:1 with a layer never get a module page (layer_page covers them)."""
+
+ def test_whole_layer_module_skipped(self):
+ parsed, pr, comm, modules = _repo_with_modules()
+ modules = [dict(m) for m in modules]
+ modules[0]["wholeLayer"] = True # core/ingestion now 1:1 with its layer
+ groups = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("curated"), kg_modules=modules)
+ )
+ keys = {g.key for _, g in groups}
+ assert "packages/app/src/core/ingestion" not in keys
+ assert "packages/app/src/ui/c4" in keys
+
+ def test_all_whole_layer_yields_no_module_pages_not_community(self):
+ # Flat-lib shape: every module is 1:1 with a layer → zero module
+ # pages, and NO fallback to community grouping (vocabulary stays
+ # curated; the layer pages carry the documentation).
+ parsed, pr, comm, modules = _repo_with_modules()
+ modules = [dict(m, wholeLayer=True) for m in modules]
+ groups = _build_module_groups(
+ _inputs(parsed, pr, comm, cfg=_cfg("curated"), kg_modules=modules)
+ )
+ assert groups == []
diff --git a/tests/unit/generation/test_tour.py b/tests/unit/generation/test_tour.py
index 44f6ec60b..6391754e2 100644
--- a/tests/unit/generation/test_tour.py
+++ b/tests/unit/generation/test_tour.py
@@ -16,6 +16,7 @@ from repowise.core.generation.tour import (
class _FI:
path: str
is_entry_point: bool = False
+ language: str = "python"
@dataclass
@@ -46,6 +47,19 @@ def test_score_entry_points_excludes_zero_score():
assert score_entry_points(files, pr) == []
+def test_score_entry_points_withholds_stem_bonus_from_docs():
+ # docs/index.md has an entry-style stem but is markdown — it must never
+ # outrank a real main.py, even when ingestion's stem rule flagged it.
+ files = [
+ _PF(_FI(path="docs/index.md", language="markdown", is_entry_point=True)),
+ _PF(_FI(path="src/main.py")),
+ ]
+ pr = {"docs/index.md": 0.9, "src/main.py": 0.5}
+ scored = {p: s for s, p in score_entry_points(files, pr)}
+ assert scored["src/main.py"] >= 3.0
+ assert scored.get("docs/index.md", 0.0) < 3.0
+
+
# ---------------------------------------------------------------------------
# Landmarks
# ---------------------------------------------------------------------------
@@ -103,6 +117,78 @@ def test_build_tour_weaves_infra_last():
assert stops[-1].target_path == "Dockerfile"
+def test_build_tour_unreached_files_get_honest_reasons():
+ # disconnected.py is never reached from the entry point — its reason must
+ # not claim it was "reached N imports deep".
+ files = _repo({"main.py": True, "a.py": False, "disconnected.py": False})
+ pr = {"main.py": 0.9, "a.py": 0.5, "disconnected.py": 0.1}
+ edges = [("main.py", "a.py")]
+ stops = build_tour(
+ files, pr, edges, file_page_paths={"main.py", "a.py", "disconnected.py"}
+ )
+ by_path = {s.target_path: s for s in stops}
+ assert "Off the import path" in by_path["disconnected.py"].reason
+ assert "Reached" not in by_path["disconnected.py"].reason
+ assert "Directly used" in by_path["a.py"].reason # reached ones unchanged
+
+
+def test_score_entry_points_withholds_entry_bonuses_from_examples():
+ # examples/*/main.go are entries by *name* only — the library itself
+ # must outrank them.
+ files = [
+ _PF(_FI(path="_examples/hello-world/main.go", is_entry_point=True)),
+ _PF(_FI(path="cmd/app/main.go", is_entry_point=True)),
+ ]
+ pr = {"_examples/hello-world/main.go": 0.9, "cmd/app/main.go": 0.5}
+ scored = {p: s for s, p in score_entry_points(files, pr)}
+ assert scored["cmd/app/main.go"] >= 3.0
+ assert scored.get("_examples/hello-world/main.go", 0.0) < 3.0
+
+
+def test_score_entry_points_withholds_entry_bonuses_from_test_files():
+ # tests/testserver/server.py has an entry-style stem, but a test fixture
+ # must never seed the onboarding walk.
+ files = [
+ _PF(_FI(path="tests/testserver/server.py", is_entry_point=True)),
+ _PF(_FI(path="src/pkg/models.py")),
+ ]
+ pr = {"tests/testserver/server.py": 0.9, "src/pkg/models.py": 0.5}
+ scored = {p: s for s, p in score_entry_points(files, pr)}
+ assert scored.get("tests/testserver/server.py", 0.0) < 3.0
+
+
+def test_build_tour_seedless_repo_reasons_do_not_overclaim():
+ # A flat library with no entry-style file: steps must not reference
+ # entry points that don't exist.
+ files = _repo({"src/pkg/models.py": False, "src/pkg/cookies.py": False})
+ pr = {"src/pkg/models.py": 0.8, "src/pkg/cookies.py": 0.6}
+ stops = build_tour(
+ files, pr, [], file_page_paths={"src/pkg/models.py", "src/pkg/cookies.py"}
+ )
+ for s in stops:
+ assert "An entry point" not in s.reason
+ # the offending phrase referenced entry points that don't exist;
+ # evidence-free parked files now say "Off the import paths walked
+ # above" instead, which references only the walk itself
+ assert "from the entry points" not in s.reason
+
+
+def test_build_tour_seedless_anchor_is_a_code_file():
+ # The fallback anchor must skip docs/config — a CLAUDE.md at the root
+ # outscores deep code files but cannot anchor an import walk.
+ files = [
+ _PF(_FI(path=".claude/CLAUDE.md", language="markdown")),
+ _PF(_FI(path="src/pkg/api.py")),
+ _PF(_FI(path="src/pkg/models.py")),
+ ]
+ pr = {".claude/CLAUDE.md": 0.9, "src/pkg/api.py": 0.5, "src/pkg/models.py": 0.4}
+ edges = [("src/pkg/api.py", "src/pkg/models.py")]
+ documented = {".claude/CLAUDE.md", "src/pkg/api.py", "src/pkg/models.py"}
+ stops = build_tour(files, pr, edges, file_page_paths=documented)
+ anchor = next(s for s in stops if s.depth == 0 and s.kind == "code")
+ assert anchor.target_path == "src/pkg/api.py"
+
+
def test_build_tour_respects_max_stops():
files = _repo({f"f{i}.py": (i == 0) for i in range(50)})
pr = {f"f{i}.py": 1.0 - i * 0.01 for i in range(50)}
@@ -110,3 +196,170 @@ def test_build_tour_respects_max_stops():
documented = {f"f{i}.py" for i in range(50)}
stops = build_tour(files, pr, edges, file_page_paths=documented, repo_name="r")
assert len(stops) <= DEFAULT_MAX_STOPS
+
+
+def test_score_entry_points_withholds_bonuses_from_api_contracts_and_infra():
+ # Schema/data languages (graphql, proto, sql, openapi) and
+ # infra wiring (shell, terraform, dockerfile) never earn entry bonuses,
+ # however entry-like their stems are.
+ files = [
+ _PF(_FI(path="index.graphql", language="graphql", is_entry_point=True)),
+ _PF(_FI(path="main.sql", language="sql", is_entry_point=True)),
+ _PF(_FI(path="run.sh", language="shell", is_entry_point=True)),
+ _PF(_FI(path="main.tf", language="terraform", is_entry_point=True)),
+ _PF(_FI(path="src/main.py")),
+ ]
+ pr = {p.file_info.path: 0.5 for p in files}
+ scored = {p: s for s, p in score_entry_points(files, pr)}
+ assert scored["src/main.py"] >= 3.0
+ for path in ("index.graphql", "main.sql", "run.sh", "main.tf"):
+ assert scored.get(path, 0.0) < 3.0, path
+
+
+def test_build_tour_anchor_reasons_never_claim_entry_points():
+ # Anchor-seeded walks (no genuine entries) must not say "the entry
+ # points above" — there are none.
+ files = [
+ _PF(_FI(path="src/core.py")),
+ _PF(_FI(path="src/helper.py")),
+ _PF(_FI(path="src/deep.py")),
+ ]
+ pr = {"src/core.py": 0.5, "src/helper.py": 0.3, "src/deep.py": 0.2}
+ edges = [("src/core.py", "src/helper.py"), ("src/helper.py", "src/deep.py")]
+ documented = {"src/core.py", "src/helper.py", "src/deep.py"}
+ stops = build_tour(files, pr, edges, file_page_paths=documented)
+ for s in stops:
+ assert "entry point" not in s.reason or s.depth == 0, s.reason
+ anchor = next(s for s in stops if s.depth == 0)
+ assert "anchor" in anchor.reason
+ d1 = next(s for s in stops if s.depth == 1)
+ assert "anchor" in d1.reason and "entry points" not in d1.reason
+
+
+def test_build_tour_unreached_non_code_files_take_no_slot():
+ # D-037 watch item: sparse-mode walks filled their budget with
+ # CHANGELOG.md / *.toml "not on the resolved import paths" slots.
+ # Unreached documents and config can never be on an import path —
+ # they are not worth a step that displaces code.
+ files = [
+ _PF(_FI(path="lib/init.lua", language="luau", is_entry_point=True)),
+ _PF(_FI(path="lib/util.lua", language="luau")),
+ _PF(_FI(path="CHANGELOG.md", language="markdown")),
+ _PF(_FI(path="wally.toml", language="toml")),
+ ]
+ pr = {p: 0.25 for p in ("lib/init.lua", "lib/util.lua", "CHANGELOG.md", "wally.toml")}
+ edges = [("lib/init.lua", "lib/util.lua")]
+ documented = {"lib/init.lua", "lib/util.lua", "CHANGELOG.md", "wally.toml"}
+ stops = build_tour(files, pr, edges, file_page_paths=documented, graph_mode="sparse")
+ paths = {s.target_path for s in stops}
+ assert "CHANGELOG.md" not in paths
+ assert "wally.toml" not in paths
+ assert {"lib/init.lua", "lib/util.lua"} <= paths
+
+
+def test_build_tour_reached_config_keeps_its_slot():
+ # A config file genuinely on an import path (TS importing data.json)
+ # keeps its step — only *unreached* non-code is exempt from parking.
+ files = [
+ _PF(_FI(path="src/index.ts", language="typescript", is_entry_point=True)),
+ _PF(_FI(path="src/config.json", language="json")),
+ ]
+ pr = {"src/index.ts": 0.6, "src/config.json": 0.4}
+ edges = [("src/index.ts", "src/config.json")]
+ documented = {"src/index.ts", "src/config.json"}
+ stops = build_tour(files, pr, edges, file_page_paths=documented)
+ assert "src/config.json" in {s.target_path for s in stops}
+
+
+# ---------------------------------------------------------------------------
+# Wiring-stub entry co-anchor
+# ---------------------------------------------------------------------------
+
+
+def _stub_entry_repo():
+ """An OTP-style library: the only entry is a supervision stub whose
+ forward BFS reaches nothing, while a hub file's imports fan out wide."""
+ paths = {
+ "lib/app/application.ex": True, # wiring stub — no outgoing imports
+ "lib/encode.ex": False,
+ "lib/codegen.ex": False,
+ "lib/fragment.ex": False,
+ "lib/decoder.ex": False,
+ "lib/helpers.ex": False,
+ "lib/sigil.ex": False,
+ "lib/jason.ex": False,
+ }
+ files = [_PF(_FI(path=p, is_entry_point=e, language="elixir")) for p, e in paths.items()]
+ edges = [
+ ("lib/encode.ex", "lib/codegen.ex"),
+ ("lib/encode.ex", "lib/fragment.ex"),
+ ("lib/encode.ex", "lib/jason.ex"),
+ ("lib/codegen.ex", "lib/decoder.ex"),
+ ]
+ pr = dict.fromkeys(paths, 0.1)
+ return files, pr, edges, set(paths)
+
+
+def test_wiring_stub_entry_gets_a_co_anchor():
+ files, pr, edges, documented = _stub_entry_repo()
+ stops = build_tour(files, pr, edges, file_page_paths=documented)
+ by_path = {s.target_path: s for s in stops}
+ # the entry keeps its step and wording
+ assert "An entry point" in by_path["lib/app/application.ex"].reason
+ # the widest-fanout file co-anchors at depth 0 with anchor wording
+ anchor = by_path["lib/encode.ex"]
+ assert anchor.depth == 0
+ assert "entry point above only wires" in anchor.reason
+ # the walk actually proceeds through the anchor's imports
+ assert by_path["lib/codegen.ex"].depth == 1
+ assert "anchor above" in by_path["lib/codegen.ex"].reason
+ assert by_path["lib/decoder.ex"].depth == 2
+
+
+def test_entry_with_real_reach_gets_no_co_anchor():
+ paths = {
+ "src/main.py": True,
+ "src/a.py": False,
+ "src/b.py": False,
+ "src/c.py": False,
+ "src/hub.py": False,
+ "src/d.py": False,
+ "src/e.py": False,
+ "src/f.py": False,
+ }
+ files = _repo(paths)
+ edges = [
+ ("src/main.py", "src/a.py"),
+ ("src/a.py", "src/b.py"),
+ ("src/b.py", "src/c.py"),
+ # a hub with wide fanout that must NOT displace the real entry walk
+ ("src/hub.py", "src/d.py"),
+ ("src/hub.py", "src/e.py"),
+ ("src/hub.py", "src/f.py"),
+ ]
+ pr = dict.fromkeys(paths, 0.1)
+ stops = build_tour(files, pr, edges, file_page_paths=set(paths))
+ by_path = {s.target_path: s for s in stops}
+ assert "An entry point" in by_path["src/main.py"].reason
+ assert "only wires" not in " ".join(s.reason for s in stops)
+
+
+# ---------------------------------------------------------------------------
+# Manifests never park
+# ---------------------------------------------------------------------------
+
+
+def test_unreached_manifest_never_parks():
+ paths = {
+ "lib/core.ex": False,
+ "lib/util.ex": False,
+ "mix.exs": False,
+ "project.clj": False,
+ }
+ files = [_PF(_FI(path=p, is_entry_point=False, language="elixir")) for p in paths]
+ edges = [("lib/core.ex", "lib/util.ex")]
+ pr = dict.fromkeys(paths, 0.1)
+ stops = build_tour(files, pr, edges, file_page_paths=set(paths))
+ visited = {s.target_path for s in stops}
+ assert "mix.exs" not in visited
+ assert "project.clj" not in visited
diff --git a/tests/unit/generation/test_wiki_tour_adoption.py b/tests/unit/generation/test_wiki_tour_adoption.py
new file mode 100644
index 000000000..d94bc9632
--- /dev/null
+++ b/tests/unit/generation/test_wiki_tour_adoption.py
@@ -0,0 +1,91 @@
+"""The wiki guided tour adopts the curated KG tour when one exists.
+
+One tour, every surface: when the indexed knowledge graph went through
+curation (marked by ``project.graph_mode``), the page orchestrator must use
+its tour verbatim instead of re-deriving a second, divergent ordering from
+the raw graph. Without a curated KG it falls back to computing the tour.
+"""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+from repowise.core.generation.kg_context import KnowledgeGraphContext
+from repowise.core.generation.page_generator.orchestrate import _GenerationRun
+
+
+def _write_kg(tmp_path, kg: dict):
+ kg_path = tmp_path / ".repowise" / "knowledge-graph.json"
+ kg_path.parent.mkdir(parents=True, exist_ok=True)
+ kg_path.write_text(json.dumps(kg))
+ return kg_path
+
+
+def _run_stub(kg_ctx) -> SimpleNamespace:
+ """The minimal duck-typed surface _compute_ia touches."""
+ stub = SimpleNamespace(
+ kg_ctx=kg_ctx,
+ tour_stops=[],
+ layer_order=[],
+ parsed_files=[],
+ pagerank={},
+ sel_file_paths=[],
+ sel_infra_paths=[],
+ repo_name="test",
+ )
+ stub._file_import_edges = lambda: []
+ return stub
+
+
+CURATED_TOUR = [
+ {"order": 1, "target_path": "README.md", "page_type": "repo_overview",
+ "title": "README.md", "depth": 0, "kind": "overview",
+ "reason": "Start here for the end-to-end picture before diving into the code.",
+ "layer_id": "layer:app"},
+ {"order": 2, "target_path": "src/main.py", "page_type": "file_page",
+ "title": "main.py", "depth": 1, "kind": "code",
+ "reason": "An entry point — execution and imports fan out from here.",
+ "layer_id": "layer:app"},
+]
+
+
+def test_curated_tour_adopted_verbatim(tmp_path):
+ kg_path = _write_kg(
+ tmp_path,
+ {
+ "project": {"name": "test", "graph_mode": "flow"},
+ "nodes": [], "edges": [], "layers": [],
+ "tour": CURATED_TOUR,
+ },
+ )
+ run = _run_stub(KnowledgeGraphContext(kg_path))
+ _GenerationRun._compute_ia(run)
+ assert [s["target_path"] for s in run.tour_stops] == ["README.md", "src/main.py"]
+ assert run.tour_stops[1]["reason"].startswith("An entry point")
+
+
+def test_uncurated_kg_falls_back_to_computed_tour(tmp_path):
+ # No graph_mode marker: the KG (and its tour, if any) predate curation —
+ # the orchestrator must compute its own tour, not adopt a stale one.
+ kg_path = _write_kg(
+ tmp_path,
+ {
+ "project": {"name": "test"},
+ "nodes": [], "edges": [], "layers": [],
+ "tour": [{"order": 1, "title": "old-style", "description": "x",
+ "nodeIds": []}],
+ },
+ )
+ run = _run_stub(KnowledgeGraphContext(kg_path))
+ _GenerationRun._compute_ia(run)
+ assert all(s.get("title") != "old-style" for s in run.tour_stops)
+
+
+def test_no_kg_computes_tour(tmp_path):
+ run = _run_stub(KnowledgeGraphContext(None))
+ _GenerationRun._compute_ia(run)
+ # The fallback build_tour ran: with nothing selected it yields just the
+ # overview stop, never an adopted (layer_id-carrying) curated step.
+ assert all("layer_id" not in s for s in run.tour_stops)
+ assert [s["kind"] for s in run.tour_stops] == ["overview"]
diff --git a/tests/unit/ingestion/parser/test_commonjs_require.py b/tests/unit/ingestion/parser/test_commonjs_require.py
index d93e64328..a520d4a64 100644
--- a/tests/unit/ingestion/parser/test_commonjs_require.py
+++ b/tests/unit/ingestion/parser/test_commonjs_require.py
@@ -43,3 +43,70 @@ def test_multi_declarator_require_keeps_both(parser: ASTParser) -> None:
def test_var_require_is_extracted(parser: ASTParser) -> None:
result = _parse(parser, "var svc = require('./svc');\n")
assert any(i.module_path == "./svc" for i in result.imports)
+
+
+def test_module_exports_require_is_reexport_import(parser: ASTParser) -> None:
+ # express's exact root shape: module.exports = require('./lib/express')
+ result = _parse(parser, "'use strict';\nmodule.exports = require('./lib/express');\n")
+ imp = next(i for i in result.imports if i.module_path == "./lib/express")
+ assert imp.is_reexport is True
+ assert imp.imported_names == ["*"]
+
+
+def test_exports_property_require_is_reexport(parser: ASTParser) -> None:
+ result = _parse(parser, "exports.json = require('./json');\n")
+ imp = next(i for i in result.imports if i.module_path == "./json")
+ assert imp.is_reexport is True
+
+
+def test_module_exports_property_require_is_reexport(parser: ASTParser) -> None:
+ result = _parse(parser, "module.exports.Router = require('./router');\n")
+ imp = next(i for i in result.imports if i.module_path == "./router")
+ assert imp.is_reexport is True
+
+
+def test_object_assign_hub_keeps_every_require(parser: ASTParser) -> None:
+ result = _parse(
+ parser,
+ "Object.assign(module.exports, require('./a'), require('./b'));\n",
+ )
+ modules = sorted(i.module_path for i in result.imports)
+ assert modules == ["./a", "./b"]
+ assert all(i.is_reexport for i in result.imports)
+
+
+def test_object_assign_non_exports_target_imports_without_reexport(
+ parser: ASTParser,
+) -> None:
+ # Object.assign(app.locals, require('./defaults')) is a real dependency
+ # but not a re-export.
+ result = _parse(parser, "Object.assign(app.locals, require('./defaults'));\n")
+ imp = next(i for i in result.imports if i.module_path == "./defaults")
+ assert imp.is_reexport is False
+
+
+def test_member_assignment_require_imports_without_reexport(parser: ASTParser) -> None:
+ result = _parse(parser, "cache.store = require('./store');\n")
+ imp = next(i for i in result.imports if i.module_path == "./store")
+ assert imp.is_reexport is False
+
+
+def test_const_require_unaffected_by_cjs_statement_branch(parser: ASTParser) -> None:
+ result = _parse(parser, "const svc = require('./svc');\n")
+ imp = next(i for i in result.imports if i.module_path == "./svc")
+ assert imp.is_reexport is False
+ assert any(b.is_module_alias for b in imp.bindings)
+
+
+def test_typescript_cjs_reexport(parser: ASTParser) -> None:
+ result = _parse(parser, "module.exports = require('./impl');\n", language="typescript")
+ imp = next(i for i in result.imports if i.module_path == "./impl")
+ assert imp.is_reexport is True
+
+
+def test_member_pick_require_is_extracted(parser: ASTParser) -> None:
+ # express lib/*.js shape: var x = require('./utils').normalizeType —
+ # the member_expression wraps the call, so the bare-call declarator
+ # pattern never matched it.
+ result = _parse(parser, "var normalizeType = require('./utils').normalizeType;\n")
+ assert any(i.module_path == "./utils" for i in result.imports)
diff --git a/tests/unit/ingestion/test_cpp_header_pairs.py b/tests/unit/ingestion/test_cpp_header_pairs.py
new file mode 100644
index 000000000..72947c883
--- /dev/null
+++ b/tests/unit/ingestion/test_cpp_header_pairs.py
@@ -0,0 +1,49 @@
+"""Unit tests for C/C++ header ↔ implementation pairing edges."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+
+def _build(repo: Path):
+ traverser = FileTraverser(repo)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=repo)
+ for fi in traverser.traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ return builder.build()
+
+class TestCppHeaderSourcePairing:
+ def test_header_source_pair_links_both_directions(self, tmp_path: Path) -> None:
+ (tmp_path / "util.h").write_text("int helper(void);\n")
+ (tmp_path / "util.c").write_text('#include "util.h"\nint helper(void) { return 1; }\n')
+ (tmp_path / "main.c").write_text('#include "util.h"\nint main(void) { return helper(); }\n')
+ graph = _build(tmp_path)
+ # main.c -> util.h (include), util.c -> util.h (include),
+ # util.h -> util.c (pairing) — the implementation is reachable
+ # from any consumer of the header.
+ assert graph.has_edge("main.c", "util.h")
+ pair = graph.get_edge_data("util.h", "util.c")
+ assert pair is not None
+ assert pair.get("hint_source") == "header_source_pair"
+ assert nx.has_path(graph, "main.c", "util.c")
+
+ def test_different_stems_not_paired(self, tmp_path: Path) -> None:
+ (tmp_path / "util.h").write_text("int helper(void);\n")
+ (tmp_path / "other.c").write_text("int x(void) { return 0; }\n")
+ graph = _build(tmp_path)
+ assert not graph.has_edge("util.h", "other.c")
+
+ def test_different_dirs_not_paired(self, tmp_path: Path) -> None:
+ (tmp_path / "include").mkdir()
+ (tmp_path / "src").mkdir()
+ (tmp_path / "include" / "util.h").write_text("int helper(void);\n")
+ (tmp_path / "src" / "util.c").write_text("int helper(void) { return 1; }\n")
+ graph = _build(tmp_path)
+ # Conservative: same-dir only (recorded cut — include/ vs src/
+ # layouts pair through the target fan-out instead).
+ assert not graph.has_edge("include/util.h", "src/util.c")
diff --git a/tests/unit/ingestion/test_cpp_workspace.py b/tests/unit/ingestion/test_cpp_workspace.py
index 868847fec..7a3e37874 100644
--- a/tests/unit/ingestion/test_cpp_workspace.py
+++ b/tests/unit/ingestion/test_cpp_workspace.py
@@ -149,3 +149,43 @@ def test_siblings_in_targets(tmp_path):
index = build_cpp_workspace_index(ctx)
siblings = set(index.siblings_in_targets("a.cc"))
assert siblings == {"b.cc", "c.cc"}
+
+
+def test_header_only_target_fans_out_to_other_headers(tmp_path):
+ # fmt-like header-only library: public headers, zero sources. One
+ # included header must pull the target's other headers along,
+ # otherwise the rest of the library is orphaned.
+ _write(tmp_path, "CMakeLists.txt", """
+ add_library(fmtish INTERFACE)
+ target_sources(fmtish INTERFACE include/fmtish/core.h include/fmtish/format.h include/fmtish/ranges.h)
+ target_include_directories(fmtish INTERFACE include)
+ """)
+ _write(tmp_path, "include/fmtish/core.h", "// core\n")
+ _write(tmp_path, "include/fmtish/format.h", "// format\n")
+ _write(tmp_path, "include/fmtish/ranges.h", "// ranges\n")
+ _write(tmp_path, "app/main.cc", '#include "fmtish/core.h"\n')
+ paths = [
+ "include/fmtish/core.h", "include/fmtish/format.h",
+ "include/fmtish/ranges.h", "app/main.cc", "CMakeLists.txt",
+ ]
+ ctx = _make_ctx(tmp_path, paths)
+ targets = resolve_cpp_import_all("fmtish/core.h", "app/main.cc", ctx)
+ assert targets[0] == "include/fmtish/core.h"
+ assert "include/fmtish/format.h" in targets
+ assert "include/fmtish/ranges.h" in targets
+
+
+def test_source_target_fanout_unchanged_by_header_pool(tmp_path):
+ # A target WITH sources keeps the TU fan-out (no header pool mixing).
+ _write(tmp_path, "CMakeLists.txt", """
+ add_library(coffee STATIC src/brew.cc src/grind.cc)
+ target_sources(coffee PUBLIC include/coffee/brew.h)
+ target_include_directories(coffee PUBLIC include)
+ """)
+ for rel in ("include/coffee/brew.h", "src/brew.cc", "src/grind.cc"):
+ _write(tmp_path, rel, "// x\n")
+ paths = ["include/coffee/brew.h", "src/brew.cc", "src/grind.cc", "CMakeLists.txt"]
+ ctx = _make_ctx(tmp_path, paths)
+ targets = resolve_cpp_import_all("coffee/brew.h", "src/brew.cc", ctx)
+ assert targets[0] == "include/coffee/brew.h"
+ assert "src/grind.cc" in targets
diff --git a/tests/unit/ingestion/test_csharp_partials.py b/tests/unit/ingestion/test_csharp_partials.py
new file mode 100644
index 000000000..b44ff5ed8
--- /dev/null
+++ b/tests/unit/ingestion/test_csharp_partials.py
@@ -0,0 +1,130 @@
+"""Unit tests for C# partial-class linking and nested-type resolution."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+from repowise.core.ingestion.resolvers.dotnet.namespace_map import (
+ build_namespace_map,
+ scan_type_declarations,
+)
+
+
+def _build(repo: Path):
+ traverser = FileTraverser(repo)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=repo)
+ for fi in traverser.traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ return builder.build()
+
+
+class TestScanTypeDeclarations:
+ def test_partial_flag_and_namespace(self) -> None:
+ decls = scan_type_declarations(
+ "namespace Acme.Models;\npublic partial class Order {\n}\nclass Plain {}\n"
+ )
+ by_name = {d.name: d for d in decls}
+ assert by_name["Order"].is_partial is True
+ assert by_name["Order"].fqn == "Acme.Models.Order"
+ assert by_name["Plain"].is_partial is False
+
+ def test_nested_type_one_level_qualified(self) -> None:
+ decls = scan_type_declarations(
+ "namespace A;\npublic class Outer {\n public class Inner {}\n}\n"
+ )
+ by_name = {d.name: d for d in decls}
+ assert by_name["Inner"].qualified == "Outer.Inner"
+
+ def test_deeper_nesting_collapses_to_immediate_parent(self) -> None:
+ # Recorded cut: only one level — Deep qualifies under Inner, not
+ # Outer.Inner.Deep.
+ decls = scan_type_declarations(
+ "class Outer {\n class Inner {\n class Deep {}\n }\n}\n"
+ )
+ by_name = {d.name: d for d in decls}
+ assert by_name["Deep"].qualified == "Inner.Deep"
+
+ def test_sibling_types_do_not_nest(self) -> None:
+ decls = scan_type_declarations("class A {}\nclass B {}\n")
+ by_name = {d.name: d for d in decls}
+ assert by_name["B"].qualified == "B"
+
+ def test_block_namespace_nesting(self) -> None:
+ decls = scan_type_declarations(
+ "namespace A {\n class Outer {\n class Inner {}\n }\n}\n"
+ )
+ by_name = {d.name: d for d in decls}
+ assert by_name["Inner"].qualified == "Outer.Inner"
+ assert by_name["Inner"].fqn == "A.Outer.Inner"
+
+
+class TestNamespaceMapNestedKeys:
+ def test_type_map_carries_qualified_key(self, tmp_path: Path) -> None:
+ f = tmp_path / "outer.cs"
+ f.write_text("namespace A;\nclass Outer {\n class Inner {}\n}\n")
+ _ns, type_map, _partials = build_namespace_map([f])
+ assert f in type_map["Inner"]
+ assert f in type_map["Outer.Inner"]
+
+ def test_partial_map_keyed_by_fqn(self, tmp_path: Path) -> None:
+ a = tmp_path / "a.cs"
+ b = tmp_path / "b.cs"
+ a.write_text("namespace A;\npublic partial class Order {}\n")
+ b.write_text("namespace A;\npublic partial class Order {}\n")
+ _ns, _types, partials = build_namespace_map([a, b])
+ assert sorted(partials["A.Order"]) == sorted([a, b])
+
+ def test_same_name_different_namespace_not_merged(self, tmp_path: Path) -> None:
+ a = tmp_path / "a.cs"
+ b = tmp_path / "b.cs"
+ a.write_text("namespace A;\npublic partial class Order {}\n")
+ b.write_text("namespace B;\npublic partial class Order {}\n")
+ _ns, _types, partials = build_namespace_map([a, b])
+ assert len(partials["A.Order"]) == 1
+ assert len(partials["B.Order"]) == 1
+
+
+class TestPartialClassEdges:
+ def test_partial_fragments_linked_bidirectionally(self, tmp_path: Path) -> None:
+ (tmp_path / "Order.cs").write_text(
+ "namespace Acme.Models;\npublic partial class Order {\n"
+ " public string Id { get; set; }\n}\n"
+ )
+ (tmp_path / "Order.Totals.cs").write_text(
+ "namespace Acme.Models;\npublic partial class Order {\n"
+ " public decimal Total { get; set; }\n}\n"
+ )
+ graph = _build(tmp_path)
+ edge_ab = graph.get_edge_data("Order.cs", "Order.Totals.cs")
+ edge_ba = graph.get_edge_data("Order.Totals.cs", "Order.cs")
+ assert edge_ab and edge_ab["edge_type"] == "imports"
+ assert edge_ab["hint_source"] == "partial_class"
+ assert edge_ba and edge_ba["hint_source"] == "partial_class"
+
+ def test_non_partial_same_names_not_linked(self, tmp_path: Path) -> None:
+ (tmp_path / "a.cs").write_text("namespace A;\npublic class Order {}\n")
+ (tmp_path / "b.cs").write_text("namespace B;\npublic class Order {}\n")
+ graph = _build(tmp_path)
+ assert not graph.has_edge("a.cs", "b.cs")
+ assert not graph.has_edge("b.cs", "a.cs")
+
+
+class TestNestedTypeResolution:
+ def test_outer_inner_type_ref_resolves(self, tmp_path: Path) -> None:
+ # using A.Models; ... Outer.Inner x; — the qualified reference must
+ # land a type_use (or stronger) edge on the declaring file.
+ (tmp_path / "Outer.cs").write_text(
+ "namespace A.Models;\npublic class Outer {\n"
+ " public class Inner {\n public int Qty { get; set; }\n }\n}\n"
+ )
+ (tmp_path / "Report.cs").write_text(
+ "namespace A.App;\nusing A.Models;\npublic class Report {\n"
+ " public Outer.Inner First { get; set; }\n}\n"
+ )
+ graph = _build(tmp_path)
+ edge = graph.get_edge_data("Report.cs", "Outer.cs")
+ assert edge is not None
+ assert edge["edge_type"] in ("imports", "type_use")
+
diff --git a/tests/unit/ingestion/test_csharp_resolver.py b/tests/unit/ingestion/test_csharp_resolver.py
index c9b43b7ba..67fae0bf6 100644
--- a/tests/unit/ingestion/test_csharp_resolver.py
+++ b/tests/unit/ingestion/test_csharp_resolver.py
@@ -165,7 +165,9 @@ class TestNamespaceMap:
def test_build_namespace_map(self, tmp_path: Path) -> None:
(tmp_path / "user.cs").write_text("namespace Domain.Users; class User {}")
(tmp_path / "order.cs").write_text("namespace Domain.Orders; class Order {}")
- ns_map, type_map = build_namespace_map([tmp_path / "user.cs", tmp_path / "order.cs"])
+ ns_map, type_map, _partials = build_namespace_map(
+ [tmp_path / "user.cs", tmp_path / "order.cs"]
+ )
assert "Domain.Users" in ns_map
assert "Domain.Orders" in ns_map
# The type map surfaces the unqualified type name for each declared type.
diff --git a/tests/unit/ingestion/test_csharp_same_namespace.py b/tests/unit/ingestion/test_csharp_same_namespace.py
new file mode 100644
index 000000000..e45f96f08
--- /dev/null
+++ b/tests/unit/ingestion/test_csharp_same_namespace.py
@@ -0,0 +1,169 @@
+"""Unit tests for C# same-namespace + global-using implicit reference edges."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from typing import ClassVar
+
+import networkx as nx
+
+from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+from repowise.core.ingestion.languages.csharp_same_namespace import (
+ resolve_csharp_same_namespace_refs,
+)
+
+
+def _graph_for(texts: dict[str, str]) -> nx.DiGraph:
+ g = nx.DiGraph()
+ for p in texts:
+ g.add_node(p, node_type="file")
+ return g
+
+
+class TestSameNamespace:
+ def test_sibling_type_reference_produces_edge(self) -> None:
+ texts = {
+ "src/Core/Order.cs": "namespace Acme.Core;\npublic class Order {}\n",
+ "src/Core/OrderService.cs": (
+ "namespace Acme.Core;\npublic class OrderService {\n"
+ " private Order _pending;\n}\n"
+ ),
+ }
+ g = _graph_for(texts)
+ added = resolve_csharp_same_namespace_refs(g, None, texts, None)
+ assert added == 1
+ edge = g["src/Core/OrderService.cs"]["src/Core/Order.cs"]
+ assert edge["edge_type"] == "imports"
+ assert edge["hint_source"] == "same_namespace"
+ assert edge["imported_names"] == ["Order"]
+
+ def test_zero_using_enum_file_gets_referenced(self) -> None:
+ # Polly regression: declaration-only files (enums) have no usings
+ # and same-namespace consumers reference them with none either.
+ texts = {
+ "src/DelayBackoffType.cs": (
+ "namespace Polly;\npublic enum DelayBackoffType { Constant }\n"
+ ),
+ "src/RetryOptions.cs": (
+ "namespace Polly;\npublic class RetryOptions {\n"
+ " public DelayBackoffType BackoffType { get; set; }\n}\n"
+ ),
+ }
+ g = _graph_for(texts)
+ added = resolve_csharp_same_namespace_refs(g, None, texts, None)
+ assert added == 1
+ assert g.has_edge("src/RetryOptions.cs", "src/DelayBackoffType.cs")
+
+ def test_ambiguous_type_produces_no_edge(self) -> None:
+ texts = {
+ "src/A/Thing.cs": "namespace Acme;\npublic partial class Thing {}\n",
+ "src/B/Thing.cs": "namespace Acme;\npublic partial class Thing {}\n",
+ "src/User.cs": "namespace Acme;\npublic class User { Thing t; }\n",
+ }
+ g = _graph_for(texts)
+ added = resolve_csharp_same_namespace_refs(g, None, texts, None)
+ assert added == 0
+
+ def test_bcl_name_produces_no_edge(self) -> None:
+ texts = {
+ "src/Task.cs": "namespace Acme;\npublic class Task {}\n",
+ "src/Runner.cs": "namespace Acme;\npublic class Runner { Task T; }\n",
+ }
+ g = _graph_for(texts)
+ added = resolve_csharp_same_namespace_refs(g, None, texts, None)
+ assert added == 0
+
+ def test_alias_using_shadows(self) -> None:
+ texts = {
+ "src/Helper.cs": "namespace Acme;\npublic class Helper {}\n",
+ "src/Consumer.cs": (
+ "using Helper = Other.Place.Helper;\n"
+ "namespace Acme;\npublic class Consumer { Helper h; }\n"
+ ),
+ }
+ g = _graph_for(texts)
+ added = resolve_csharp_same_namespace_refs(g, None, texts, None)
+ assert added == 0
+
+ def test_cross_namespace_name_produces_no_edge(self) -> None:
+ texts = {
+ "src/Core/Widget.cs": "namespace Acme.Core;\npublic class Widget {}\n",
+ "src/Web/Page.cs": "namespace Acme.Web;\npublic class Page { Widget w; }\n",
+ }
+ g = _graph_for(texts)
+ added = resolve_csharp_same_namespace_refs(g, None, texts, None)
+ assert added == 0
+
+ def test_existing_edge_wins(self) -> None:
+ texts = {
+ "src/Order.cs": "namespace Acme;\npublic class Order {}\n",
+ "src/Svc.cs": "namespace Acme;\npublic class Svc { Order o; }\n",
+ }
+ g = _graph_for(texts)
+ g.add_edge("src/Svc.cs", "src/Order.cs", edge_type="imports", confidence=1.0)
+ added = resolve_csharp_same_namespace_refs(g, None, texts, None)
+ assert added == 0
+ assert "hint_source" not in g["src/Svc.cs"]["src/Order.cs"]
+
+
+class TestGlobalUsings:
+ def _repo(self, tmp_path: Path, files: dict[str, str]) -> Path:
+ for rel, text in files.items():
+ full = tmp_path / rel
+ full.parent.mkdir(parents=True, exist_ok=True)
+ full.write_text(text)
+ return tmp_path
+
+ def test_csproj_using_items_link_zero_using_test_file(self, tmp_path: Path) -> None:
+ # Polly.Specs regression: the test project declares
+ # <Using Include="Polly.Specs.Helpers"/> so spec files carry no
+ # per-file usings at all — they must still link to the helpers.
+ repo = self._repo(
+ tmp_path,
+ {
+ "test/Specs/Specs.csproj": (
+ "<Project Sdk=\"Microsoft.NET.Sdk\">\n <ItemGroup>\n"
+ " <Using Include=\"Acme.Specs.Helpers\" />\n"
+ " </ItemGroup>\n</Project>\n"
+ ),
+ "test/Specs/Helpers/Doer.cs": (
+ "namespace Acme.Specs.Helpers;\npublic class Doer {}\n"
+ ),
+ "test/Specs/RetrySpecs.cs": (
+ "namespace Acme.Specs;\npublic class RetrySpecs {\n"
+ " public void Runs() { var d = new Doer(); }\n}\n"
+ ),
+ },
+ )
+ traverser = FileTraverser(repo)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=repo)
+ for fi in traverser.traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ g = builder.build()
+ edge = g.get_edge_data("test/Specs/RetrySpecs.cs", "test/Specs/Helpers/Doer.cs")
+ assert edge is not None
+ assert edge.get("hint_source") == "global_using"
+
+ def test_explicit_using_namespace_shadows_global_tier(self, tmp_path: Path) -> None:
+ # A file that explicitly `using`s a local namespace resolves through
+ # the normal import path — the global tier must not double-guess.
+ texts = {
+ "src/Helpers/Doer.cs": "namespace Acme.Helpers;\npublic class Doer {}\n",
+ "src/Consumer.cs": (
+ "using Acme.Helpers;\n"
+ "namespace Acme;\npublic class Consumer { Doer d; }\n"
+ ),
+ }
+ g = _graph_for(texts)
+
+ class _FakeIndex:
+ file_to_project: ClassVar[dict[Path, Path]] = {
+ (tmp_path / "src/Consumer.cs").resolve(): Path("proj.csproj")
+ }
+
+ def globals_for_project(self, csproj):
+ return {"Acme.Helpers"}
+
+ added = resolve_csharp_same_namespace_refs(g, _FakeIndex(), texts, tmp_path)
+ assert added == 0
diff --git a/tests/unit/ingestion/test_go_workspace.py b/tests/unit/ingestion/test_go_workspace.py
index b3c20fcd3..e6d40bbef 100644
--- a/tests/unit/ingestion/test_go_workspace.py
+++ b/tests/unit/ingestion/test_go_workspace.py
@@ -124,3 +124,51 @@ class TestBuildIndex:
first = get_or_build_go_index(ctx)
second = get_or_build_go_index(ctx)
assert first is second
+
+
+class TestPackageMainEntries:
+ def test_main_files_recorded_regardless_of_filename(self, tmp_path: Path) -> None:
+ # Go's entry convention is semantic (package main + func main), not
+ # filename-based — cmd/task/task.go is as much a binary as
+ # cmd/release/main.go.
+ _write(tmp_path, "cmd/task/task.go", "package main\n\nfunc main() {}\n")
+ _write(tmp_path, "cmd/release/main.go", "package main\n\nfunc main() {}\n")
+ # package main helper WITHOUT func main: never an entry.
+ _write(tmp_path, "cmd/task/helpers.go", "package main\n\nfunc run() {}\n")
+ # Library package with a func main-looking method: never an entry.
+ _write(tmp_path, "lib/lib.go", "package lib\n\nfunc main() {}\n")
+ paths = ["cmd/task/task.go", "cmd/release/main.go", "cmd/task/helpers.go", "lib/lib.go"]
+ ctx = _ctx(tmp_path, paths, go_modules=(("", "m"),))
+ index = build_go_package_index(ctx)
+ assert index.packages["cmd/task"].main_files == ("cmd/task/task.go",)
+ assert index.packages["cmd/release"].main_files == ("cmd/release/main.go",)
+ assert index.packages["lib"].main_files == ()
+
+ def test_warmup_stamps_entry_flag_on_main_files(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion.graph_warmups import _warmup_go
+
+ _write(tmp_path, "cmd/task/task.go", "package main\n\nfunc main() {}\n")
+ _write(tmp_path, "lib/lib.go", "package lib\n")
+ paths = ["cmd/task/task.go", "lib/lib.go"]
+ ctx = _ctx(tmp_path, paths, go_modules=(("", "m"),))
+ for p in paths:
+ ctx.graph.add_node(p, node_type="file")
+ _warmup_go(ctx)
+ assert ctx.graph.nodes["cmd/task/task.go"].get("is_entry_point") is True
+ assert "is_entry_point" not in ctx.graph.nodes["lib/lib.go"]
+
+
+def test_warmup_stamps_parsed_file_info(tmp_path: Path) -> None:
+ # The exported KG's entry tags read FileInfo.is_entry_point, not the
+ # graph attr — the warmup must stamp both surfaces.
+ from types import SimpleNamespace
+
+ from repowise.core.ingestion.graph_warmups import _warmup_go
+
+ _write(tmp_path, "cmd/task/task.go", "package main\n\nfunc main() {}\n")
+ ctx = _ctx(tmp_path, ["cmd/task/task.go"], go_modules=(("", "m"),))
+ fi = SimpleNamespace(is_entry_point=False)
+ ctx.parsed_files = {"cmd/task/task.go": SimpleNamespace(file_info=fi)}
+ ctx.graph.add_node("cmd/task/task.go", node_type="file")
+ _warmup_go(ctx)
+ assert fi.is_entry_point is True
diff --git a/tests/unit/ingestion/test_java_extractors.py b/tests/unit/ingestion/test_java_extractors.py
index e9998dc5f..7ec4402a8 100644
--- a/tests/unit/ingestion/test_java_extractors.py
+++ b/tests/unit/ingestion/test_java_extractors.py
@@ -68,3 +68,26 @@ class TestJavaModuleDocstring:
result = parser.parse_file(_file(), src)
assert result.docstring is not None
assert "Module-level summary" in result.docstring
+
+
+class TestJavaWildcardImports:
+ def test_wildcard_import_keeps_star(self, parser: ASTParser) -> None:
+ # The grammar query captures only the scoped identifier — the `*`
+ # is a sibling node. Extraction must restore it or the resolver's
+ # package fan-out branch can never fire.
+ src = b"package x;\nimport com.example.util.*;\npublic class App {}\n"
+ result = parser.parse_file(_file(), src)
+ modules = [imp.module_path for imp in result.imports]
+ assert "com.example.util.*" in modules
+
+ def test_static_wildcard_import_keeps_star(self, parser: ASTParser) -> None:
+ src = b"package x;\nimport static com.example.Assertions.*;\npublic class App {}\n"
+ result = parser.parse_file(_file(), src)
+ modules = [imp.module_path for imp in result.imports]
+ assert "com.example.Assertions.*" in modules
+
+ def test_plain_import_unchanged(self, parser: ASTParser) -> None:
+ src = b"package x;\nimport com.example.Foo;\npublic class App {}\n"
+ result = parser.parse_file(_file(), src)
+ modules = [imp.module_path for imp in result.imports]
+ assert modules == ["com.example.Foo"]
diff --git a/tests/unit/ingestion/test_java_resolver.py b/tests/unit/ingestion/test_java_resolver.py
index ac5bfc267..09467e310 100644
--- a/tests/unit/ingestion/test_java_resolver.py
+++ b/tests/unit/ingestion/test_java_resolver.py
@@ -99,3 +99,47 @@ class TestJavaImportResolution:
ctx = _ctx(tmp_path, [a, b])
targets = resolve_java_import_all("com.foo.A", "Main.java", ctx)
assert targets == (a,)
+
+
+class TestJavaStdlibFiltering:
+ def test_javax_dropped(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, [])
+ assert resolve_java_import_all("javax.annotation.Nullable", "Main.java", ctx) == ()
+
+ def test_jdk_dropped(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, [])
+ assert resolve_java_import_all("jdk.incubator.vector.VectorSpecies", "Main.java", ctx) == ()
+
+ def test_java_util_dropped(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, [])
+ assert resolve_java_import_all("java.util.List", "Main.java", ctx) == ()
+
+ def test_jakarta_is_external_not_stdlib(self, tmp_path: Path) -> None:
+ # jakarta.* is a real dependency namespace — external node wanted.
+ ctx = _ctx(tmp_path, [])
+ targets = resolve_java_import_all("jakarta.servlet.Filter", "Main.java", ctx)
+ assert targets == ("external:jakarta.servlet.Filter",)
+
+ def test_jakarta_never_stem_matches_local_file(self, tmp_path: Path) -> None:
+ # A repo-local Filter.java must not capture jakarta.servlet.Filter.
+ local = _make_java(tmp_path, "src/com/app/Filter.java", "com.app", "Filter")
+ ctx = _ctx(tmp_path, [local])
+ targets = resolve_java_import_all("jakarta.servlet.Filter", "Main.java", ctx)
+ assert targets == ("external:jakarta.servlet.Filter",)
+
+ def test_jakarta_exact_local_match_wins(self, tmp_path: Path) -> None:
+ # The repo may BE the jakarta library — exact FQN match resolves locally.
+ local = _make_java(
+ tmp_path, "api/src/jakarta/servlet/Filter.java", "jakarta.servlet", "Filter"
+ )
+ ctx = _ctx(tmp_path, [local])
+ targets = resolve_java_import_all("jakarta.servlet.Filter", "Main.java", ctx)
+ assert targets == (local,)
+
+ def test_prefix_match_is_segment_aware(self, tmp_path: Path) -> None:
+ # A local package literally named javautil must not be swallowed
+ # by the java. prefix filter.
+ local = _make_java(tmp_path, "src/javautil/Helper.java", "javautil", "Helper")
+ ctx = _ctx(tmp_path, [local])
+ result = resolve_java_import("javautil.Helper", "Main.java", ctx)
+ assert result == local
diff --git a/tests/unit/ingestion/test_jvm_same_package.py b/tests/unit/ingestion/test_jvm_same_package.py
new file mode 100644
index 000000000..1ae0a82a1
--- /dev/null
+++ b/tests/unit/ingestion/test_jvm_same_package.py
@@ -0,0 +1,238 @@
+"""Unit tests for JVM same-package implicit reference edges."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.languages.jvm_same_package import (
+ resolve_jvm_same_package_refs,
+)
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.jvm_workspace import build_jvm_workspace_index
+
+
+def _write(repo: Path, rel_path: str, text: str) -> str:
+ full = repo / rel_path
+ full.parent.mkdir(parents=True, exist_ok=True)
+ full.write_text(text)
+ return rel_path
+
+
+def _setup(repo: Path, files: dict[str, str]):
+ """Write *files*, build index + graph with file nodes, return (graph, index, texts)."""
+ paths = [_write(repo, rel, text) for rel, text in files.items()]
+ ctx = ResolverContext(path_set=set(paths), stem_map={}, graph=nx.DiGraph(), repo_path=repo)
+ index = build_jvm_workspace_index(ctx)
+ graph = nx.DiGraph()
+ for p in paths:
+ graph.add_node(p, node_type="file")
+ texts = {rel: (repo / rel).read_text() for rel in paths}
+ return graph, index, texts
+
+
+class TestJavaSamePackage:
+ def test_sibling_type_reference_produces_edge(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/shop/Order.java": "package com.shop;\npublic class Order {}\n",
+ "src/com/shop/OrderService.java": (
+ "package com.shop;\npublic class OrderService {\n"
+ " Order pending;\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 1
+ edge = graph["src/com/shop/OrderService.java"]["src/com/shop/Order.java"]
+ assert edge["edge_type"] == "imports"
+ assert edge["hint_source"] == "same_package"
+ assert edge["imported_names"] == ["Order"]
+
+ def test_self_reference_produces_no_edge(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/shop/Order.java": (
+ "package com.shop;\npublic class Order {\n"
+ " Order next;\n}\n"
+ ),
+ "src/com/shop/Other.java": "package com.shop;\npublic class Other {}\n",
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 0
+
+ def test_stdlib_name_produces_no_edge(self, tmp_path: Path) -> None:
+ # A sibling declaring a java.lang name must not attract edges:
+ # bare ``String`` references are overwhelmingly stdlib.
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/shop/String.java": "package com.shop;\npublic class String {}\n",
+ "src/com/shop/User.java": (
+ "package com.shop;\npublic class User {\n"
+ " String name;\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 0
+
+ def test_ambiguous_type_produces_no_edge(self, tmp_path: Path) -> None:
+ # Two package files declare ``Config`` — edge to neither.
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/shop/A.java": "package com.shop;\npublic class A {}\nclass Config {}\n",
+ "src/com/shop/B.java": "package com.shop;\npublic class B {}\nclass Config {}\n",
+ "src/com/shop/C.java": (
+ "package com.shop;\npublic class C {\n Config cfg;\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 0
+
+ def test_cross_package_name_produces_no_edge(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/shop/Order.java": "package com.shop;\npublic class Order {}\n",
+ "src/com/billing/Invoice.java": (
+ "package com.billing;\npublic class Invoice {\n Order o;\n}\n"
+ ),
+ "src/com/billing/Other.java": "package com.billing;\npublic class Other {}\n",
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 0
+
+ def test_explicit_import_shadows_same_package(self, tmp_path: Path) -> None:
+ # A imports com.other.Helper explicitly — JVM semantics say the
+ # import wins over the same-package Helper, so no sibling edge.
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/shop/Helper.java": "package com.shop;\npublic class Helper {}\n",
+ "src/com/shop/User.java": (
+ "package com.shop;\nimport com.other.Helper;\n"
+ "public class User {\n Helper h;\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 0
+
+ def test_existing_import_edge_wins(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/shop/Order.java": "package com.shop;\npublic class Order {}\n",
+ "src/com/shop/OrderService.java": (
+ "package com.shop;\npublic class OrderService {\n Order o;\n}\n"
+ ),
+ })
+ graph.add_edge(
+ "src/com/shop/OrderService.java",
+ "src/com/shop/Order.java",
+ edge_type="imports",
+ imported_names=["Order"],
+ )
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 0
+ edge = graph["src/com/shop/OrderService.java"]["src/com/shop/Order.java"]
+ assert "hint_source" not in edge
+
+ def test_multiple_types_aggregate_on_one_edge(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/shop/Models.java": (
+ "package com.shop;\npublic class Order {}\nclass Invoice {}\n"
+ ),
+ "src/com/shop/Service.java": (
+ "package com.shop;\npublic class Service {\n"
+ " Order o;\n Invoice i;\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 1
+ edge = graph["src/com/shop/Service.java"]["src/com/shop/Models.java"]
+ assert sorted(edge["imported_names"]) == ["Invoice", "Order"]
+
+
+class TestKotlinSamePackage:
+ def test_kotlin_class_and_object_references(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/app/Config.kt": "package com.app\n\nobject Config\n",
+ "src/com/app/Model.kt": "package com.app\n\nclass Model\n",
+ "src/com/app/Service.kt": (
+ "package com.app\n\nclass Service {\n"
+ " val cfg = Config\n val m = Model()\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 2
+ assert graph.has_edge("src/com/app/Service.kt", "src/com/app/Config.kt")
+ assert graph.has_edge("src/com/app/Service.kt", "src/com/app/Model.kt")
+
+ def test_kotlin_enum_class_resolves(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/app/Status.kt": "package com.app\n\nenum class Status { OPEN, DONE }\n",
+ "src/com/app/Ticket.kt": (
+ "package com.app\n\nclass Ticket {\n var status: Status = Status.OPEN\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 1
+ assert graph.has_edge("src/com/app/Ticket.kt", "src/com/app/Status.kt")
+
+ def test_kotlin_stdlib_names_skipped(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/app/Pair.kt": "package com.app\n\nclass Pair\n",
+ "src/com/app/Use.kt": (
+ "package com.app\n\nclass Use {\n val p: Pair<Int, Int>? = null\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 0
+
+ def test_kotlin_top_level_function_not_linked(self, tmp_path: Path) -> None:
+ # Types only: lowercase top-level callables are out of scope.
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/app/Helpers.kt": "package com.app\n\nfun formatName(n: String) = n\n",
+ "src/com/app/Service.kt": (
+ "package com.app\n\nclass Service {\n"
+ " fun run() = formatName(\"x\")\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 0
+
+ def test_cross_language_java_to_kotlin_sibling(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/com/app/Repo.kt": "package com.app\n\nclass Repo\n",
+ "src/com/app/Service.java": (
+ "package com.app;\npublic class Service {\n Repo repo;\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 1
+ assert graph.has_edge("src/com/app/Service.java", "src/com/app/Repo.kt")
+
+
+class TestScalaSamePackage:
+ def test_scala_sibling_trait_reference(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/main/scala/com/app/Api.scala": "package com.app\n\ntrait Api\n",
+ "src/main/scala/com/app/Service.scala": (
+ "package com.app\n\nclass Service extends Api\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 1
+ assert graph.has_edge(
+ "src/main/scala/com/app/Service.scala", "src/main/scala/com/app/Api.scala"
+ )
+
+ def test_scala_predef_names_skipped(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/main/scala/com/app/Option.scala": "package com.app\n\nclass Option\n",
+ "src/main/scala/com/app/Use.scala": (
+ "package com.app\n\nclass Use {\n val o: Option[Int] = None\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 0
+
+ def test_scala_brace_import_shadows_same_package(self, tmp_path: Path) -> None:
+ graph, index, texts = _setup(tmp_path, {
+ "src/main/scala/com/app/Helper.scala": "package com.app\n\nclass Helper\n",
+ "src/main/scala/com/app/Use.scala": (
+ "package com.app\n\nimport com.other.{Helper, Misc}\n\n"
+ "class Use {\n val h = new Helper()\n}\n"
+ ),
+ })
+ added = resolve_jvm_same_package_refs(graph, index, texts)
+ assert added == 0
diff --git a/tests/unit/ingestion/test_jvm_workspace.py b/tests/unit/ingestion/test_jvm_workspace.py
index 702d9178d..4ddacf406 100644
--- a/tests/unit/ingestion/test_jvm_workspace.py
+++ b/tests/unit/ingestion/test_jvm_workspace.py
@@ -157,3 +157,51 @@ class TestJvmWorkspaceIndex:
fqns = index.autoconfig_imports[key]
assert "com.example.MyAutoConfig" in fqns
assert "com.example.OtherConfig" in fqns
+
+
+class TestMemberFqnResolution:
+ def test_kotlin_companion_member_import_resolves_to_declaring_type(
+ self, tmp_path: Path
+ ) -> None:
+ # okio regression: ``import okio.ByteString.Companion.encodeUtf8``
+ # names a companion member — strip trailing segments until the
+ # prefix is a local type.
+ b = _make_kotlin(tmp_path, "src/main/java/okio/ByteString.kt", "okio", "ByteString")
+ ctx = _ctx(tmp_path, [b])
+ index = build_jvm_workspace_index(ctx)
+ assert index.files_for_member_fqn("okio.ByteString.Companion.encodeUtf8") == (b,)
+ assert index.files_for_member_fqn("okio.ByteString.Companion") == (b,)
+
+ def test_java_static_member_import_resolves(self, tmp_path: Path) -> None:
+ a = _make_java(tmp_path, "src/main/java/com/foo/Bar.java", "com.foo", "Bar")
+ ctx = _ctx(tmp_path, [a])
+ index = build_jvm_workspace_index(ctx)
+ assert index.files_for_member_fqn("com.foo.Bar.CONSTANT") == (a,)
+
+ def test_unknown_prefix_returns_empty(self, tmp_path: Path) -> None:
+ a = _make_java(tmp_path, "src/main/java/com/foo/Bar.java", "com.foo", "Bar")
+ ctx = _ctx(tmp_path, [a])
+ index = build_jvm_workspace_index(ctx)
+ assert index.files_for_member_fqn("org.junit.Assert.assertEquals") == ()
+
+ def test_kotlin_resolver_emits_member_import_edge(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion.resolvers.kotlin import resolve_kotlin_import_all
+
+ b = _make_kotlin(tmp_path, "src/main/java/okio/ByteString.kt", "okio", "ByteString")
+ u = _make_kotlin(tmp_path, "src/main/java/okio/User.kt", "okio", "User")
+ ctx = _ctx(tmp_path, [b, u])
+ targets = resolve_kotlin_import_all(
+ "okio.ByteString.Companion.encodeUtf8", u, ctx
+ )
+ assert targets == (b,)
+
+ def test_kotlin_member_wildcard_import_resolves(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion.resolvers.kotlin import resolve_kotlin_import_all
+
+ b = _make_kotlin(tmp_path, "src/main/java/okio/ByteString.kt", "okio", "ByteString")
+ u = _make_kotlin(tmp_path, "src/main/java/okio/User.kt", "okio", "User")
+ ctx = _ctx(tmp_path, [b, u])
+ # ``import okio.ByteString.Companion.*`` — the prefix is a type, not
+ # a package.
+ targets = resolve_kotlin_import_all("okio.ByteString.Companion.*", u, ctx)
+ assert targets == (b,)
diff --git a/tests/unit/ingestion/test_kotlin_extractors.py b/tests/unit/ingestion/test_kotlin_extractors.py
index 310c76a3d..f40e2d17d 100644
--- a/tests/unit/ingestion/test_kotlin_extractors.py
+++ b/tests/unit/ingestion/test_kotlin_extractors.py
@@ -90,3 +90,19 @@ class UserRepo : Repo
names = {s.name for s in result.symbols}
assert "Repo" in names
assert "UserRepo" in names
+
+
+class TestKotlinWildcardImports:
+ def test_wildcard_import_keeps_star(self, parser: ASTParser) -> None:
+ # The `*` is an anonymous sibling token of the qualified identifier
+ # in the Kotlin grammar; extraction must restore it for package fan-out.
+ src = b"package x\nimport com.example.util.*\nclass App\n"
+ result = parser.parse_file(_file(), src)
+ modules = [imp.module_path for imp in result.imports]
+ assert "com.example.util.*" in modules
+
+ def test_plain_import_unchanged(self, parser: ASTParser) -> None:
+ src = b"package x\nimport com.example.Foo\nclass App\n"
+ result = parser.parse_file(_file(), src)
+ modules = [imp.module_path for imp in result.imports]
+ assert modules == ["com.example.Foo"]
diff --git a/tests/unit/ingestion/test_kotlin_resolver.py b/tests/unit/ingestion/test_kotlin_resolver.py
index 0518e5e94..61382dd51 100644
--- a/tests/unit/ingestion/test_kotlin_resolver.py
+++ b/tests/unit/ingestion/test_kotlin_resolver.py
@@ -71,3 +71,38 @@ class TestKotlinIndex:
ctx = _ctx(tmp_path, ["src/main/kotlin/com/example/Util.kt"])
result = resolve_kotlin_import("com.example.Util", "main.kt", ctx)
assert result == "src/main/kotlin/com/example/Util.kt"
+
+
+class TestKotlinStdlibFiltering:
+ def test_kotlin_stdlib_dropped(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, [])
+ assert resolve_kotlin_import("kotlin.collections.List", "Main.kt", ctx) is None
+
+ def test_java_stdlib_dropped_for_kotlin(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, [])
+ assert resolve_kotlin_import("java.util.UUID", "Main.kt", ctx) is None
+ assert resolve_kotlin_import("javax.inject.Inject", "Main.kt", ctx) is None
+
+ def test_kotlinx_is_external_not_stdlib(self, tmp_path: Path) -> None:
+ # kotlinx.* is a library namespace, not stdlib — external node wanted.
+ ctx = _ctx(tmp_path, [])
+ result = resolve_kotlin_import("kotlinx.coroutines.launch", "Main.kt", ctx)
+ assert result == "external:kotlinx.coroutines.launch"
+
+ def test_kotlinx_never_stem_matches_local_file(self, tmp_path: Path) -> None:
+ # A repo-local Launch.kt must not capture kotlinx.coroutines.Launch.
+ repo_file = tmp_path / "src" / "Launch.kt"
+ repo_file.parent.mkdir(parents=True)
+ repo_file.write_text("package com.app\n\nclass Launch\n")
+ ctx = _ctx(tmp_path, ["src/Launch.kt"])
+ result = resolve_kotlin_import("kotlinx.coroutines.Launch", "Main.kt", ctx)
+ assert result == "external:kotlinx.coroutines.Launch"
+
+ def test_prefix_match_is_segment_aware(self, tmp_path: Path) -> None:
+ # kotlinutil.* is not kotlin.* — segment-aware prefix matching.
+ repo_file = tmp_path / "src" / "kotlinutil" / "Helper.kt"
+ repo_file.parent.mkdir(parents=True)
+ repo_file.write_text("package kotlinutil\n\nclass Helper\n")
+ ctx = _ctx(tmp_path, ["src/kotlinutil/Helper.kt"])
+ result = resolve_kotlin_import("kotlinutil.Helper", "Main.kt", ctx)
+ assert result == "src/kotlinutil/Helper.kt"
diff --git a/tests/unit/ingestion/test_language_capabilities.py b/tests/unit/ingestion/test_language_capabilities.py
new file mode 100644
index 000000000..5ca0342f0
--- /dev/null
+++ b/tests/unit/ingestion/test_language_capabilities.py
@@ -0,0 +1,251 @@
+"""Language capability registry — parity goldens and derivation pins.
+
+Per-language knowledge (test filename conventions, entry stems,
+import-support tiers, layer hints) lives on the ``LanguageSpec`` registry;
+``generation/layers.py``, ``generation/tour.py``, the traverser, and
+``analysis/kg_curation.py`` consume registry derivations.
+
+Two kinds of test live here:
+
+1. **Parity goldens** — the derived unions are pinned exactly. Any spec
+ edit that changes a union must update the golden *consciously*: these
+ sets steer test detection, entry scoring, and layer inference globally.
+
+2. **Derivation pins** — constants that used to be drifting hard-coded
+ literals (``_CODE_SUFFIXES``, ``_NON_CODE_LANGUAGES``) are now registry
+ derivations; the pins assert the derivation relationship and its key
+ membership so a regression back to drift cannot land silently.
+"""
+
+from __future__ import annotations
+
+from repowise.core.analysis.kg_curation import _CODE_SUFFIXES
+from repowise.core.generation import layers
+from repowise.core.generation.tour import _ENTRY_FILENAME_STEMS, _NON_CODE_LANGUAGES
+from repowise.core.ingestion.languages.registry import REGISTRY
+
+# ---------------------------------------------------------------------------
+# Parity goldens — derived unions == historical literals
+# ---------------------------------------------------------------------------
+
+
+class TestParityGoldens:
+ def test_entry_filename_stems_match_historical_set(self) -> None:
+ assert frozenset(
+ {
+ "index",
+ "main",
+ "app",
+ "server",
+ "mod",
+ "manage",
+ "wsgi",
+ "asgi",
+ "cli",
+ "__main__",
+ "bootstrap",
+ "entry",
+ }
+ ) == _ENTRY_FILENAME_STEMS
+
+ def test_test_stem_prefixes_match_historical_set(self) -> None:
+ assert set(layers._TEST_FILE_STEM_PREFIXES) == {"test_"}
+
+ def test_test_stem_suffixes_match_historical_set(self) -> None:
+ # "_unittest" (C/C++ GoogleTest convention) was a conscious
+ # addition to the historical {"_test", "_spec"} union.
+ assert set(layers._TEST_FILE_STEM_SUFFIXES) == {"_test", "_spec", "_unittest"}
+
+ def test_test_infixes_match_historical_set(self) -> None:
+ assert set(layers._TEST_FILE_INFIXES) == {".test.", ".spec."}
+
+ def test_test_fixture_stems_match_historical_set(self) -> None:
+ assert frozenset(
+ {"conftest", "spec_helper", "test_helper"}
+ ) == layers._TEST_FIXTURE_STEMS
+
+ def test_suite_anchor_stems(self) -> None:
+ # ruby (rspec/minitest helpers) and elixir (ExUnit's
+ # test_helper.exs) join python's conftest as closing-stop anchors.
+ assert REGISTRY.suite_anchor_stems() == frozenset(
+ {"conftest", "spec_helper", "test_helper"}
+ )
+
+ def test_descriptor_filenames(self) -> None:
+ # JPMS/javadoc descriptors: source files that declare, not implement.
+ assert REGISTRY.descriptor_filenames() == frozenset(
+ {"module-info.java", "package-info.java"}
+ )
+
+ def test_layer_dir_hints_by_language(self) -> None:
+ # Per-language hints (consulted after the generic table, only for
+ # the declaring language's files). csharp's project-suffix hints
+ # await verification against a live .NET repo.
+ assert REGISTRY.layer_dir_hints_by_language() == {
+ "go": (("internal", "Service"), ("pkg", "Service")),
+ "rust": (("-cli", "CLI"), ("src/bin", "CLI")),
+ "ruby": (("jobs", "Service"),),
+ "csharp": (
+ (".Api", "API"),
+ (".Domain", "Service"),
+ (".Infrastructure", "Data"),
+ ),
+ # Root-anchored ("/"): only a TOP-LEVEL include/ is a C/C++
+ # library's public API surface (libuv, fmt — validated live).
+ "c": (("/include", "API"),),
+ "cpp": (("/include", "API"),),
+ }
+
+ def test_camel_suffix_extension_map(self) -> None:
+ # Case-sensitive camel-boundary test suffixes per language.
+ camel = REGISTRY.camel_test_res_by_extension()
+ assert set(camel) == {
+ ".java", ".kt", ".kts", ".scala", ".cs", ".swift", ".php",
+ ".hs", ".lhs",
+ }
+ assert camel[".java"].pattern == r"(?<=[a-z0-9])(?:Tests|Test|IT)$"
+ assert camel[".scala"].pattern == r"(?<=[a-z0-9])(?:Suite|Spec|Test)$"
+
+ def test_test_dir_paths_union(self) -> None:
+ assert REGISTRY.test_dir_paths() == (
+ # "src/*Test" = Gradle source-set wildcard (src/commonTest,
+ # src/jvmTest, … — okio, validated live).
+ "src/*Test",
+ "src/integrationtest/java",
+ "src/it/java",
+ "src/it/scala",
+ "src/test/java",
+ "src/test/kotlin",
+ "src/test/scala",
+ )
+
+ def test_test_dir_suffixes_union(self) -> None:
+ # .Specs = BDD-style sibling test projects (Polly, validated live).
+ assert REGISTRY.test_dir_suffixes() == (".Specs", ".Tests")
+
+
+# ---------------------------------------------------------------------------
+# Import-support tiers
+# ---------------------------------------------------------------------------
+
+_FULL = {
+ "c",
+ "cpp",
+ "csharp",
+ "go",
+ "java",
+ "javascript",
+ "kotlin",
+ # php + swift promoted after live validation (Slim, Alamofire).
+ "php",
+ "python",
+ "ruby",
+ "rust",
+ "swift",
+ "typescript",
+}
+_PARTIAL = {
+ "luau",
+ "scala",
+ # Lightweight regex-tier resolvers (module-name index + import regexes).
+ "elixir",
+ "dart",
+ "clojure",
+ "haskell",
+ "erlang",
+ "fsharp",
+}
+
+
+class TestImportSupportTiers:
+ def test_every_spec_declares_a_valid_tier(self) -> None:
+ for spec in REGISTRY.all_specs():
+ assert spec.import_support in {"full", "partial", "none"}, spec.tag
+
+ def test_full_tier_membership(self) -> None:
+ support = REGISTRY.import_support_map()
+ assert {t for t, v in support.items() if v == "full"} == _FULL
+
+ def test_partial_tier_membership(self) -> None:
+ support = REGISTRY.import_support_map()
+ assert {t for t, v in support.items() if v == "partial"} == _PARTIAL
+
+ def test_unknown_language_reports_none(self) -> None:
+ assert REGISTRY.import_support_for("klingon") == "none"
+
+
+# ---------------------------------------------------------------------------
+# Derivation pins — constants that used to be drifting frozen literals are
+# now registry derivations; pin the relationship, not a literal.
+# ---------------------------------------------------------------------------
+
+# Non-tag defensive aliases inside tour._NON_CODE_LANGUAGES (none is a
+# registry tag; they guard against unnormalized language strings).
+_NON_CODE_ALIASES = {
+ "cmake", "css", "csv", "html", "ini", "md", "rst", "svg", "text", "txt",
+ "xml", "yml",
+} # fmt: skip
+
+# Entry-point conventions per language, including those recovered from the
+# deleted dead LanguageConfig table. "public/index.php" was intentionally
+# dropped: patterns match bare filenames, and "index.php" subsumes it.
+_ENTRY_PATTERNS_BY_LANGUAGE = {
+ "kotlin": ("Main.kt", "Application.kt"),
+ "ruby": ("main.rb", "app.rb", "config.ru"),
+ "swift": ("main.swift", "App.swift"),
+ "scala": ("Main.scala", "App.scala"),
+ "php": ("index.php", "artisan"),
+ "elixir": ("application.ex",),
+ "clojure": ("core.clj", "main.clj"),
+ "dart": ("main.dart",),
+ "haskell": ("Main.hs",),
+ "ocaml": ("main.ml",),
+ "erlang": ("*_app.erl",),
+ "fsharp": ("Program.fs",),
+ "crystal": ("main.cr",),
+ "nim": ("main.nim",),
+ "dlang": ("app.d",),
+ "elm": ("Main.elm",),
+ "zig": ("main.zig",),
+ "objectivec": ("main.m",),
+}
+
+
+class TestDriftManifests:
+ def test_code_suffixes_are_the_non_infra_code_derivation(self) -> None:
+ assert REGISTRY.non_infra_code_extensions() == _CODE_SUFFIXES
+ # The 32 once-missing extensions are protected now …
+ assert {".dart", ".hs", ".clj", ".erl", ".nim", ".m", ".luau"} <= _CODE_SUFFIXES
+ # … infra languages stay promotable, and the perl orphan is gone.
+ assert {".sh", ".bash", ".zsh", ".tf", ".hcl", ".pl"} & _CODE_SUFFIXES == set()
+
+ def test_non_code_languages_are_config_plus_infra_plus_aliases(self) -> None:
+ assert (
+ REGISTRY.config_languages()
+ | REGISTRY.infra_languages()
+ | frozenset(_NON_CODE_ALIASES)
+ ) == _NON_CODE_LANGUAGES
+ # The once-missing is_code=False tags and infra tags are covered …
+ assert {
+ "graphql", "openapi", "proto", "sql", "unknown", "xaml",
+ "shell", "terraform", "dockerfile", "makefile",
+ } <= _NON_CODE_LANGUAGES # fmt: skip
+ # … and real (Tier-3 included) code languages never are.
+ assert {"python", "elixir", "dart", "haskell", "go"} & _NON_CODE_LANGUAGES == set()
+
+ def test_merged_entry_patterns_present_on_specs(self) -> None:
+ # Every language with a citable convention declares it. Deliberate
+ # skips: julia (src/<Pkg>.jl is package-named), R (no convention),
+ # PHP bin/console (the bare filename "console" is too generic).
+ for tag, patterns in _ENTRY_PATTERNS_BY_LANGUAGE.items():
+ spec = REGISTRY.get(tag)
+ assert spec is not None, tag
+ assert spec.entry_point_patterns == patterns, tag
+
+ def test_entry_flag_stems_match_historical_traverser_set(self) -> None:
+ # The traverser's is_entry_point stem set, now registry-derived —
+ # parity with the historical hard-coded frozenset (run.py/server.py
+ # extras were redundant with the run/server stems).
+ assert REGISTRY.entry_flag_stems() == frozenset(
+ {"main", "index", "app", "run", "server", "start", "wsgi", "asgi"}
+ )
diff --git a/tests/unit/ingestion/test_lightweight_resolvers.py b/tests/unit/ingestion/test_lightweight_resolvers.py
new file mode 100644
index 000000000..73e2e5dc8
--- /dev/null
+++ b/tests/unit/ingestion/test_lightweight_resolvers.py
@@ -0,0 +1,660 @@
+"""Unit tests for the lightweight (regex-tier) import extractors + resolvers.
+
+Covers Elixir, Dart, Clojure, Haskell, Erlang, and F#: each import form the
+extractor claims, the declared-module index (declaration + path-convention
+inverse), relative/package forms, and false-positive guards.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.lightweight_imports import (
+ LIGHTWEIGHT_IMPORT_LANGUAGES,
+ extract_lightweight_imports,
+)
+from repowise.core.ingestion.lightweight_imports.clojure import extract_clojure_imports
+from repowise.core.ingestion.lightweight_imports.dart import extract_dart_imports
+from repowise.core.ingestion.lightweight_imports.elixir import extract_elixir_imports
+from repowise.core.ingestion.lightweight_imports.erlang import extract_erlang_imports
+from repowise.core.ingestion.lightweight_imports.haskell import extract_haskell_imports
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.resolvers import resolve_import
+from repowise.core.ingestion.resolvers.clojure import resolve_clojure_import
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.dart import resolve_dart_import
+from repowise.core.ingestion.resolvers.elixir import resolve_elixir_import
+from repowise.core.ingestion.resolvers.erlang import resolve_erlang_import
+from repowise.core.ingestion.resolvers.haskell import resolve_haskell_import
+
+
+def _ctx(repo: Path | None, files: dict[str, str]) -> ResolverContext:
+ """ResolverContext over *files* ({path: content}); writes them under *repo*."""
+ if repo is not None:
+ for rel, content in files.items():
+ target = repo / rel
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8")
+ stem_map: dict[str, list[str]] = {}
+ for p in files:
+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=set(files),
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ )
+
+
+def _modules(imports) -> list[str]:
+ return [imp.module_path for imp in imports]
+
+
+def _file_info(rel: str, lang: str) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=f"/tmp/{rel}",
+ language=lang, # type: ignore[arg-type]
+ size_bytes=0,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+# ---------------------------------------------------------------------------
+# Dispatch
+# ---------------------------------------------------------------------------
+
+
+class TestDispatch:
+ def test_registered_languages(self) -> None:
+ assert {
+ "elixir",
+ "dart",
+ "clojure",
+ "haskell",
+ "erlang",
+ "fsharp",
+ } == LIGHTWEIGHT_IMPORT_LANGUAGES
+
+ def test_other_language_returns_empty(self) -> None:
+ info = _file_info("x.zig", "zig")
+ assert extract_lightweight_imports(info, b'const std = @import("std");') == []
+
+ def test_resolver_dispatch_reaches_lightweight_resolver(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {"lib/jason.ex": "defmodule Jason do\nend\n", "lib/jason/encoder.ex": ""},
+ )
+ assert resolve_import("Jason", "lib/jason/encoder.ex", "elixir", ctx) == "lib/jason.ex"
+
+
+# ---------------------------------------------------------------------------
+# Elixir
+# ---------------------------------------------------------------------------
+
+
+class TestElixirExtraction:
+ def test_alias_import_use_require(self) -> None:
+ src = (
+ "defmodule Foo do\n"
+ " alias Foo.Bar\n"
+ " import Foo.Baz\n"
+ " require Logger\n"
+ " use GenServer\n"
+ "end\n"
+ )
+ assert _modules(extract_elixir_imports(src)) == [
+ "Foo.Bar",
+ "Foo.Baz",
+ "Logger",
+ "GenServer",
+ ]
+
+ def test_brace_expansion_and_multiline(self) -> None:
+ src = "alias Foo.{Bar, Baz.Qux,\n Deep}\n"
+ assert _modules(extract_elixir_imports(src)) == [
+ "Foo.Bar",
+ "Foo.Baz.Qux",
+ "Foo.Deep",
+ ]
+
+ def test_as_option_keeps_module(self) -> None:
+ src = "alias Foo.Bar, as: B\n"
+ assert _modules(extract_elixir_imports(src)) == ["Foo.Bar"]
+
+ def test_skips_erlang_atoms_and_module_macro(self) -> None:
+ src = "import :math\nalias __MODULE__.Inner\n"
+ assert extract_elixir_imports(src) == []
+
+ def test_import_marks_wildcard_names(self) -> None:
+ imports = extract_elixir_imports("import Foo.Bar\nalias Foo.Baz\n")
+ assert imports[0].imported_names == ["*"]
+ assert imports[1].imported_names == []
+
+ def test_dedup(self) -> None:
+ src = "alias Foo.Bar\nrequire Foo.Bar\n"
+ assert _modules(extract_elixir_imports(src)) == ["Foo.Bar"]
+
+
+class TestElixirResolution:
+ def test_declared_module(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "lib/jason.ex": "defmodule Jason do\nend\n",
+ "lib/jason/decoder.ex": "defmodule Jason.Decoder do\nend\n",
+ },
+ )
+ assert resolve_elixir_import("Jason.Decoder", "lib/jason.ex", ctx) == (
+ "lib/jason/decoder.ex"
+ )
+
+ def test_trailing_strip_hits_nested_module(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "lib/foo/bar.ex": "defmodule Foo.Bar do\n defmodule Baz do\n end\nend\n",
+ "lib/consumer.ex": "",
+ },
+ )
+ assert resolve_elixir_import("Foo.Bar.Baz", "lib/consumer.ex", ctx) == "lib/foo/bar.ex"
+
+ def test_path_convention_inverse_for_undeclared_file(self, tmp_path: Path) -> None:
+ # File without a defmodule head still resolves via lib/foo/bar.ex → Foo.Bar
+ ctx = _ctx(
+ tmp_path,
+ {"lib/my_app/web_router.ex": "# generated\n", "lib/other.ex": ""},
+ )
+ assert resolve_elixir_import("MyApp.WebRouter", "lib/other.ex", ctx) == (
+ "lib/my_app/web_router.ex"
+ )
+
+ def test_umbrella_inverse(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {"apps/core/lib/core/worker.ex": "# no decl\n", "apps/web/lib/web.ex": ""},
+ )
+ assert resolve_elixir_import("Core.Worker", "apps/web/lib/web.ex", ctx) == (
+ "apps/core/lib/core/worker.ex"
+ )
+
+ def test_stdlib_dropped_after_local_miss(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"lib/foo.ex": "defmodule Foo do\nend\n"})
+ assert resolve_elixir_import("GenServer", "lib/foo.ex", ctx) is None
+ assert resolve_elixir_import("Mix.Project", "lib/foo.ex", ctx) is None
+
+ def test_local_shadows_stdlib_name(self, tmp_path: Path) -> None:
+ # A repo that IS a stdlib-named library resolves locally first.
+ ctx = _ctx(
+ tmp_path,
+ {"lib/logger.ex": "defmodule Logger do\nend\n", "lib/use.ex": ""},
+ )
+ assert resolve_elixir_import("Logger", "lib/use.ex", ctx) == "lib/logger.ex"
+
+ def test_unknown_module_is_external(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"lib/foo.ex": "defmodule Foo do\nend\n"})
+ assert resolve_elixir_import("Phoenix.Controller", "lib/foo.ex", ctx) == (
+ "external:Phoenix.Controller"
+ )
+
+ def test_self_reference_returns_none(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"lib/foo.ex": "defmodule Foo do\nend\n"})
+ assert resolve_elixir_import("Foo", "lib/foo.ex", ctx) is None
+
+
+# ---------------------------------------------------------------------------
+# Dart
+# ---------------------------------------------------------------------------
+
+
+class TestDartExtraction:
+ def test_import_export_part(self) -> None:
+ src = (
+ "import 'package:args/src/parser.dart';\n"
+ "import 'dart:async';\n"
+ "import 'utils.dart' as utils;\n"
+ "export 'src/api.dart';\n"
+ "part 'impl.dart';\n"
+ )
+ imports = extract_dart_imports(src)
+ assert _modules(imports) == [
+ "package:args/src/parser.dart",
+ "dart:async",
+ "utils.dart",
+ "src/api.dart",
+ "impl.dart",
+ ]
+ by_module = {imp.module_path: imp for imp in imports}
+ assert by_module["src/api.dart"].is_reexport
+ assert not by_module["impl.dart"].is_reexport
+ assert by_module["utils.dart"].is_relative
+ assert not by_module["package:args/src/parser.dart"].is_relative
+
+ def test_part_of_uri_and_name_forms(self) -> None:
+ assert _modules(extract_dart_imports("part of 'lib.dart';\n")) == ["lib.dart"]
+ assert _modules(extract_dart_imports("part of my.library;\n")) == [
+ "library:my.library"
+ ]
+
+
+class TestDartResolution:
+ def test_sdk_uri_dropped(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"lib/main.dart": ""})
+ assert resolve_dart_import("dart:async", "lib/main.dart", ctx) is None
+
+ def test_package_self_import(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "pubspec.yaml": "name: args\nversion: 2.0.0\n",
+ "lib/src/parser.dart": "",
+ "lib/args.dart": "",
+ },
+ )
+ assert resolve_dart_import(
+ "package:args/src/parser.dart", "lib/args.dart", ctx
+ ) == "lib/src/parser.dart"
+
+ def test_monorepo_package_import(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "packages/core/pubspec.yaml": "name: core\n",
+ "packages/core/lib/core.dart": "",
+ "packages/app/pubspec.yaml": "name: app\n",
+ "packages/app/lib/main.dart": "",
+ },
+ )
+ assert resolve_dart_import(
+ "package:core/core.dart", "packages/app/lib/main.dart", ctx
+ ) == "packages/core/lib/core.dart"
+
+ def test_foreign_package_is_labelled_external(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"pubspec.yaml": "name: app\n", "lib/main.dart": ""})
+ assert resolve_dart_import("package:http/http.dart", "lib/main.dart", ctx) == (
+ "external:pub:http"
+ )
+
+ def test_relative_with_parent_traversal(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"lib/src/a.dart": "", "lib/b.dart": ""})
+ assert resolve_dart_import("../b.dart", "lib/src/a.dart", ctx) == "lib/b.dart"
+
+ def test_part_of_library_name(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "lib/args.dart": "library args;\npart 'src/impl.dart';\n",
+ "lib/src/impl.dart": "part of args;\n",
+ },
+ )
+ assert resolve_dart_import("library:args", "lib/src/impl.dart", ctx) == "lib/args.dart"
+
+ def test_unresolved_library_name_dropped(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"lib/a.dart": ""})
+ assert resolve_dart_import("library:nope", "lib/a.dart", ctx) is None
+
+
+# ---------------------------------------------------------------------------
+# Clojure
+# ---------------------------------------------------------------------------
+
+
+class TestClojureExtraction:
+ def test_ns_require_vectors(self) -> None:
+ src = (
+ "(ns foo.bar\n"
+ " (:require [baz.qux :as q]\n"
+ " [other.ns :refer [x y]]\n"
+ " plain.ns))\n"
+ )
+ assert _modules(extract_clojure_imports(src)) == [
+ "baz.qux",
+ "other.ns",
+ "plain.ns",
+ ]
+
+ def test_refer_vector_members_not_captured(self) -> None:
+ src = "(ns a (:require [b.c :refer [important-fn other-fn]]))"
+ assert _modules(extract_clojure_imports(src)) == ["b.c"]
+
+ def test_use_and_standalone_require(self) -> None:
+ src = "(ns a (:use [old.style]))\n(require '[dyn.ns :as d])\n"
+ assert _modules(extract_clojure_imports(src)) == ["old.style", "dyn.ns"]
+
+ def test_import_block_not_captured(self) -> None:
+ src = "(ns a (:import (java.util Date) [java.io File]))"
+ assert extract_clojure_imports(src) == []
+
+ def test_strings_and_comments_skipped(self) -> None:
+ src = '(ns a (:require [b.c]))\n; (:require [commented.out])\n(def s "(:require [fake.ns])")\n'
+ assert _modules(extract_clojure_imports(src)) == ["b.c"]
+
+
+class TestClojureResolution:
+ def test_declared_ns(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "src/foo/bar.clj": "(ns foo.bar)\n",
+ "src/foo/core.clj": "(ns foo.core)\n",
+ },
+ )
+ assert resolve_clojure_import("foo.bar", "src/foo/core.clj", ctx) == "src/foo/bar.clj"
+
+ def test_dash_underscore_inverse(self, tmp_path: Path) -> None:
+ # File with no ns decl: src/my_lib/web_utils.clj → my-lib.web-utils
+ ctx = _ctx(
+ tmp_path,
+ {"src/my_lib/web_utils.clj": "; no ns\n", "src/core.clj": "(ns core)\n"},
+ )
+ assert resolve_clojure_import("my-lib.web-utils", "src/core.clj", ctx) == (
+ "src/my_lib/web_utils.clj"
+ )
+
+ def test_cljc_and_cljs_share_mapping(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {"src/shared/util.cljc": "(ns shared.util)\n", "src/app.cljs": "(ns app)\n"},
+ )
+ assert resolve_clojure_import("shared.util", "src/app.cljs", ctx) == (
+ "src/shared/util.cljc"
+ )
+
+ def test_core_namespaces_dropped(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"src/a.clj": "(ns a)\n"})
+ assert resolve_clojure_import("clojure.string", "src/a.clj", ctx) is None
+ assert resolve_clojure_import("cljs.reader", "src/a.clj", ctx) is None
+
+ def test_unknown_ns_external(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"src/a.clj": "(ns a)\n"})
+ assert resolve_clojure_import("ring.core", "src/a.clj", ctx) == "external:ring.core"
+
+
+# ---------------------------------------------------------------------------
+# Haskell
+# ---------------------------------------------------------------------------
+
+
+class TestHaskellExtraction:
+ def test_import_forms(self) -> None:
+ src = (
+ "module Main where\n"
+ "import Data.Aeson\n"
+ "import qualified Data.Map as M\n"
+ "import Data.Text (Text, pack)\n"
+ 'import "lens" Control.Lens\n'
+ "import safe qualified Trusted.Mod\n"
+ )
+ assert _modules(extract_haskell_imports(src)) == [
+ "Data.Aeson",
+ "Data.Map",
+ "Data.Text",
+ "Control.Lens",
+ "Trusted.Mod",
+ ]
+
+ def test_indented_or_commented_import_not_captured(self) -> None:
+ src = "-- import Fake.Mod\nlet x = 1\n import Nested.NotReal\n"
+ assert extract_haskell_imports(src) == []
+
+
+class TestHaskellResolution:
+ def test_declared_module(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "src/Data/Aeson/Types.hs": "module Data.Aeson.Types where\n",
+ "src/Data/Aeson.hs": "module Data.Aeson where\n",
+ },
+ )
+ assert resolve_haskell_import("Data.Aeson.Types", "src/Data/Aeson.hs", ctx) == (
+ "src/Data/Aeson/Types.hs"
+ )
+
+ def test_local_shadows_base_prefix(self, tmp_path: Path) -> None:
+ # The aeson repo's own Data.Aeson resolves locally despite the Data. prefix.
+ ctx = _ctx(
+ tmp_path,
+ {"src/Data/Aeson.hs": "module Data.Aeson where\n", "app/Main.hs": ""},
+ )
+ assert resolve_haskell_import("Data.Aeson", "app/Main.hs", ctx) == "src/Data/Aeson.hs"
+
+ def test_capitalized_path_inverse(self, tmp_path: Path) -> None:
+ # No module decl: trailing capitalized segments derive the name.
+ ctx = _ctx(
+ tmp_path,
+ {"lib/Foo/Bar.hs": "-- no decl\n", "app/Main.hs": "module Main where\n"},
+ )
+ assert resolve_haskell_import("Foo.Bar", "app/Main.hs", ctx) == "lib/Foo/Bar.hs"
+
+ def test_base_modules_dropped(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"app/Main.hs": "module Main where\n"})
+ assert resolve_haskell_import("Control.Monad", "app/Main.hs", ctx) is None
+ assert resolve_haskell_import("Prelude", "app/Main.hs", ctx) is None
+
+ def test_unknown_module_external(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"app/Main.hs": "module Main where\n"})
+ assert resolve_haskell_import("Network.Wai", "app/Main.hs", ctx) == (
+ "external:Network.Wai"
+ )
+
+
+# ---------------------------------------------------------------------------
+# Erlang
+# ---------------------------------------------------------------------------
+
+
+class TestErlangExtraction:
+ def test_includes_and_behaviour(self) -> None:
+ src = (
+ '-module(my_worker).\n'
+ '-behaviour(gen_server).\n'
+ '-include("records.hrl").\n'
+ '-include_lib("kernel/include/logger.hrl").\n'
+ )
+ assert _modules(extract_erlang_imports(src)) == [
+ "records.hrl",
+ "lib:kernel/include/logger.hrl",
+ "gen_server",
+ ]
+
+ def test_qualified_calls_marked(self) -> None:
+ src = "-module(a).\nrun() -> my_util:do(1), lists:map(F, L).\n"
+ modules = _modules(extract_erlang_imports(src))
+ assert "call:my_util" in modules
+ assert "call:lists" in modules
+
+ def test_calls_in_comments_and_strings_skipped(self) -> None:
+ src = '-module(a).\n%% my_util:do()\nf() -> io_lib:format("calls x:y(", []).\n'
+ modules = _modules(extract_erlang_imports(src))
+ assert "call:my_util" not in modules
+ assert "call:x" not in modules
+ assert "call:io_lib" in modules
+
+
+class TestErlangResolution:
+ def test_include_importer_relative_and_app_include(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "src/my_worker.erl": "-module(my_worker).\n",
+ "include/records.hrl": "",
+ },
+ )
+ assert resolve_erlang_import("records.hrl", "src/my_worker.erl", ctx) == (
+ "include/records.hrl"
+ )
+
+ def test_include_lib_local_umbrella_app(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {
+ "apps/core/include/core.hrl": "",
+ "apps/web/src/web.erl": "-module(web).\n",
+ },
+ )
+ assert resolve_erlang_import(
+ "lib:core/include/core.hrl", "apps/web/src/web.erl", ctx
+ ) == "apps/core/include/core.hrl"
+
+ def test_include_lib_foreign_app_external(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"src/a.erl": "-module(a).\n"})
+ assert resolve_erlang_import("lib:kernel/include/logger.hrl", "src/a.erl", ctx) == (
+ "external:kernel"
+ )
+
+ def test_qualified_call_local_hit(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {"src/my_util.erl": "-module(my_util).\n", "src/a.erl": "-module(a).\n"},
+ )
+ assert resolve_erlang_import("call:my_util", "src/a.erl", ctx) == "src/my_util.erl"
+
+ def test_qualified_call_miss_is_dropped_not_external(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, {"src/a.erl": "-module(a).\n"})
+ assert resolve_erlang_import("call:lists", "src/a.erl", ctx) is None
+ assert resolve_erlang_import("call:some_dep", "src/a.erl", ctx) is None
+
+ def test_behaviour_local_then_otp_drop(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ {"src/my_behaviour.erl": "-module(my_behaviour).\n", "src/a.erl": "-module(a).\n"},
+ )
+ assert resolve_erlang_import("my_behaviour", "src/a.erl", ctx) == (
+ "src/my_behaviour.erl"
+ )
+ assert resolve_erlang_import("gen_server", "src/a.erl", ctx) is None
+
+
+# ---------------------------------------------------------------------------
+# F#
+# ---------------------------------------------------------------------------
+
+
+class TestFSharpExtraction:
+ def test_open_forms(self) -> None:
+ from repowise.core.ingestion.lightweight_imports.fsharp import (
+ extract_fsharp_imports,
+ )
+
+ src = (
+ "namespace MyApp.Core\n"
+ "open System\n"
+ "open MyApp.Domain\n"
+ "open type System.Math\n"
+ "let x = 1\n"
+ )
+ assert _modules(extract_fsharp_imports(src)) == [
+ "System",
+ "MyApp.Domain",
+ "System.Math",
+ ]
+
+
+class TestFSharpResolution:
+ def test_unambiguous_module_resolves(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion.resolvers.fsharp import resolve_fsharp_import
+
+ ctx = _ctx(
+ tmp_path,
+ {
+ "src/Domain.fs": "module MyApp.Domain\n",
+ "src/App.fs": "module MyApp.App\nopen MyApp.Domain\n",
+ },
+ )
+ assert resolve_fsharp_import("MyApp.Domain", "src/App.fs", ctx) == "src/Domain.fs"
+
+ def test_ambiguous_namespace_yields_no_edge(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion.resolvers.fsharp import resolve_fsharp_import
+
+ ctx = _ctx(
+ tmp_path,
+ {
+ "src/A.fs": "namespace MyApp.Core\n",
+ "src/B.fs": "namespace MyApp.Core\n",
+ "src/C.fs": "module MyApp.App\n",
+ },
+ )
+ assert resolve_fsharp_import("MyApp.Core", "src/C.fs", ctx) is None
+
+ def test_nested_module_binding_not_indexed(self, tmp_path: Path) -> None:
+ # `module Helpers =` is a nested binding, not a file-level decl.
+ from repowise.core.ingestion.resolvers.fsharp import resolve_fsharp_import
+
+ ctx = _ctx(
+ tmp_path,
+ {
+ "src/Lib.fs": "module MyApp.Lib\nmodule Helpers =\n let x = 1\n",
+ "src/App.fs": "module MyApp.App\n",
+ },
+ )
+ # trailing strip: open MyApp.Lib.Helpers hits the file-level MyApp.Lib
+ assert resolve_fsharp_import("MyApp.Lib.Helpers", "src/App.fs", ctx) == "src/Lib.fs"
+
+ def test_dotnet_namespaces_dropped(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion.resolvers.fsharp import resolve_fsharp_import
+
+ ctx = _ctx(tmp_path, {"src/App.fs": "module MyApp.App\n"})
+ assert resolve_fsharp_import("System.IO", "src/App.fs", ctx) is None
+ assert resolve_fsharp_import("FSharp.Control", "src/App.fs", ctx) is None
+
+ def test_unknown_namespace_external(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion.resolvers.fsharp import resolve_fsharp_import
+
+ ctx = _ctx(tmp_path, {"src/App.fs": "module MyApp.App\n"})
+ assert resolve_fsharp_import("Newtonsoft.Json", "src/App.fs", ctx) == (
+ "external:Newtonsoft.Json"
+ )
+
+
+class TestFSharpCompileOrder:
+ def test_adjacent_spine_edges(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion.languages.fsharp_compile_order import (
+ add_fsharp_compile_order_edges,
+ )
+
+ (tmp_path / "src").mkdir(parents=True)
+ (tmp_path / "src/App.fsproj").write_text(
+ "<Project>\n <ItemGroup>\n"
+ ' <Compile Include="Domain.fs" />\n'
+ ' <Compile Include="Logic.fs" />\n'
+ ' <Compile Include="Program.fs" />\n'
+ ' <Compile Include="$(Generated)/Gen.fs" />\n'
+ " </ItemGroup>\n</Project>\n"
+ )
+ graph = nx.DiGraph()
+ for p in ("src/Domain.fs", "src/Logic.fs", "src/Program.fs"):
+ graph.add_node(p)
+ added = add_fsharp_compile_order_edges(graph, tmp_path)
+ assert added == 2
+ assert graph.has_edge("src/Logic.fs", "src/Domain.fs")
+ assert graph.has_edge("src/Program.fs", "src/Logic.fs")
+ edge = graph["src/Logic.fs"]["src/Domain.fs"]
+ assert edge["edge_type"] == "imports"
+ assert edge["hint_source"] == "compile_order"
+
+ def test_existing_edge_wins(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion.languages.fsharp_compile_order import (
+ add_fsharp_compile_order_edges,
+ )
+
+ (tmp_path / "App.fsproj").write_text(
+ '<Project><ItemGroup><Compile Include="A.fs" /><Compile Include="B.fs" />'
+ "</ItemGroup></Project>"
+ )
+ graph = nx.DiGraph()
+ graph.add_node("A.fs")
+ graph.add_node("B.fs")
+ graph.add_edge("B.fs", "A.fs", edge_type="imports", imported_names=["X"])
+ added = add_fsharp_compile_order_edges(graph, tmp_path)
+ assert added == 0
+ assert graph["B.fs"]["A.fs"]["imported_names"] == ["X"]
diff --git a/tests/unit/ingestion/test_luau_resolver.py b/tests/unit/ingestion/test_luau_resolver.py
index 78807c336..ce79be836 100644
--- a/tests/unit/ingestion/test_luau_resolver.py
+++ b/tests/unit/ingestion/test_luau_resolver.py
@@ -4,9 +4,9 @@ Covers the two resolution modes implemented in this PR:
- String-literal requires (``require("relative/path")``)
- ``script`` / ``script.Parent`` relative instance paths
-
-The ``game.<Service>.Path`` absolute form requires Rojo project JSON and is
-explicitly deferred to a follow-up (issue #52); see the xfail case.
+- ``game.<Service>.Path`` absolute instance paths via Rojo
+ ``default.project.json`` (issue #52)
+- ``@alias`` requires via ``.luaurc`` aliases (issue #52)
Parser contract
---------------
@@ -21,7 +21,6 @@ production handoff.
from __future__ import annotations
import networkx as nx
-import pytest
from repowise.core.ingestion.resolvers.context import ResolverContext
from repowise.core.ingestion.resolvers.luau import resolve_luau_import
@@ -137,48 +136,180 @@ class TestStringLiteral:
got = resolve_luau_import("nowhere", "src/a.luau", ctx)
assert got == "external:nowhere"
- def test_luaurc_alias_is_external_until_follow_up(self) -> None:
- # `.luaurc` `@alias` resolution is deferred — see
- # TestLuaurcAlias.test_alias_resolves_via_luaurc_follow_up.
+ def test_alias_without_luaurc_is_external(self) -> None:
+ # No .luaurc anywhere (no repo_path at all here) → the alias keeps
+ # the external-node fallback instead of guessing a file.
ctx = _ctx({"src/dependency.luau"})
got = resolve_luau_import("@dep", "src/main.luau", ctx)
assert got == "external:@dep"
+def _repo_ctx(tmp_path, paths: set[str], files: dict[str, str]) -> ResolverContext:
+ """Context with a real repo dir holding config *files* (Rojo/.luaurc)."""
+ for rel, text in files.items():
+ full = tmp_path / rel
+ full.parent.mkdir(parents=True, exist_ok=True)
+ full.write_text(text)
+ ctx = _ctx(paths)
+ ctx.repo_path = tmp_path
+ return ctx
+
+
class TestAbsoluteInstancePath:
- @pytest.mark.xfail(
- reason="Rojo default.project.json-aware resolution — issue #52 follow-up.",
- strict=True,
- )
- def test_game_replicated_storage_resolves_via_rojo_tree(self) -> None:
- """Expected end state: given a Rojo project whose tree maps
- ``ReplicatedStorage.Shared`` to ``src/shared``, a require of
- ``game.ReplicatedStorage.Shared.Util`` resolves to
- ``src/shared/Util.luau``.
+ def test_game_replicated_storage_resolves_via_rojo_tree(self, tmp_path) -> None:
+ """Given a Rojo project whose tree maps ``ReplicatedStorage.Shared``
+ to ``src/shared``, ``game.ReplicatedStorage.Shared.Util`` resolves to
+ ``src/shared/Util.luau`` (issue #52).
"""
- ctx = _ctx({"src/shared/Util.luau"})
- got = resolve_luau_import("game.ReplicatedStorage.Shared.Util", "src/client/main.luau", ctx)
+ project = """{
+ "name": "MyGame",
+ "tree": {
+ "$className": "DataModel",
+ "ReplicatedStorage": {
+ "Shared": { "$path": "src/shared" }
+ }
+ }
+}"""
+ ctx = _repo_ctx(
+ tmp_path, {"src/shared/Util.luau"}, {"default.project.json": project}
+ )
+ got = resolve_luau_import(
+ "game.ReplicatedStorage.Shared.Util", "src/client/main.luau", ctx
+ )
+ assert got == "src/shared/Util.luau"
+
+ def test_get_service_idiom_resolves(self, tmp_path) -> None:
+ project = """{
+ "tree": {
+ "ReplicatedStorage": { "Shared": { "$path": "src/shared" } }
+ }
+}"""
+ ctx = _repo_ctx(
+ tmp_path, {"src/shared/Util.luau"}, {"default.project.json": project}
+ )
+ got = resolve_luau_import(
+ 'game:GetService("ReplicatedStorage").Shared.Util',
+ "src/client/main.luau",
+ ctx,
+ )
assert got == "src/shared/Util.luau"
+ def test_nested_tree_and_module_directory(self, tmp_path) -> None:
+ # Deeper instance nesting + module-as-directory (init.luau).
+ project = """{
+ "tree": {
+ "ServerScriptService": {
+ "Server": {
+ "Systems": { "$path": "src/server/systems" }
+ }
+ }
+ }
+}"""
+ ctx = _repo_ctx(
+ tmp_path,
+ {"src/server/systems/Combat/init.luau"},
+ {"default.project.json": project},
+ )
+ got = resolve_luau_import(
+ "game.ServerScriptService.Server.Systems.Combat", "src/main.luau", ctx
+ )
+ assert got == "src/server/systems/Combat/init.luau"
+
+ def test_missing_project_file_falls_back_to_external(self, tmp_path) -> None:
+ # Current behavior preserved: no default.project.json → external node.
+ ctx = _repo_ctx(tmp_path, {"src/shared/Util.luau"}, {})
+ got = resolve_luau_import(
+ "game.ReplicatedStorage.Shared.Util", "src/client/main.luau", ctx
+ )
+ assert got == "external:game.ReplicatedStorage.Shared.Util"
+
+ def test_unmapped_instance_path_goes_external(self, tmp_path) -> None:
+ project = '{ "tree": { "ReplicatedStorage": { "$path": "src/shared" } } }'
+ ctx = _repo_ctx(
+ tmp_path, {"src/shared/Util.luau"}, {"default.project.json": project}
+ )
+ got = resolve_luau_import("game.Workspace.Thing", "src/main.luau", ctx)
+ assert got == "external:game.Workspace.Thing"
+
class TestLuaurcAlias:
- @pytest.mark.xfail(
- reason=".luaurc alias-aware resolution — second Luau follow-up, parallel to Rojo.",
- strict=True,
- )
- def test_alias_resolves_via_luaurc_follow_up(self) -> None:
- """Expected end state: given a ``.luaurc`` alongside the importer
- declaring ``{"aliases": {"dep": "./dependency"}}``, a require of
- ``@dep`` resolves to ``src/dependency.luau``.
-
- Counts from running `repowise init` against the upstream
- luau-lang/luau repo: 24 `@alias` requires — every one of them
- currently lands on the external-node fallback. Implementing this
- needs a ``.luaurc`` reader layered in via
- ``core/ingestion/dynamic_hints/luaurc.py`` (analogous to the Rojo
- reader), with lookup walking parent directories and child
- ``.luaurc`` files overriding parent aliases.
+ def test_alias_resolves_via_luaurc(self, tmp_path) -> None:
+ """A ``.luaurc`` above the importer declaring
+ ``{"aliases": {"dep": "./dependency"}}`` makes ``@dep`` resolve to
+ ``src/dependency.luau`` (issue #52's second half — on
+ luau-lang/luau, 24 ``@alias`` requires previously all landed on the
+ external-node fallback).
"""
- ctx = _ctx({"src/dependency.luau"})
+ ctx = _repo_ctx(
+ tmp_path,
+ {"src/dependency.luau"},
+ {"src/.luaurc": '{"aliases": {"dep": "./dependency"}}'},
+ )
got = resolve_luau_import("@dep", "src/main.luau", ctx)
assert got == "src/dependency.luau"
+
+ def test_alias_subpath_and_comments(self, tmp_path) -> None:
+ luaurc = """{
+ // shared code lives here
+ "aliases": { "shared": "./shared" }
+}"""
+ ctx = _repo_ctx(
+ tmp_path,
+ {"src/shared/util/Signal.luau"},
+ {"src/.luaurc": luaurc},
+ )
+ got = resolve_luau_import("@shared/util/Signal", "src/client/main.luau", ctx)
+ assert got == "src/shared/util/Signal.luau"
+
+ def test_child_luaurc_overrides_parent(self, tmp_path) -> None:
+ # Parent maps @dep to ./a, the importer's own dir remaps it to ./b —
+ # the nearest declaration wins.
+ ctx = _repo_ctx(
+ tmp_path,
+ {"a.luau", "src/b.luau"},
+ {
+ ".luaurc": '{"aliases": {"dep": "./a"}}',
+ "src/.luaurc": '{"aliases": {"dep": "./b"}}',
+ },
+ )
+ got = resolve_luau_import("@dep", "src/main.luau", ctx)
+ assert got == "src/b.luau"
+
+ def test_parent_alias_visible_from_subdir(self, tmp_path) -> None:
+ ctx = _repo_ctx(
+ tmp_path,
+ {"libs/dep/init.luau"},
+ {".luaurc": '{"aliases": {"dep": "./libs/dep"}}'},
+ )
+ got = resolve_luau_import("@dep", "src/deeply/nested/main.luau", ctx)
+ assert got == "libs/dep/init.luau"
+
+ def test_unknown_alias_goes_external(self, tmp_path) -> None:
+ ctx = _repo_ctx(
+ tmp_path,
+ {"src/dependency.luau"},
+ {"src/.luaurc": '{"aliases": {"dep": "./dependency"}}'},
+ )
+ got = resolve_luau_import("@nope", "src/main.luau", ctx)
+ assert got == "external:@nope"
+
+
+class TestBareScriptParent:
+ def test_spec_requires_sibling_init_module(self, tmp_path) -> None:
+ # Roblox idiom: lib/init.spec.lua tests its own module with
+ # ``require(script.Parent)`` — the container directory IS the
+ # module (backed by its init.lua).
+ ctx = _ctx({"lib/init.lua", "lib/init.spec.lua"})
+ resolved = resolve_luau_import("script.Parent", "lib/init.spec.lua", ctx)
+ assert resolved == "lib/init.lua"
+
+ def test_bare_parent_without_init_goes_external(self, tmp_path) -> None:
+ ctx = _ctx({"lib/foo.lua", "lib/foo.spec.lua"})
+ resolved = resolve_luau_import("script.Parent", "lib/foo.spec.lua", ctx)
+ assert resolved is None or resolved.startswith("external:")
+
+ def test_bare_parent_never_resolves_to_importer(self, tmp_path) -> None:
+ # init.lua itself saying require(script.Parent) must not self-link.
+ ctx = _ctx({"lib/init.lua"})
+ resolved = resolve_luau_import("script.Parent", "lib/init.lua", ctx)
+ assert resolved != "lib/init.lua"
diff --git a/tests/unit/ingestion/test_php_resolver.py b/tests/unit/ingestion/test_php_resolver.py
index 7ffb2c44d..37fba69a8 100644
--- a/tests/unit/ingestion/test_php_resolver.py
+++ b/tests/unit/ingestion/test_php_resolver.py
@@ -92,3 +92,73 @@ class TestPhpResolverIntegration:
ctx = _ctx(tmp_path, ["src/Foo.php"])
result = resolve_php_import("Vendor\\Lib\\Missing", "src/Foo.php", ctx)
assert result == "external:Vendor\\Lib\\Missing"
+
+
+class TestFileBasedRequires:
+ def test_importer_relative_require(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["legacy/index.php", "legacy/inc/db.php"])
+ got = resolve_php_import("inc/db.php", "legacy/index.php", ctx)
+ assert got == "legacy/inc/db.php"
+
+ def test_dir_concatenation_leading_slash(self, tmp_path: Path) -> None:
+ # require __DIR__ . '/inc/db.php' captures '/inc/db.php' —
+ # importer-relative by construction.
+ ctx = _ctx(tmp_path, ["legacy/index.php", "legacy/inc/db.php"])
+ got = resolve_php_import("/inc/db.php", "legacy/index.php", ctx)
+ assert got == "legacy/inc/db.php"
+
+ def test_repo_root_relative_require(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["app/bootstrap.php", "lib/helpers.php"])
+ got = resolve_php_import("lib/helpers.php", "app/bootstrap.php", ctx)
+ assert got == "lib/helpers.php"
+
+ def test_parent_relative_require(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["app/sub/page.php", "app/config.php"])
+ got = resolve_php_import("../config.php", "app/sub/page.php", ctx)
+ assert got == "app/config.php"
+
+ def test_unresolved_literal_is_external_not_fuzzy(self, tmp_path: Path) -> None:
+ # A literal path matching nothing must NOT stem-match a same-named
+ # file elsewhere.
+ ctx = _ctx(tmp_path, ["other/place/db.php", "index.php"])
+ got = resolve_php_import("inc/db.php", "index.php", ctx)
+ assert got == "external:inc/db.php"
+
+ def test_psr4_use_unaffected(self, tmp_path: Path) -> None:
+ # Namespace imports don't end in .php and keep the PSR-4 path.
+ (tmp_path / "composer.json").write_text(
+ '{"autoload": {"psr-4": {"App\\\\": "src/"}}}'
+ )
+ src = tmp_path / "src" / "Service"
+ src.mkdir(parents=True)
+ (src / "Mailer.php").write_text("<?php namespace App\\Service; class Mailer {}\n")
+ ctx = _ctx(tmp_path, ["src/Service/Mailer.php"])
+ got = resolve_php_import("App\\Service\\Mailer", "index.php", ctx)
+ assert got == "src/Service/Mailer.php"
+
+
+class TestRequireExtraction:
+ def test_all_require_shapes_extract(self) -> None:
+ from datetime import datetime
+
+ from repowise.core.ingestion.models import FileInfo
+ from repowise.core.ingestion.parser import ASTParser
+
+ fi = FileInfo(
+ path="index.php", abs_path="/tmp/index.php", language="php",
+ size_bytes=1, git_hash="", last_modified=datetime.now(),
+ is_test=False, is_config=False, is_api_contract=False,
+ is_entry_point=False,
+ )
+ src = (
+ b"<?php\n"
+ b"require 'lib/helpers.php';\n" # single-quoted (string node)
+ b'require_once "config/app.php";\n' # double-quoted (encapsed)
+ b"include __DIR__ . '/inc/db.php';\n" # __DIR__ concatenation
+ b'require __DIR__ . "/inc/auth.php";\n'
+ )
+ pf = ASTParser().parse_file(fi, src)
+ modules = sorted(i.module_path for i in pf.imports)
+ assert modules == [
+ "/inc/auth.php", "/inc/db.php", "config/app.php", "lib/helpers.php",
+ ]
diff --git a/tests/unit/ingestion/test_ruby_resolver.py b/tests/unit/ingestion/test_ruby_resolver.py
index 4c8b10776..2a8a44086 100644
--- a/tests/unit/ingestion/test_ruby_resolver.py
+++ b/tests/unit/ingestion/test_ruby_resolver.py
@@ -89,3 +89,133 @@ class TestRubyResolverIntegration:
ctx = _ctx(tmp_path, ["lib/foo.rb"])
result = resolve_ruby_import("foo", "main.rb", ctx)
assert result == "lib/foo.rb"
+
+
+class TestLoadPathConvention:
+ def test_lib_probe_resolves_nested_require(self, tmp_path: Path) -> None:
+ # Ruby's $LOAD_PATH convention: require 'sinatra/base' from
+ # anywhere in the repo means lib/sinatra/base.rb.
+ paths = ["lib/sinatra/base.rb", "lib/sinatra.rb", "test/helper.rb"]
+ ctx = _ctx(tmp_path, paths)
+ assert resolve_ruby_import("sinatra/base", "test/helper.rb", ctx) == "lib/sinatra/base.rb"
+
+ def test_lib_probe_resolves_root_require(self, tmp_path: Path) -> None:
+ paths = ["lib/sinatra.rb", "examples/app.rb"]
+ ctx = _ctx(tmp_path, paths)
+ assert resolve_ruby_import("sinatra", "examples/app.rb", ctx) == "lib/sinatra.rb"
+
+ def test_repo_root_join_still_works(self, tmp_path: Path) -> None:
+ paths = ["helpers/util.rb", "main.rb"]
+ ctx = _ctx(tmp_path, paths)
+ assert resolve_ruby_import("helpers/util", "main.rb", ctx) == "helpers/util.rb"
+
+ def test_lib_probe_beats_basename_fuzzy_match(self, tmp_path: Path) -> None:
+ # base.rb exists in two places; the $LOAD_PATH join is exact and
+ # must win over any same-basename fuzzy hit.
+ paths = ["lib/sinatra/base.rb", "spec/fixtures/base.rb", "app.rb"]
+ ctx = _ctx(tmp_path, paths)
+ assert resolve_ruby_import("sinatra/base", "app.rb", ctx) == "lib/sinatra/base.rb"
+
+
+class TestGemDistinction:
+ def test_gemfile_gem_require_labelled_as_gem(self, tmp_path: Path) -> None:
+ (tmp_path / "Gemfile").write_text("source 'https://rubygems.org'\ngem 'rack'\n")
+ ctx = _ctx(tmp_path, ["app.rb"])
+ got = resolve_ruby_import("rack", "app.rb", ctx)
+ assert got == "external:gem:rack"
+
+ def test_gem_subpath_require_labelled_as_gem(self, tmp_path: Path) -> None:
+ (tmp_path / "Gemfile").write_text("gem 'rack'\n")
+ ctx = _ctx(tmp_path, ["app.rb"])
+ got = resolve_ruby_import("rack/protection", "app.rb", ctx)
+ assert got == "external:gem:rack/protection"
+
+ def test_dashed_gem_name_matches_slash_require(self, tmp_path: Path) -> None:
+ (tmp_path / "Gemfile").write_text("gem 'rack-protection'\n")
+ ctx = _ctx(tmp_path, ["app.rb"])
+ got = resolve_ruby_import("rack/protection", "app.rb", ctx)
+ assert got == "external:gem:rack/protection"
+
+ def test_gemspec_dependency_recognised(self, tmp_path: Path) -> None:
+ (tmp_path / "mylib.gemspec").write_text(
+ 'Gem::Specification.new do |s|\n s.add_dependency "mustermann"\n'
+ ' s.add_development_dependency "rack-test"\nend\n'
+ )
+ ctx = _ctx(tmp_path, ["app.rb"])
+ assert resolve_ruby_import("mustermann", "app.rb", ctx) == "external:gem:mustermann"
+ # rake itself ships with the interpreter (stdlib drop); a dashed
+ # dev dependency keeps the gem label.
+ assert resolve_ruby_import("rack/test", "app.rb", ctx) == "external:gem:rack/test"
+
+ def test_unknown_require_stays_plain_external(self, tmp_path: Path) -> None:
+ (tmp_path / "Gemfile").write_text("gem 'rack'\n")
+ ctx = _ctx(tmp_path, ["app.rb"])
+ got = resolve_ruby_import("definitely_not_a_thing", "app.rb", ctx)
+ assert got == "external:definitely_not_a_thing"
+
+ def test_local_file_beats_gem_label(self, tmp_path: Path) -> None:
+ # The repo IS the gem: require 'sinatra/base' must resolve locally
+ # even though sinatra.gemspec names dependencies.
+ (tmp_path / "Gemfile").write_text("gem 'sinatra'\n")
+ ctx = _ctx(tmp_path, ["lib/sinatra/base.rb", "app.rb"])
+ assert resolve_ruby_import("sinatra/base", "app.rb", ctx) == "lib/sinatra/base.rb"
+
+
+class TestRubyStdlib:
+ def test_stdlib_requires_dropped(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["app.rb"])
+ assert resolve_ruby_import("stringio", "app.rb", ctx) is None
+ assert resolve_ruby_import("net/http", "app.rb", ctx) is None
+ assert resolve_ruby_import("open-uri", "app.rb", ctx) is None
+
+ def test_local_file_beats_stdlib_name(self, tmp_path: Path) -> None:
+ # The repo may BE the json gem — exact lib/ probe wins.
+ ctx = _ctx(tmp_path, ["lib/json.rb", "app.rb"])
+ assert resolve_ruby_import("json", "app.rb", ctx) == "lib/json.rb"
+
+ def test_stdlib_never_fuzzy_matches(self, tmp_path: Path) -> None:
+ # require 'time' must not stem-match a repo file named time.rb in
+ # some unrelated subdirectory.
+ ctx = _ctx(tmp_path, ["app/models/time.rb", "app.rb"])
+ assert resolve_ruby_import("time", "app.rb", ctx) is None
+
+
+class TestSpecMirrorEdges:
+ def test_spec_mirror_links_subject(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+ (tmp_path / "rack-protection/lib/rack/protection").mkdir(parents=True)
+ (tmp_path / "rack-protection/spec/lib/rack/protection").mkdir(parents=True)
+ (tmp_path / "rack-protection/lib/rack/protection/base.rb").write_text(
+ "module Rack\n module Protection\n class Base\n end\n end\nend\n"
+ )
+ (tmp_path / "rack-protection/spec/lib/rack/protection/base_spec.rb").write_text(
+ "RSpec.describe Rack::Protection::Base do\nend\n"
+ )
+ traverser = FileTraverser(tmp_path)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=tmp_path)
+ for fi in traverser.traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ graph = builder.build()
+ edge = graph.get_edge_data(
+ "rack-protection/spec/lib/rack/protection/base_spec.rb",
+ "rack-protection/lib/rack/protection/base.rb",
+ )
+ assert edge is not None
+ assert edge.get("hint_source") == "spec_mirror"
+
+ def test_spec_without_mirror_stays_unlinked(self, tmp_path: Path) -> None:
+ from repowise.core.ingestion import ASTParser, FileTraverser, GraphBuilder
+
+ (tmp_path / "spec").mkdir()
+ (tmp_path / "lib").mkdir()
+ (tmp_path / "spec/integration_spec.rb").write_text("RSpec.describe 'x' do\nend\n")
+ (tmp_path / "lib/other.rb").write_text("class Other\nend\n")
+ traverser = FileTraverser(tmp_path)
+ parser = ASTParser()
+ builder = GraphBuilder(repo_path=tmp_path)
+ for fi in traverser.traverse():
+ builder.add_file(parser.parse_file(fi, Path(fi.abs_path).read_bytes()))
+ graph = builder.build()
+ assert not graph.has_edge("spec/integration_spec.rb", "lib/other.rb")
diff --git a/tests/unit/ingestion/test_rust_resolver.py b/tests/unit/ingestion/test_rust_resolver.py
index 19d406e64..80842b4ec 100644
--- a/tests/unit/ingestion/test_rust_resolver.py
+++ b/tests/unit/ingestion/test_rust_resolver.py
@@ -564,3 +564,103 @@ class TestBinTargetDiscovery:
assert idx is not None
foo = next(c for c in idx.crates if c.name == "foo")
assert foo.bin_paths == ()
+
+
+def _parsed_with_imports(import_specs: list[tuple[str, bool, list[str]]]):
+ """Fake ParsedFile carrying Import-shaped objects (module_path, is_reexport, names)."""
+ from types import SimpleNamespace
+
+ return SimpleNamespace(
+ imports=[
+ SimpleNamespace(module_path=mp, is_reexport=rx, imported_names=names)
+ for mp, rx, names in import_specs
+ ]
+ )
+
+
+class TestPubUseReexportFollowing:
+ def test_prelude_pattern_within_crate(self, tmp_path: Path) -> None:
+ # lib.rs: pub use crate::engine::Engine; app.rs: use crate::Engine
+ paths = ["src/lib.rs", "src/engine.rs", "src/app.rs"]
+ ctx = _ctx(tmp_path, paths)
+ ctx.parsed_files = {
+ "src/lib.rs": _parsed_with_imports(
+ [("crate::engine::Engine", True, ["Engine"])]
+ ),
+ "src/engine.rs": _parsed_with_imports([]),
+ "src/app.rs": _parsed_with_imports([]),
+ }
+ got = resolve_rust_import("crate::Engine", "src/app.rs", ctx)
+ assert got == "src/engine.rs"
+
+ def test_workspace_cross_crate_reexport(self, tmp_path: Path) -> None:
+ _write_workspace(tmp_path, ["crates/core", "crates/app"])
+ _write_member_crate(tmp_path, "crates/core", "my_core")
+ _write_member_crate(tmp_path, "crates/app", "my_app")
+ paths = [
+ "crates/core/src/lib.rs",
+ "crates/core/src/store.rs",
+ "crates/app/src/lib.rs",
+ "crates/app/src/main.rs",
+ ]
+ ctx = _ctx(tmp_path, paths)
+ ctx.parsed_files = {
+ "crates/core/src/lib.rs": _parsed_with_imports(
+ [("crate::store::Store", True, ["Store"])]
+ ),
+ "crates/core/src/store.rs": _parsed_with_imports([]),
+ "crates/app/src/lib.rs": _parsed_with_imports([]),
+ "crates/app/src/main.rs": _parsed_with_imports([]),
+ }
+ got = resolve_rust_import("my_core::Store", "crates/app/src/main.rs", ctx)
+ assert got == "crates/core/src/store.rs"
+
+ def test_brace_group_reexport(self, tmp_path: Path) -> None:
+ paths = ["src/lib.rs", "src/types.rs", "src/app.rs"]
+ ctx = _ctx(tmp_path, paths)
+ ctx.parsed_files = {
+ "src/lib.rs": _parsed_with_imports(
+ [("crate::types::{Foo, Bar}", True, ["Foo", "Bar"])]
+ ),
+ "src/types.rs": _parsed_with_imports([]),
+ "src/app.rs": _parsed_with_imports([]),
+ }
+ got = resolve_rust_import("crate::Bar", "src/app.rs", ctx)
+ assert got == "src/types.rs"
+
+ def test_glob_reexport(self, tmp_path: Path) -> None:
+ paths = ["src/lib.rs", "src/prelude.rs", "src/app.rs"]
+ ctx = _ctx(tmp_path, paths)
+ ctx.parsed_files = {
+ "src/lib.rs": _parsed_with_imports([("crate::prelude::*", True, ["*"])]),
+ "src/prelude.rs": _parsed_with_imports([]),
+ "src/app.rs": _parsed_with_imports([]),
+ }
+ got = resolve_rust_import("crate::Anything", "src/app.rs", ctx)
+ assert got == "src/prelude.rs"
+
+ def test_non_reexport_use_not_followed(self, tmp_path: Path) -> None:
+ # A plain (non-pub) use in lib.rs is not part of the crate's API.
+ paths = ["src/lib.rs", "src/engine.rs", "src/app.rs"]
+ ctx = _ctx(tmp_path, paths)
+ ctx.parsed_files = {
+ "src/lib.rs": _parsed_with_imports(
+ [("crate::engine::Engine", False, ["Engine"])]
+ ),
+ "src/engine.rs": _parsed_with_imports([]),
+ "src/app.rs": _parsed_with_imports([]),
+ }
+ got = resolve_rust_import("crate::Engine", "src/app.rs", ctx)
+ assert got is None
+
+ def test_reexport_cycle_does_not_recurse(self, tmp_path: Path) -> None:
+ # lib.rs re-exporting an unresolvable name through itself must
+ # terminate (depth cap), not recurse.
+ paths = ["src/lib.rs", "src/app.rs"]
+ ctx = _ctx(tmp_path, paths)
+ ctx.parsed_files = {
+ "src/lib.rs": _parsed_with_imports([("crate::Ghost", True, ["Ghost"])]),
+ "src/app.rs": _parsed_with_imports([]),
+ }
+ got = resolve_rust_import("crate::Ghost", "src/app.rs", ctx)
+ assert got is None
diff --git a/tests/unit/ingestion/test_scala_extractors.py b/tests/unit/ingestion/test_scala_extractors.py
index f8e065d86..77df9a85f 100644
--- a/tests/unit/ingestion/test_scala_extractors.py
+++ b/tests/unit/ingestion/test_scala_extractors.py
@@ -65,3 +65,49 @@ class TestScalaImports:
result = parser.parse_file(_file(), src)
modules = [imp.module_path for imp in result.imports]
assert any("scala" in m for m in modules)
+
+
+class TestScalaImportExtraction:
+ def test_full_dotted_path(self, parser: ASTParser) -> None:
+ # The grammar query captures only the first identifier; extraction
+ # must reconstruct the full dotted path.
+ src = b"package p\nimport com.example.util.Helper\n"
+ result = parser.parse_file(_file(), src)
+ assert [i.module_path for i in result.imports] == ["com.example.util.Helper"]
+ assert result.imports[0].imported_names == ["Helper"]
+
+ def test_underscore_wildcard_normalises_to_star(self, parser: ASTParser) -> None:
+ src = b"package p\nimport com.example.util._\n"
+ result = parser.parse_file(_file(), src)
+ assert [i.module_path for i in result.imports] == ["com.example.util.*"]
+ assert result.imports[0].imported_names == ["*"]
+
+ def test_scala3_star_wildcard(self, parser: ASTParser) -> None:
+ src = b"package p\nimport com.example.util.*\n"
+ result = parser.parse_file(_file(), src)
+ assert [i.module_path for i in result.imports] == ["com.example.util.*"]
+
+ def test_brace_imports_expand(self, parser: ASTParser) -> None:
+ src = b"package p\nimport com.example.model.{User, Order}\n"
+ result = parser.parse_file(_file(), src)
+ assert sorted(i.module_path for i in result.imports) == [
+ "com.example.model.Order",
+ "com.example.model.User",
+ ]
+
+ def test_rename_keeps_source_path_and_local_name(self, parser: ASTParser) -> None:
+ src = b"package p\nimport com.example.model.{Account => Acct}\n"
+ result = parser.parse_file(_file(), src)
+ assert [i.module_path for i in result.imports] == ["com.example.model.Account"]
+ assert result.imports[0].imported_names == ["Acct"]
+
+ def test_hidden_import_skipped_wildcard_kept(self, parser: ASTParser) -> None:
+ # {Account => _, _}: Account is excluded, the rest wildcards in.
+ src = b"package p\nimport com.example.model.{Account => _, _}\n"
+ result = parser.parse_file(_file(), src)
+ assert [i.module_path for i in result.imports] == ["com.example.model.*"]
+
+ def test_comma_separated_clauses(self, parser: ASTParser) -> None:
+ src = b"package p\nimport a.B, c.D\n"
+ result = parser.parse_file(_file(), src)
+ assert sorted(i.module_path for i in result.imports) == ["a.B", "c.D"]
diff --git a/tests/unit/ingestion/test_scala_resolver.py b/tests/unit/ingestion/test_scala_resolver.py
index 31a8566f3..a1500cce5 100644
--- a/tests/unit/ingestion/test_scala_resolver.py
+++ b/tests/unit/ingestion/test_scala_resolver.py
@@ -7,7 +7,10 @@ from pathlib import Path
import networkx as nx
from repowise.core.ingestion.resolvers.context import ResolverContext
-from repowise.core.ingestion.resolvers.scala import resolve_scala_import
+from repowise.core.ingestion.resolvers.scala import (
+ resolve_scala_import,
+ resolve_scala_import_all,
+)
from repowise.core.ingestion.resolvers.scala_build import build_scala_index
@@ -77,3 +80,95 @@ class TestScalaIndex:
ctx = _ctx(tmp_path, ["src/Foo.scala"])
result = resolve_scala_import("com.example.Foo", "main.scala", ctx)
assert result == "src/Foo.scala"
+
+
+def _make_scala(repo: Path, rel_path: str, package: str, decl: str) -> str:
+ full = repo / rel_path
+ full.parent.mkdir(parents=True, exist_ok=True)
+ full.write_text(f"package {package}\n\n{decl}\n")
+ return rel_path
+
+
+class TestScalaWorkspaceResolution:
+ def test_package_fqn_resolution(self, tmp_path: Path) -> None:
+ a = _make_scala(tmp_path, "src/main/scala/com/foo/Engine.scala", "com.foo", "class Engine")
+ ctx = _ctx(tmp_path, [a])
+ result = resolve_scala_import("com.foo.Engine", "Main.scala", ctx)
+ assert result == a
+
+ def test_type_in_differently_named_file(self, tmp_path: Path) -> None:
+ # FQN lookup keys on declared type names, not stems.
+ a = _make_scala(
+ tmp_path, "src/main/scala/com/foo/models.scala", "com.foo",
+ "case class User(name: String)\ncase class Order(id: Int)",
+ )
+ ctx = _ctx(tmp_path, [a])
+ assert resolve_scala_import("com.foo.User", "Main.scala", ctx) == a
+ assert resolve_scala_import("com.foo.Order", "Main.scala", ctx) == a
+
+ def test_trait_and_object_resolution(self, tmp_path: Path) -> None:
+ a = _make_scala(tmp_path, "src/main/scala/com/foo/Api.scala", "com.foo", "trait Api")
+ b = _make_scala(tmp_path, "src/main/scala/com/foo/Defaults.scala", "com.foo", "object Defaults")
+ ctx = _ctx(tmp_path, [a, b])
+ assert resolve_scala_import("com.foo.Api", "Main.scala", ctx) == a
+ assert resolve_scala_import("com.foo.Defaults", "Main.scala", ctx) == b
+
+ def test_wildcard_fans_out_to_package(self, tmp_path: Path) -> None:
+ a = _make_scala(tmp_path, "src/main/scala/com/foo/A.scala", "com.foo", "class A")
+ b = _make_scala(tmp_path, "src/main/scala/com/foo/B.scala", "com.foo", "class B")
+ ctx = _ctx(tmp_path, [a, b])
+ targets = resolve_scala_import_all("com.foo.*", "Main.scala", ctx)
+ assert set(targets) == {a, b}
+ # Scala 2 underscore form normalises identically.
+ targets = resolve_scala_import_all("com.foo._", "Main.scala", ctx)
+ assert set(targets) == {a, b}
+
+ def test_package_import_fans_out(self, tmp_path: Path) -> None:
+ a = _make_scala(tmp_path, "src/main/scala/com/foo/A.scala", "com.foo", "class A")
+ ctx = _ctx(tmp_path, [a])
+ targets = resolve_scala_import_all("com.foo", "Main.scala", ctx)
+ assert targets == (a,)
+
+ def test_stdlib_dropped(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, [])
+ assert resolve_scala_import_all("scala.collection.mutable", "Main.scala", ctx) == ()
+ assert resolve_scala_import_all("java.util.UUID", "Main.scala", ctx) == ()
+ assert resolve_scala_import_all("scala.concurrent.Future", "Main.scala", ctx) == ()
+
+ def test_unknown_external(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, [])
+ result = resolve_scala_import("org.typelevel.cats.Monad", "Main.scala", ctx)
+ assert result == "external:org.typelevel.cats.Monad"
+
+ def test_cross_language_scala_to_java(self, tmp_path: Path) -> None:
+ j = tmp_path / "src/main/java/com/foo/Legacy.java"
+ j.parent.mkdir(parents=True)
+ j.write_text("package com.foo;\npublic class Legacy {}\n")
+ ctx = _ctx(tmp_path, ["src/main/java/com/foo/Legacy.java"])
+ result = resolve_scala_import("com.foo.Legacy", "Main.scala", ctx)
+ assert result == "src/main/java/com/foo/Legacy.java"
+
+ def test_chained_package_clauses(self, tmp_path: Path) -> None:
+ full = tmp_path / "core/src/main/scala/tools/Runner.scala"
+ full.parent.mkdir(parents=True)
+ full.write_text("package org.example\npackage tools\n\nclass Runner\n")
+ ctx = _ctx(tmp_path, ["core/src/main/scala/tools/Runner.scala"])
+ result = resolve_scala_import("org.example.tools.Runner", "Main.scala", ctx)
+ assert result == "core/src/main/scala/tools/Runner.scala"
+
+ def test_multi_module_resolution(self, tmp_path: Path) -> None:
+ (tmp_path / "build.sbt").write_text(
+ 'lazy val core = project.in(file("core"))\n'
+ 'lazy val app = project.in(file("app"))\n'
+ )
+ core = _make_scala(
+ tmp_path, "core/src/main/scala/com/example/core/Engine.scala",
+ "com.example.core", "class Engine",
+ )
+ app = _make_scala(
+ tmp_path, "app/src/main/scala/com/example/app/Main.scala",
+ "com.example.app", "object Main extends App",
+ )
+ ctx = _ctx(tmp_path, [core, app])
+ result = resolve_scala_import("com.example.core.Engine", app, ctx)
+ assert result == core
diff --git a/tests/unit/ingestion/test_swift_extractors.py b/tests/unit/ingestion/test_swift_extractors.py
index d3f5eeadb..b047bb9c8 100644
--- a/tests/unit/ingestion/test_swift_extractors.py
+++ b/tests/unit/ingestion/test_swift_extractors.py
@@ -79,3 +79,12 @@ extension Foo: A, B {}
rels = {(r.child_name, r.parent_name) for r in result.heritage}
assert ("Foo", "A") in rels
assert ("Foo", "B") in rels
+
+
+class TestSwiftExportedImport:
+ def test_exported_import_is_reexport(self, parser: ASTParser) -> None:
+ src = b"@_exported import FooKit\nimport Foundation\n"
+ result = parser.parse_file(_file(), src)
+ by_module = {i.module_path: i for i in result.imports}
+ assert by_module["FooKit"].is_reexport is True
+ assert by_module["Foundation"].is_reexport is False
diff --git a/tests/unit/ingestion/test_swift_same_module.py b/tests/unit/ingestion/test_swift_same_module.py
new file mode 100644
index 000000000..79112b362
--- /dev/null
+++ b/tests/unit/ingestion/test_swift_same_module.py
@@ -0,0 +1,175 @@
+"""Unit tests for Swift intra-module type-reference edges."""
+
+from __future__ import annotations
+
+import networkx as nx
+
+from repowise.core.ingestion.languages.swift_same_module import (
+ resolve_swift_same_module_refs,
+)
+
+
+def _graph(paths: list[str]) -> nx.DiGraph:
+ g = nx.DiGraph()
+ for p in paths:
+ g.add_node(p, node_type="file")
+ return g
+
+
+class TestSwiftSameModule:
+ def test_same_target_type_reference(self) -> None:
+ texts = {
+ "Sources/Core/Engine.swift": "public final class Engine {}\n",
+ "Sources/Core/Runner.swift": (
+ "struct Runner {\n let engine = Engine()\n}\n"
+ ),
+ }
+ g = _graph(list(texts))
+ added = resolve_swift_same_module_refs(g, {"Core": "Sources/Core"}, texts)
+ assert added == 1
+ edge = g["Sources/Core/Runner.swift"]["Sources/Core/Engine.swift"]
+ assert edge["edge_type"] == "imports"
+ assert edge["hint_source"] == "same_module"
+ assert edge["imported_names"] == ["Engine"]
+
+ def test_cross_target_requires_real_import(self) -> None:
+ # Engine lives in Core; App files cannot see it without an import,
+ # so the same-module pass must not invent an edge across targets.
+ texts = {
+ "Sources/Core/Engine.swift": "public class Engine {}\n",
+ "Sources/App/Main.swift": "let engine = Engine()\n",
+ "Sources/App/Helper.swift": "struct Helper {}\n",
+ }
+ g = _graph(list(texts))
+ targets = {"Core": "Sources/Core", "App": "Sources/App"}
+ added = resolve_swift_same_module_refs(g, targets, texts)
+ assert added == 0
+
+ def test_ambiguous_type_no_edge(self) -> None:
+ texts = {
+ "Sources/Core/A.swift": "struct Config {}\n",
+ "Sources/Core/B.swift": "struct Config {}\n",
+ "Sources/Core/C.swift": "let c = Config()\n",
+ }
+ g = _graph(list(texts))
+ added = resolve_swift_same_module_refs(g, {"Core": "Sources/Core"}, texts)
+ assert added == 0
+
+ def test_stdlib_name_skipped(self) -> None:
+ texts = {
+ "Sources/Core/Data.swift": "struct Data {}\n",
+ "Sources/Core/Use.swift": "let d: Data? = nil\n",
+ }
+ g = _graph(list(texts))
+ added = resolve_swift_same_module_refs(g, {"Core": "Sources/Core"}, texts)
+ assert added == 0
+
+ def test_protocol_enum_actor_declarations_resolve(self) -> None:
+ texts = {
+ "Sources/Core/Shapes.swift": (
+ "protocol Drawable {}\nenum Mode { case a }\nactor Store {}\n"
+ ),
+ "Sources/Core/Use.swift": (
+ "struct Canvas: Drawable {\n"
+ " var mode: Mode = .a\n let store = Store()\n}\n"
+ ),
+ }
+ g = _graph(list(texts))
+ added = resolve_swift_same_module_refs(g, {"Core": "Sources/Core"}, texts)
+ assert added == 1
+ edge = g["Sources/Core/Use.swift"]["Sources/Core/Shapes.swift"]
+ assert sorted(edge["imported_names"]) == ["Drawable", "Mode", "Store"]
+
+ def test_no_spm_manifest_implicit_single_module(self) -> None:
+ # Xcode-style repo: no Package.swift → all files form one module.
+ texts = {
+ "MyApp/Model.swift": "struct Model {}\n",
+ "MyApp/ViewController.swift": "let m = Model()\n",
+ }
+ g = _graph(list(texts))
+ added = resolve_swift_same_module_refs(g, {}, texts)
+ assert added == 1
+ assert g.has_edge("MyApp/ViewController.swift", "MyApp/Model.swift")
+
+ def test_existing_edge_wins(self) -> None:
+ texts = {
+ "Sources/Core/Engine.swift": "class Engine {}\n",
+ "Sources/Core/Use.swift": "let e = Engine()\n",
+ }
+ g = _graph(list(texts))
+ g.add_edge(
+ "Sources/Core/Use.swift",
+ "Sources/Core/Engine.swift",
+ edge_type="imports",
+ imported_names=["Engine"],
+ )
+ added = resolve_swift_same_module_refs(g, {"Core": "Sources/Core"}, texts)
+ assert added == 0
+ assert "hint_source" not in g["Sources/Core/Use.swift"]["Sources/Core/Engine.swift"]
+
+ def test_extension_declares_nothing(self) -> None:
+ # An extension of Engine in another file must not claim the name.
+ texts = {
+ "Sources/Core/Engine.swift": "class Engine {}\n",
+ "Sources/Core/Engine+Extras.swift": "extension Engine {\n func go() {}\n}\n",
+ "Sources/Core/Use.swift": "let e = Engine()\n",
+ }
+ g = _graph(list(texts))
+ added = resolve_swift_same_module_refs(g, {"Core": "Sources/Core"}, texts)
+ # Use → Engine (unique declaration), and the extension file itself
+ # references Engine too — also → Engine.
+ assert added == 2
+ assert g.has_edge("Sources/Core/Use.swift", "Sources/Core/Engine.swift")
+ assert g.has_edge(
+ "Sources/Core/Engine+Extras.swift", "Sources/Core/Engine.swift"
+ )
+
+
+class TestSwiftEntryWarmup:
+ def test_main_attribute_flags_entry_point(self, tmp_path) -> None:
+ from types import SimpleNamespace
+
+ from repowise.core.ingestion.graph_warmups import _warmup_swift
+
+ app = tmp_path / "App.swift"
+ app.write_text("@main\nstruct MyApp {\n}\n")
+ other = tmp_path / "Helper.swift"
+ other.write_text("struct H {}\n")
+
+ g = nx.DiGraph()
+ g.add_node("App.swift", node_type="file")
+ g.add_node("Helper.swift", node_type="file")
+ ctx = SimpleNamespace(
+ graph=g,
+ parsed_files={
+ "App.swift": SimpleNamespace(
+ file_info=SimpleNamespace(language="swift", abs_path=str(app))
+ ),
+ "Helper.swift": SimpleNamespace(
+ file_info=SimpleNamespace(language="swift", abs_path=str(other))
+ ),
+ },
+ )
+ _warmup_swift(ctx)
+ assert g.nodes["App.swift"].get("is_entry_point") is True
+ assert g.nodes["Helper.swift"].get("is_entry_point") is not True
+
+ def test_uiapplicationmain_flags_entry_point(self, tmp_path) -> None:
+ from types import SimpleNamespace
+
+ from repowise.core.ingestion.graph_warmups import _warmup_swift
+
+ app = tmp_path / "AppDelegate.swift"
+ app.write_text("@UIApplicationMain\nclass AppDelegate: UIResponder {\n}\n")
+ g = nx.DiGraph()
+ g.add_node("AppDelegate.swift", node_type="file")
+ ctx = SimpleNamespace(
+ graph=g,
+ parsed_files={
+ "AppDelegate.swift": SimpleNamespace(
+ file_info=SimpleNamespace(language="swift", abs_path=str(app))
+ ),
+ },
+ )
+ _warmup_swift(ctx)
+ assert g.nodes["AppDelegate.swift"].get("is_entry_point") is True
diff --git a/tests/unit/ingestion/test_traverser.py b/tests/unit/ingestion/test_traverser.py
index 0e83d1be9..881b5debb 100644
--- a/tests/unit/ingestion/test_traverser.py
+++ b/tests/unit/ingestion/test_traverser.py
@@ -649,3 +649,47 @@ class TestNestedGitRepoHandling:
assert any("ok.py" in p for p in paths)
assert not any("vendored" in p for p in paths)
+
+
+# ---------------------------------------------------------------------------
+# Entry-point flag (registry-derived conventions)
+# ---------------------------------------------------------------------------
+
+
+class TestEntryPointFlag:
+ def _flagged(self, tmp_path: Path) -> set[str]:
+ return {f.path for f in FileTraverser(tmp_path).traverse() if f.is_entry_point}
+
+ def test_new_language_conventions_flag_entry_points(self, tmp_path: Path) -> None:
+ files = {
+ "src/Application.kt": "fun main() {}",
+ "config.ru": "run App",
+ "myapp/src/myapp_app.erl": "-module(myapp_app).",
+ "lib/shop/application.ex": "defmodule Shop.Application do\nend",
+ "shop/core.clj": "(defn -main [])",
+ "cli/Program.fs": "[<EntryPoint>]\nlet main argv = 0",
+ "artisan": "#!/usr/bin/env php\n<?php",
+ }
+ for rel, content in files.items():
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(content)
+ flagged = self._flagged(tmp_path)
+ assert flagged == set(files), flagged
+
+ def test_historical_stem_parity_and_non_entries(self, tmp_path: Path) -> None:
+ files = {
+ "run.py": "print('x')", # covered by the run stem (dropped pattern)
+ "server.py": "print('x')",
+ "pkg/helper.py": "x = 1",
+ "latest_app.py": "x = 1", # _app suffix is Erlang-only (*_app.erl)
+ }
+ for rel, content in files.items():
+ p = tmp_path / rel
+ p.parent.mkdir(parents=True, exist_ok=True)
+ p.write_text(content)
+ flagged = self._flagged(tmp_path)
+ assert "run.py" in flagged
+ assert "server.py" in flagged
+ assert "pkg/helper.py" not in flagged
+ assert "latest_app.py" not in flagged
diff --git a/tests/unit/persistence/test_kg_models.py b/tests/unit/persistence/test_kg_models.py
index ced3ad760..a32141fea 100644
--- a/tests/unit/persistence/test_kg_models.py
+++ b/tests/unit/persistence/test_kg_models.py
@@ -8,8 +8,12 @@ import pytest
from repowise.core.persistence.crud import (
get_kg_layers,
+ get_kg_node_meta,
+ get_kg_project_meta,
get_kg_tour_steps,
upsert_kg_layers,
+ upsert_kg_node_meta,
+ upsert_kg_project_meta,
upsert_kg_tour_steps,
)
from tests.unit.persistence.helpers import insert_repo
@@ -124,3 +128,134 @@ async def test_kg_tour_steps_description_defaults_empty(async_session, repo):
)
result = await get_kg_tour_steps(async_session, repo.id)
assert result[0].description == ""
+
+
+# ---------------------------------------------------------------------------
+# Curated fields (sub-groups, layer-aware tour, project meta, node meta)
+# ---------------------------------------------------------------------------
+
+
+async def test_kg_layers_sub_groups_round_trip(async_session, repo):
+ """Curated subGroups survive the JSON → DB boundary verbatim."""
+ sub_groups = [
+ {"id": "layer:ui:forms", "name": "forms", "nodeIds": ["file:src/ui/form.tsx"]},
+ {"id": "layer:ui:tables", "name": "tables", "nodeIds": ["file:src/ui/table.tsx"]},
+ ]
+ await upsert_kg_layers(
+ async_session, repo.id,
+ [{"id": "layer:ui", "name": "UI", "nodeIds": [], "subGroups": sub_groups}],
+ )
+ result = await get_kg_layers(async_session, repo.id)
+ assert json.loads(result[0].sub_groups_json) == sub_groups
+
+
+async def test_kg_layers_sub_groups_default_empty(async_session, repo):
+ """Layers without subGroups (legacy / community layers) store []."""
+ await upsert_kg_layers(
+ async_session, repo.id,
+ [{"id": "layer:plain", "name": "Plain", "nodeIds": []}],
+ )
+ result = await get_kg_layers(async_session, repo.id)
+ assert json.loads(result[0].sub_groups_json) == []
+
+
+async def test_kg_layers_sub_groups_snake_case_variant(async_session, repo):
+ await upsert_kg_layers(
+ async_session, repo.id,
+ [{"id": "layer:s", "name": "S", "nodeIds": [],
+ "sub_groups": [{"id": "layer:s:x", "name": "x", "nodeIds": []}]}],
+ )
+ result = await get_kg_layers(async_session, repo.id)
+ assert json.loads(result[0].sub_groups_json)[0]["name"] == "x"
+
+
+async def test_kg_tour_steps_curated_fields_round_trip(async_session, repo):
+ """The six curated tour fields survive the JSON → DB boundary."""
+ steps = [
+ {
+ "order": 1,
+ "title": "main.py",
+ "target_path": "src/main.py",
+ "page_type": "file_page",
+ "depth": 0,
+ "kind": "code",
+ "reason": "Top of the stack (CLI) — start of the control flow.",
+ "layer_id": "layer:cli",
+ },
+ ]
+ await upsert_kg_tour_steps(async_session, repo.id, steps)
+ result = await get_kg_tour_steps(async_session, repo.id)
+ row = result[0]
+ assert row.target_path == "src/main.py"
+ assert row.page_type == "file_page"
+ assert row.depth == 0
+ assert row.kind == "code"
+ assert row.reason == "Top of the stack (CLI) — start of the control flow."
+ assert row.layer_id == "layer:cli"
+
+
+async def test_kg_tour_steps_legacy_steps_get_defaults(async_session, repo):
+ """Legacy LLM tour steps (no curated fields) store None/empty defaults."""
+ await upsert_kg_tour_steps(
+ async_session, repo.id,
+ [{"order": 1, "title": "Legacy", "description": "d", "nodeIds": ["file:a.py"]}],
+ )
+ row = (await get_kg_tour_steps(async_session, repo.id))[0]
+ assert row.target_path is None
+ assert row.layer_id is None
+ assert row.reason == ""
+ assert row.depth is None
+ assert row.kind == ""
+ assert row.page_type is None
+
+
+async def test_kg_project_meta_round_trip(async_session, repo):
+ await upsert_kg_project_meta(
+ async_session, repo.id,
+ entry_points=["src/main.py", "src/cli.py"],
+ entry_candidates=["src/main.py", "src/cli.py", "src/app.py"],
+ )
+ meta = await get_kg_project_meta(async_session, repo.id)
+ assert meta is not None
+ assert json.loads(meta.entry_points_json) == ["src/main.py", "src/cli.py"]
+ assert json.loads(meta.entry_candidates_json) == [
+ "src/main.py", "src/cli.py", "src/app.py",
+ ]
+
+
+async def test_kg_project_meta_replaces_on_reinit(async_session, repo):
+ """One row per repo: re-upsert replaces, never duplicates."""
+ await upsert_kg_project_meta(async_session, repo.id, entry_points=["old.py"])
+ await upsert_kg_project_meta(async_session, repo.id, entry_points=["new.py"])
+ meta = await get_kg_project_meta(async_session, repo.id)
+ assert json.loads(meta.entry_points_json) == ["new.py"]
+
+
+async def test_kg_project_meta_missing_returns_none(async_session, repo):
+ assert await get_kg_project_meta(async_session, repo.id) is None
+
+
+async def test_kg_node_meta_round_trip(async_session, repo):
+ nodes = [
+ {"id": "src/main.py", "type": "file", "summary": "CLI entry point.",
+ "tags": ["entry_point", "python"]},
+ {"id": "Dockerfile", "type": "service", "summary": "Container build.", "tags": []},
+ ]
+ await upsert_kg_node_meta(async_session, repo.id, nodes)
+ rows = {r.node_id: r for r in await get_kg_node_meta(async_session, repo.id)}
+ assert rows["src/main.py"].summary == "CLI entry point."
+ assert json.loads(rows["src/main.py"].tags_json) == ["entry_point", "python"]
+ assert rows["Dockerfile"].node_type == "service"
+
+
+async def test_kg_node_meta_replaces_on_reinit(async_session, repo):
+ await upsert_kg_node_meta(async_session, repo.id, [{"id": "old.py", "summary": "x"}])
+ await upsert_kg_node_meta(async_session, repo.id, [{"id": "new.py", "summary": "y"}])
+ rows = await get_kg_node_meta(async_session, repo.id)
+ assert len(rows) == 1
+ assert rows[0].node_id == "new.py"
+ assert rows[0].node_type == "file" # default
+
+
+async def test_kg_node_meta_empty_for_new_repo(async_session, repo):
+ assert await get_kg_node_meta(async_session, repo.id) == []
diff --git a/tests/unit/persistence/test_kg_pipeline_persist.py b/tests/unit/persistence/test_kg_pipeline_persist.py
new file mode 100644
index 000000000..9bb962340
--- /dev/null
+++ b/tests/unit/persistence/test_kg_pipeline_persist.py
@@ -0,0 +1,107 @@
+"""persist_generation carries curated KG meta (project entry points, node
+summaries/tags/types) into the DB alongside layers and tour steps."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.persistence.crud import (
+ get_kg_layers,
+ get_kg_node_meta,
+ get_kg_project_meta,
+ get_kg_tour_steps,
+)
+from repowise.core.pipeline.persist import persist_generation
+from tests.unit.persistence.helpers import insert_repo
+
+
+async def repo(async_session):
+ return await insert_repo(async_session)
+
+
+def _result(**kg_fields) -> SimpleNamespace:
+ defaults: dict = {"project": {}, "nodes": [], "layers": [], "tour": []}
+ kg = SimpleNamespace(**{**defaults, **kg_fields})
+ return SimpleNamespace(generated_pages=None, knowledge_graph_result=kg)
+
+
+async def test_persists_entry_points_from_project(async_session, repo):
+ result = _result(
+ project={
+ "name": "demo",
+ "entry_points": ["src/main.py"],
+ "entry_candidates": ["src/main.py", "src/app.py"],
+ }
+ )
+ await persist_generation(result, async_session, repo.id)
+
+ meta = await get_kg_project_meta(async_session, repo.id)
+ assert meta is not None
+ assert json.loads(meta.entry_points_json) == ["src/main.py"]
+ assert json.loads(meta.entry_candidates_json) == ["src/main.py", "src/app.py"]
+
+
+async def test_persists_file_node_meta_with_prefix_stripped(async_session, repo):
+ result = _result(
+ nodes=[
+ {
+ "id": "file:src/main.py",
+ "type": "file",
+ "summary": "CLI entry point.",
+ "tags": ["entry_point", "python"],
+ },
+ {"id": "file:Dockerfile", "type": "service", "summary": "Container build."},
+ # Non-file nodes (concepts, symbols) are not node-meta material.
+ {"id": "concept:auth", "type": "concept", "summary": "Auth concept."},
+ ]
+ )
+ await persist_generation(result, async_session, repo.id)
+
+ rows = {r.node_id: r for r in await get_kg_node_meta(async_session, repo.id)}
+ assert set(rows) == {"src/main.py", "Dockerfile"}
+ assert rows["src/main.py"].summary == "CLI entry point."
+ assert json.loads(rows["src/main.py"].tags_json) == ["entry_point", "python"]
+ assert rows["Dockerfile"].node_type == "service"
+
+
+async def test_no_curated_meta_writes_nothing(async_session, repo):
+ """Uncurated KG (no entry_points, no nodes) leaves the meta tables empty."""
+ await persist_generation(_result(), async_session, repo.id)
+
+ assert await get_kg_project_meta(async_session, repo.id) is None
+ assert await get_kg_node_meta(async_session, repo.id) == []
+
+
+async def test_layers_and_tour_still_persisted(async_session, repo):
+ """Existing layer/tour persistence is unchanged by the meta additions."""
+ result = _result(
+ layers=[{"id": "layer:cli", "name": "CLI", "nodeIds": ["file:src/main.py"]}],
+ tour=[
+ {
+ "order": 1,
+ "title": "main.py",
+ "target_path": "src/main.py",
+ "kind": "code",
+ "reason": "Top of the stack.",
+ "layer_id": "layer:cli",
+ }
+ ],
+ )
+ await persist_generation(result, async_session, repo.id)
+
+ layers = await get_kg_layers(async_session, repo.id)
+ assert [layer.layer_id for layer in layers] == ["layer:cli"]
+ steps = await get_kg_tour_steps(async_session, repo.id)
+ assert steps[0].target_path == "src/main.py"
+ assert steps[0].layer_id == "layer:cli"
+
+
+async def test_missing_kg_result_is_a_noop(async_session, repo):
+ result = SimpleNamespace(generated_pages=None, knowledge_graph_result=None)
+ await persist_generation(result, async_session, repo.id)
+ assert await get_kg_layers(async_session, repo.id) == []
+ assert await get_kg_project_meta(async_session, repo.id) is None
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index 9f08f7b6a..e13db2c55 100644
--- a/tests/unit/persistence/test_models.py
+++ b/tests/unit/persistence/test_models.py
@@ -321,5 +321,7 @@ def test_base_includes_all_models():
"graph_metrics",
"knowledge_graph_layers",
"knowledge_graph_tour_steps",
+ "kg_project_meta",
+ "kg_node_meta",
}
assert expected == table_names
diff --git a/tests/unit/persistence/test_persist_sweep_pages.py b/tests/unit/persistence/test_persist_sweep_pages.py
new file mode 100644
index 000000000..1e55ed752
--- /dev/null
+++ b/tests/unit/persistence/test_persist_sweep_pages.py
@@ -0,0 +1,216 @@
+"""Tests for the stale generated-page sweep.
+
+Module/scc pages key on clustering ordinals and layer pages on display
+names — identities that drift between runs. A full run's output is
+authoritative for those page types: anything it did not reproduce is a
+stranded duplicate from an earlier run and must be swept.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+from types import SimpleNamespace
+
+from sqlalchemy import select
+
+from repowise.core.persistence.models import Page, PageVersion
+from repowise.core.pipeline.persist import _sweep_stale_generated_pages
+from tests.unit.persistence.helpers import insert_repo
+
+
+def _page_row(repo_id: str, page_type: str, target: str) -> Page:
+ now = datetime.now(UTC)
+ return Page(
+ id=f"{page_type}:{target}",
+ repository_id=repo_id,
+ page_type=page_type,
+ title=target,
+ content="body",
+ target_path=target,
+ source_hash="x" * 64,
+ model_name="mock",
+ provider_name="mock",
+ created_at=now,
+ updated_at=now,
+ )
+
+
+def _generated(page_type: str, target: str) -> SimpleNamespace:
+ return SimpleNamespace(page_id=f"{page_type}:{target}", page_type=page_type)
+
+
+async def test_sweep_removes_pages_absent_from_run(async_session):
+ repo = await insert_repo(async_session)
+ # Two module pages from a previous run; the new run reproduces only one
+ # (under a fresh community ordinal) — the other is stale.
+ async_session.add(_page_row(repo.id, "module_page", "community-155"))
+ async_session.add(_page_row(repo.id, "module_page", "community-75"))
+ async_session.add(
+ PageVersion(
+ page_id="module_page:community-155",
+ repository_id=repo.id,
+ version=1,
+ page_type="module_page",
+ title="old",
+ content="old body",
+ source_hash="x" * 64,
+ model_name="mock",
+ provider_name="mock",
+ archived_at=datetime.now(UTC),
+ )
+ )
+ await async_session.flush()
+
+ swept = await _sweep_stale_generated_pages(
+ async_session, repo.id, [_generated("module_page", "community-75")]
+ )
+ await async_session.commit()
+
+ assert swept == ["module_page:community-155"]
+ remaining = (
+ (await async_session.execute(select(Page.id).where(Page.repository_id == repo.id)))
+ .scalars()
+ .all()
+ )
+ assert remaining == ["module_page:community-75"]
+ # Versions of the swept page go with it (FK would block the delete).
+ versions = (
+ (
+ await async_session.execute(
+ select(PageVersion).where(PageVersion.repository_id == repo.id)
+ )
+ )
+ .scalars()
+ .all()
+ )
+ assert versions == []
+
+
+async def test_sweep_skips_types_the_run_did_not_produce(async_session):
+ repo = await insert_repo(async_session)
+ async_session.add(_page_row(repo.id, "module_page", "community-1"))
+ async_session.add(_page_row(repo.id, "layer_page", "layer:Data"))
+ await async_session.flush()
+
+ # The run produced layer pages but no module pages (e.g. the module level
+ # was skipped) — module pages must survive.
+ swept = await _sweep_stale_generated_pages(
+ async_session, repo.id, [_generated("layer_page", "layer:Data")]
+ )
+ await async_session.commit()
+
+ assert swept == []
+ remaining = (
+ (await async_session.execute(select(Page.id).where(Page.repository_id == repo.id)))
+ .scalars()
+ .all()
+ )
+ assert set(remaining) == {"module_page:community-1", "layer_page:layer:Data"}
+
+
+async def test_sweep_never_touches_unswept_page_types(async_session):
+ repo = await insert_repo(async_session)
+ # file_page ids are stable paths — never swept here even when absent
+ # from the run's output.
+ async_session.add(_page_row(repo.id, "file_page", "src/app.py"))
+ async_session.add(_page_row(repo.id, "module_page", "community-9"))
+ await async_session.flush()
+
+ swept = await _sweep_stale_generated_pages(
+ async_session, repo.id, [_generated("module_page", "community-10")]
+ )
+ await async_session.commit()
+
+ assert swept == ["module_page:community-9"]
+ remaining = (
+ (await async_session.execute(select(Page.id).where(Page.repository_id == repo.id)))
+ .scalars()
+ .all()
+ )
+ assert "file_page:src/app.py" in remaining
+
+
+async def test_sweep_noop_on_empty_run(async_session):
+ repo = await insert_repo(async_session)
+ async_session.add(_page_row(repo.id, "module_page", "community-1"))
+ await async_session.flush()
+
+ swept = await _sweep_stale_generated_pages(async_session, repo.id, [])
+ assert swept == []
+ swept = await _sweep_stale_generated_pages(async_session, repo.id, None)
+ assert swept == []
+
+
+async def test_authoritative_type_sweeps_when_zero_produced(async_session):
+ """Regression for the live mini-taskq bug.
+
+ A curated full run derived modules 1:1 with layers (every module
+ ``wholeLayer``-skipped), so it emitted layer pages and ZERO module pages
+ while still being authoritative for ``module_page``. The pre-curated
+ community module page must be swept even though the run produced none.
+ """
+ repo = await insert_repo(async_session)
+ async_session.add(_page_row(repo.id, "module_page", "community-0"))
+ async_session.add(_page_row(repo.id, "layer_page", "layer:Data"))
+ await async_session.flush()
+
+ swept = await _sweep_stale_generated_pages(
+ async_session,
+ repo.id,
+ [_generated("layer_page", "layer:Data")],
+ {"module_page", "layer_page"},
+ )
+ await async_session.commit()
+
+ assert swept == ["module_page:community-0"]
+ remaining = (
+ (await async_session.execute(select(Page.id).where(Page.repository_id == repo.id)))
+ .scalars()
+ .all()
+ )
+ assert set(remaining) == {"layer_page:layer:Data"}
+
+
+async def test_degraded_run_does_not_wipe_layer_pages(async_session):
+ """A community-fallback (degraded) run is authoritative for nothing.
+
+ It produces module pages but no layer authority, so pre-existing curated
+ layer pages it cannot reproduce must survive — degradation honesty.
+ """
+ repo = await insert_repo(async_session)
+ async_session.add(_page_row(repo.id, "layer_page", "layer:Core"))
+ async_session.add(_page_row(repo.id, "module_page", "community-1"))
+ await async_session.flush()
+
+ swept = await _sweep_stale_generated_pages(
+ async_session,
+ repo.id,
+ [_generated("module_page", "community-2")],
+ set(), # degraded: no authority
+ )
+ await async_session.commit()
+
+ # The stale community module page is swept (its type was produced), but the
+ # curated layer page is untouched (not produced, not authoritative). The
+ # produced ``community-2`` page is upserted elsewhere, not by the sweep, so
+ # it is not among the seeded rows here.
+ assert swept == ["module_page:community-1"]
+ remaining = (
+ (await async_session.execute(select(Page.id).where(Page.repository_id == repo.id)))
+ .scalars()
+ .all()
+ )
+ assert set(remaining) == {"layer_page:layer:Core"}
+
+
+async def test_incremental_no_authority_sweeps_nothing(async_session):
+ """Incremental no-KG run: generated_pages None + empty authority → no-op."""
+ repo = await insert_repo(async_session)
+ async_session.add(_page_row(repo.id, "module_page", "community-1"))
+ async_session.add(_page_row(repo.id, "layer_page", "layer:Core"))
+ await async_session.flush()
+
+ swept = await _sweep_stale_generated_pages(async_session, repo.id, None, set())
+ assert swept == []
+ swept = await _sweep_stale_generated_pages(async_session, repo.id, None, None)
+ assert swept == []
diff --git a/tests/unit/persistence/test_vector_store_batching.py b/tests/unit/persistence/test_vector_store_batching.py
index 5a7a8e237..c99caa615 100644
--- a/tests/unit/persistence/test_vector_store_batching.py
+++ b/tests/unit/persistence/test_vector_store_batching.py
@@ -5,7 +5,11 @@ from __future__ import annotations
import pytest
-from repowise.core.persistence.vector_store.lancedb_store import _paths_in_filter
+from repowise.core.persistence.vector_store.in_memory import InMemoryVectorStore
+from repowise.core.persistence.vector_store.lancedb_store import (
+ _page_ids_in_filter,
+ _paths_in_filter,
+)
from repowise.core.persistence.vector_store.pgvector_store import (
PgVectorStore,
_summary_payload,
@@ -66,9 +70,7 @@ async def test_pg_embed_batch_single_executemany() -> None:
session = _FakeSession()
store = PgVectorStore(_factory(session), MockEmbedder())
- await store.embed_batch(
- [("p1", "alpha", {}), ("p2", "beta", {}), ("p3", "gamma", {})]
- )
+ await store.embed_batch([("p1", "alpha", {}), ("p2", "beta", {}), ("p3", "gamma", {})])
assert len(session.executed) == 1 # one statement, list-of-params
stmt, params = session.executed[0]
@@ -153,11 +155,80 @@ async def test_lancedb_batch_summaries_roundtrip(tmp_path) -> None:
]
)
batch = await store.get_page_summaries_by_paths(["a.py", "c.py", "missing.py"])
- singles = {
- p: await store.get_page_summary_by_path(p) for p in ("a.py", "c.py")
- }
+ singles = {p: await store.get_page_summary_by_path(p) for p in ("a.py", "c.py")}
assert set(batch) == {"a.py", "c.py"}
for p in ("a.py", "c.py"):
assert batch[p]["summary"] == singles[p]["summary"]
finally:
await store.close()
+
+
+# ---------------------------------------------------------------------------
+# delete_many — bulk removal of swept page embeddings
+# ---------------------------------------------------------------------------
+
+
+async def test_in_memory_delete_many_removes_only_listed_ids() -> None:
+ store = InMemoryVectorStore(MockEmbedder())
+ await store.embed_batch([("p1", "a", {}), ("p2", "b", {}), ("p3", "c", {})])
+
+ await store.delete_many(["p1", "p3"])
+
+ assert await store.list_page_ids() == {"p2"}
+
+
+async def test_in_memory_delete_many_empty_is_noop() -> None:
+ store = InMemoryVectorStore(MockEmbedder())
+ await store.embed_batch([("p1", "a", {})])
+ await store.delete_many([])
+ assert await store.list_page_ids() == {"p1"}
+
+
+async def test_pg_delete_many_single_update_with_in_params() -> None:
+ session = _FakeSession()
+ store = PgVectorStore(_factory(session), MockEmbedder())
+
+ await store.delete_many(["p1", "p2", "p3"])
+
+ assert len(session.executed) == 1
+ stmt, params = session.executed[0]
+ assert "UPDATE wiki_pages SET embedding = NULL" in stmt
+ assert "id IN" in stmt
+ assert params == {"ids": ["p1", "p2", "p3"]}
+ assert session.commits == 1
+
+
+async def test_pg_delete_many_empty_is_noop() -> None:
+ session = _FakeSession()
+ store = PgVectorStore(_factory(session), MockEmbedder())
+ await store.delete_many([])
+ assert session.executed == []
+ assert session.commits == 0
+
+
+def test_lancedb_page_ids_filter_escapes_quotes() -> None:
+ flt = _page_ids_in_filter(["module_page:c-1", "weird'id"])
+ assert flt == "page_id IN ('module_page:c-1', 'weird''id')"
+
+
+async def test_lancedb_delete_many_roundtrip(tmp_path) -> None:
+ pytest.importorskip("lancedb")
+ from repowise.core.persistence.vector_store import LanceDBVectorStore
+
+ store = LanceDBVectorStore(str(tmp_path / "lance"), MockEmbedder())
+ try:
+ await store.embed_batch(
+ [
+ ("p1", "module a", {"target_path": "a.py"}),
+ ("p2", "module b", {"target_path": "b.py"}),
+ ("p3", "module c", {"target_path": "c.py"}),
+ ]
+ )
+ await store.delete_many(["p1", "p3"])
+ assert await store.list_page_ids() == {"p2"}
+ # empty list is a no-op
+ await store.delete_many([])
+ assert await store.list_page_ids() == {"p2"}
+ finally:
+ await store.close()
diff --git a/tests/unit/server/services/test_c4_curation.py b/tests/unit/server/services/test_c4_curation.py
new file mode 100644
index 000000000..e8c93a28f
--- /dev/null
+++ b/tests/unit/server/services/test_c4_curation.py
@@ -0,0 +1,404 @@
+"""C4 legibility: curated KG layers feed the architecture view, and the L1/L2
+Mermaid groups externals by category once there are many (plan §Phase 5).
+
+Also pins the Phase-A data contract of the viewer plan: every curated field
+(sub-groups, layer-aware tour, entry points, node summaries/tags/types)
+survives JSON → DB → builder with zero loss, and uncurated repos behave
+exactly as before."""
+
+from __future__ import annotations
+
+import json
+import os
+from types import SimpleNamespace
+
+import pytest
+
+from repowise.core.persistence import (
+ batch_upsert_graph_nodes,
+ upsert_repository,
+)
+from repowise.server.services.c4_builder.architecture import (
+ _layers_from_db,
+ _layers_from_knowledge_graph,
+ _migrate_kg_file_to_db,
+ _tour_from_knowledge_graph,
+ build_architecture_view,
+)
+from repowise.server.services.c4_builder.mermaid import to_mermaid_l1
+from repowise.server.services.c4_builder.models import (
+ C4L1,
+ ExternalSystemView,
+ Person,
+ Relation,
+ System,
+)
+
+# ---------------------------------------------------------------------------
+# Curated layers flow through the architecture cascade (tier 2: KG file)
+# ---------------------------------------------------------------------------
+
+
+def test_architecture_view_consumes_curated_layers():
+ kg = {
+ "layers": [
+ {
+ "id": "layer:ui",
+ "name": "UI",
+ "description": "front end",
+ "nodeIds": ["file:src/ui/a.tsx", "file:src/ui/b.tsx"],
+ },
+ {
+ "id": "layer:service",
+ "name": "Service",
+ "description": "core",
+ "nodeIds": ["file:src/core/x.py"],
+ },
+ ]
+ }
+ node_ids = {"src/ui/a.tsx", "src/ui/b.tsx", "src/core/x.py"}
+ layers = _layers_from_knowledge_graph(kg, node_ids)
+
+ # Curated names/ids/order preserved — not community-N / cluster-N.
+ assert [layer["name"] for layer in layers] == ["UI", "Service"]
+ assert [layer["id"] for layer in layers] == ["layer:ui", "layer:service"]
+ assert layers[0]["node_ids"] == ["src/ui/a.tsx", "src/ui/b.tsx"]
+
+
+def test_layers_carry_sub_groups_and_display_order():
+ kg = {
+ "layers": [
+ {
+ "id": "layer:ui",
+ "name": "UI",
+ "nodeIds": ["file:src/ui/a.tsx", "file:src/ui/b.tsx"],
+ "display_order": 3,
+ "subGroups": [
+ {"id": "layer:ui:forms", "name": "forms", "nodeIds": ["file:src/ui/a.tsx"]},
+ {"id": "layer:ui:gone", "name": "gone", "nodeIds": ["file:src/ui/zz.tsx"]},
+ ],
+ },
+ ]
+ }
+ layers = _layers_from_knowledge_graph(kg, {"src/ui/a.tsx", "src/ui/b.tsx"})
+
+ assert layers[0]["display_order"] == 3
+ # Sub-group node ids are prefix-stripped; groups with no surviving nodes drop.
+ assert layers[0]["sub_groups"] == [
+ {"id": "layer:ui:forms", "name": "forms", "node_ids": ["src/ui/a.tsx"]},
+ ]
+
+
+def test_layers_from_db_tolerate_pre_migration_rows():
+ """Rows from a DB created before migration 0030 lack the new columns."""
+ row = SimpleNamespace(
+ layer_id="layer:ui",
+ name="UI",
+ description="",
+ node_ids_json=json.dumps(["file:src/ui/a.tsx"]),
+ )
+ layers = _layers_from_db([row], {"src/ui/a.tsx"})
+ assert layers[0]["sub_groups"] == []
+ assert layers[0]["display_order"] == 0
+
+
+def test_tour_steps_carry_curated_fields():
+ kg = {
+ "tour": [
+ {
+ "order": 1,
+ "title": "main.py",
+ "target_path": "src/main.py",
+ "page_type": "file_page",
+ "depth": 0,
+ "kind": "code",
+ "reason": "Top of the stack.",
+ "layer_id": "layer:cli",
+ },
+ # Legacy LLM step: nodeIds, no curated fields.
+ {"order": 2, "title": "Core", "description": "d", "nodeIds": ["file:core.py"]},
+ ]
+ }
+ steps = _tour_from_knowledge_graph(kg)
+
+ curated = steps[0]
+ assert curated.target_path == "src/main.py"
+ assert curated.layer_id == "layer:cli"
+ assert curated.reason == "Top of the stack."
+ assert curated.depth == 0
+ assert curated.kind == "code"
+ assert curated.page_type == "file_page"
+ # Curated steps address one file: node_ids falls back to the target path.
+ assert curated.node_ids == ["src/main.py"]
+
+ legacy = steps[1]
+ assert legacy.node_ids == ["core.py"]
+ assert legacy.target_path is None
+ assert legacy.kind == ""
+
+
+# ---------------------------------------------------------------------------
+# Round trip: curated JSON → auto-migrate → DB → architecture view (zero loss)
+# ---------------------------------------------------------------------------
+
+_CURATED_KG = {
+ "version": "1.0.0",
+ "project": {
+ "name": "demo",
+ "entry_points": ["src/main.py"],
+ "entry_candidates": ["src/main.py", "src/api/routes.py", "missing/file.py"],
+ },
+ "nodes": [
+ {
+ "id": "file:src/main.py",
+ "filePath": "src/main.py",
+ "type": "file",
+ "summary": "SENTINEL: CLI entry point wiring commands.",
+ "tags": ["entry_point", "python"],
+ },
+ {
+ "id": "file:src/api/routes.py",
+ "filePath": "src/api/routes.py",
+ "type": "file",
+ "summary": "SENTINEL: HTTP routes.",
+ "tags": ["python"],
+ },
+ {
+ "id": "file:src/ui/form.tsx",
+ "filePath": "src/ui/form.tsx",
+ "type": "file",
+ "summary": "SENTINEL: form component.",
+ "tags": ["typescript"],
+ },
+ {
+ "id": "file:Dockerfile",
+ "filePath": "Dockerfile",
+ "type": "service",
+ "summary": "SENTINEL: container build.",
+ "tags": ["infra"],
+ },
+ {"id": "concept:auth", "type": "concept", "summary": "not file meta"},
+ ],
+ "edges": [],
+ "layers": [
+ {
+ "id": "layer:ui",
+ "name": "UI",
+ "description": "Presentation",
+ "nodeIds": ["file:src/ui/form.tsx"],
+ "display_order": 0,
+ "subGroups": [
+ {"id": "layer:ui:forms", "name": "forms", "nodeIds": ["file:src/ui/form.tsx"]},
+ ],
+ },
+ {
+ "id": "layer:api",
+ "name": "API",
+ "description": "Routes",
+ "nodeIds": ["file:src/api/routes.py", "file:src/main.py"],
+ "display_order": 1,
+ },
+ {
+ "id": "layer:config",
+ "name": "Config",
+ "description": "Infra",
+ "nodeIds": ["file:Dockerfile"],
+ "display_order": 2,
+ },
+ ],
+ "tour": [
+ {
+ "order": 1,
+ "title": "main.py",
+ "target_path": "src/main.py",
+ "page_type": "file_page",
+ "depth": 0,
+ "kind": "code",
+ "reason": "SENTINEL: start of the control flow.",
+ "layer_id": "layer:api",
+ },
+ ],
+}
+
+
+async def _seed_curated_repo(session, tmp_path):
+ kg_dir = tmp_path / ".repowise"
+ kg_dir.mkdir()
+ (kg_dir / "knowledge-graph.json").write_text(json.dumps(_CURATED_KG))
+
+ repo = await upsert_repository(session, name="demo", local_path=str(tmp_path))
+ files = ["src/main.py", "src/api/routes.py", "src/ui/form.tsx", "Dockerfile"]
+ await batch_upsert_graph_nodes(
+ session,
+ repo.id,
+ [
+ {
+ "node_id": f,
+ "node_type": "file",
+ "language": "python" if f.endswith(".py") else "",
+ "symbol_count": 1,
+ }
+ for f in files
+ ],
+ )
+ return repo
+
+
+def _assert_curated_view(view) -> None:
+ by_id = {layer.id: layer for layer in view.layers}
+ ui = by_id["layer:ui"]
+ assert ui.display_order == 0
+ assert [(sg.id, sg.name, sg.node_ids) for sg in ui.sub_groups] == [
+ ("layer:ui:forms", "forms", ["src/ui/form.tsx"]),
+ ]
+ assert by_id["layer:api"].display_order == 1
+ assert by_id["layer:api"].sub_groups == []
+
+ step = view.tour[0]
+ assert step.target_path == "src/main.py"
+ assert step.layer_id == "layer:api"
+ assert step.reason == "SENTINEL: start of the control flow."
+ assert step.depth == 0
+ assert step.kind == "code"
+ assert step.page_type == "file_page"
+ assert step.node_ids == ["src/main.py"]
+
+ assert view.entry_points == ["src/main.py"]
+ # Candidates are filtered to nodes that exist in the graph.
+ assert view.entry_candidates == ["src/main.py", "src/api/routes.py"]
+
+ nodes = {n.id: n for n in view.nodes}
+ assert nodes["src/main.py"].summary == "SENTINEL: CLI entry point wiring commands."
+ assert nodes["src/main.py"].tags == ["entry_point", "python"]
+ assert nodes["Dockerfile"].node_type == "service"
+ assert nodes["Dockerfile"].summary == "SENTINEL: container build."
+
+
+async def test_round_trip_zero_curated_field_loss(async_session, tmp_path):
+ """First read auto-migrates the file; second read serves from the DB.
+
+ Both views must carry every curated field — the Phase-A acceptance."""
+ repo = await _seed_curated_repo(async_session, tmp_path)
+
+ view_from_file = await build_architecture_view(async_session, repo.id)
+ _assert_curated_view(view_from_file)
+
+ # Remove the workspace file: the second read must come purely from the DB.
+ os.remove(tmp_path / ".repowise" / "knowledge-graph.json")
+ view_from_db = await build_architecture_view(async_session, repo.id)
+ _assert_curated_view(view_from_db)
+
+
+async def test_migration_twice_is_idempotent(async_session, tmp_path):
+ """Two first-readers racing into the migration must be idempotent.
+
+ The delete-then-insert migration carries no concurrency guard, so a
+ concurrent first-reader can hit the unique constraints. Running it twice in
+ a row (the serialized analogue of that race) must raise nothing and leave
+ the DB holding exactly one curated set."""
+ repo = await _seed_curated_repo(async_session, tmp_path)
+
+ # Both calls open their own sessions and commit; neither raises.
+ await _migrate_kg_file_to_db(async_session, repo.id, _CURATED_KG)
+ await _migrate_kg_file_to_db(async_session, repo.id, _CURATED_KG)
+
+ # The view (served from the migrated DB rows) carries every curated field.
+ os.remove(tmp_path / ".repowise" / "knowledge-graph.json")
+ view = await build_architecture_view(async_session, repo.id)
+ _assert_curated_view(view)
+
+
+async def test_failed_migration_does_not_roll_back_caller_writes(async_session, tmp_path):
+ """A failed migration runs in its own session, so the caller's pending
+ writes survive — the old broad ``except: session.rollback()`` would have
+ discarded them."""
+ repo = await _seed_curated_repo(async_session, tmp_path)
+
+ # An unrelated write pending on the CALLER's session.
+ sentinel = await upsert_repository(
+ session=async_session, name="caller-sentinel", local_path=str(tmp_path / "x")
+ )
+
+ # A KG whose layer is missing the required "id" key makes upsert_kg_layers
+ # raise inside the migration's own session.
+ broken_kg = {"layers": [{"name": "no id key"}]}
+ with pytest.raises(KeyError):
+ await _migrate_kg_file_to_db(async_session, repo.id, broken_kg)
+
+ # The caller's session was never touched by the migration's rollback.
+ await async_session.flush()
+ found = await async_session.get(type(sentinel), sentinel.id)
+ assert found is not None
+ assert found.name == "caller-sentinel"
+
+
+async def test_uncurated_repo_unchanged(async_session, tmp_path):
+ """Flag-off contract: no KG file, no DB rows → behaviour identical to today."""
+ repo = await upsert_repository(session=async_session, name="plain", local_path=str(tmp_path))
+ await batch_upsert_graph_nodes(
+ async_session,
+ repo.id,
+ [{"node_id": "src/a.py", "node_type": "file", "language": "python", "symbol_count": 1}],
+ )
+
+ view = await build_architecture_view(async_session, repo.id)
+
+ assert view.entry_points == []
+ assert view.entry_candidates == []
+ assert all(layer.sub_groups == [] for layer in view.layers)
+ node = view.nodes[0]
+ assert node.summary == "Handles src logic" # heuristic fallback intact
+ assert node.node_type == "file"
+
+
+def _ext(name: str, category: str) -> ExternalSystemView:
+ return ExternalSystemView(
+ id=f"ext:{name}",
+ name=name,
+ display_name=name,
+ category=category,
+ ecosystem="pypi",
+ version="",
+ )
+
+
+def _l1(externals: list[ExternalSystemView]) -> C4L1:
+ system = System(id="sys:r", name="r")
+ return C4L1(
+ system=system,
+ people=[Person(id="person:user", name="User", description="")],
+ external_systems=externals,
+ relations=[
+ Relation(source_id=system.id, target_id=e.id, label=e.category) for e in externals
+ ],
+ )
+
+
+# ---------------------------------------------------------------------------
+# Mermaid external grouping
+# ---------------------------------------------------------------------------
+
+
+def test_few_externals_stay_flat():
+ externals = [_ext(f"lib{i}", "library") for i in range(4)]
+ out = to_mermaid_l1(_l1(externals))
+ assert "Boundary(extgrp_" not in out
+
+
+def test_many_externals_group_by_category():
+ externals = (
+ [_ext(f"fw{i}", "framework") for i in range(4)]
+ + [_ext(f"svc{i}", "service") for i in range(3)]
+ + [_ext(f"lib{i}", "library") for i in range(5)]
+ )
+ out = to_mermaid_l1(_l1(externals))
+ assert "Boundary(extgrp_framework" in out
+ assert "Boundary(extgrp_service" in out
+ assert "Boundary(extgrp_library" in out
+ assert '"Frameworks"' in out
+ assert '"Services & Infrastructure"' in out
+ # Frameworks group is rendered before Libraries (category priority order).
+ assert out.index("extgrp_framework") < out.index("extgrp_library")
+ # Every external still appears as a box.
+ for i in range(5):
+ assert f"ext_lib{i}" in out
diff --git a/tests/unit/server/test_architecture_api.py b/tests/unit/server/test_architecture_api.py
index e0ce6fc5d..e235d4909 100644
--- a/tests/unit/server/test_architecture_api.py
+++ b/tests/unit/server/test_architecture_api.py
@@ -10,6 +10,10 @@ from repowise.core.persistence import (
batch_upsert_graph_nodes,
bulk_upsert_external_systems,
link_graph_nodes_to_external_systems,
+ upsert_kg_layers,
+ upsert_kg_node_meta,
+ upsert_kg_project_meta,
+ upsert_kg_tour_steps,
)
@@ -82,6 +86,93 @@ async def test_api_architecture_endpoint(client: AsyncClient, app) -> None:
assert edge["confidence"] > 0
+async def test_api_architecture_curated_fields(client: AsyncClient, app) -> None:
+ """Curated KG fields (sub_groups, tour, entry points, node meta) reach the
+ HTTP response — the Phase-A acceptance, DB-served path."""
+ repo_id = await _seed(client, app)
+
+ async with app.state.session_factory() as session:
+ await upsert_kg_layers(session, repo_id, [
+ {
+ "id": "layer:api",
+ "name": "API",
+ "description": "Service edge",
+ "nodeIds": ["file:src/app.py", "file:src/db.py"],
+ "display_order": 0,
+ "subGroups": [
+ {"id": "layer:api:app", "name": "app", "nodeIds": ["file:src/app.py"]},
+ {"id": "layer:api:db", "name": "db", "nodeIds": ["file:src/db.py"]},
+ ],
+ },
+ ])
+ await upsert_kg_tour_steps(session, repo_id, [
+ {
+ "order": 1,
+ "title": "app.py",
+ "target_path": "src/app.py",
+ "page_type": "file_page",
+ "depth": 0,
+ "kind": "code",
+ "reason": "Top of the stack.",
+ "layer_id": "layer:api",
+ },
+ ])
+ await upsert_kg_project_meta(
+ session, repo_id,
+ entry_points=["src/app.py"],
+ entry_candidates=["src/app.py", "src/db.py"],
+ )
+ await upsert_kg_node_meta(session, repo_id, [
+ {"id": "src/app.py", "type": "file",
+ "summary": "Curated app summary.", "tags": ["entry_point", "python"]},
+ ])
+ await session.commit()
+
+ resp = await client.get(f"/api/graph/{repo_id}/architecture-view")
+ assert resp.status_code == 200
+ body = resp.json()
+
+ layer = next(la for la in body["layers"] if la["id"] == "layer:api")
+ assert layer["display_order"] == 0
+ assert layer["sub_groups"] == [
+ {"id": "layer:api:app", "name": "app", "node_ids": ["src/app.py"]},
+ {"id": "layer:api:db", "name": "db", "node_ids": ["src/db.py"]},
+ ]
+
+ step = body["tour"][0]
+ assert step["target_path"] == "src/app.py"
+ assert step["layer_id"] == "layer:api"
+ assert step["reason"] == "Top of the stack."
+ assert step["depth"] == 0
+ assert step["kind"] == "code"
+ assert step["page_type"] == "file_page"
+ assert step["node_ids"] == ["src/app.py"]
+
+ assert body["entry_points"] == ["src/app.py"]
+ assert body["entry_candidates"] == ["src/app.py", "src/db.py"]
+
+ app_node = next(n for n in body["nodes"] if n["id"] == "src/app.py")
+ assert app_node["summary"] == "Curated app summary."
+ assert app_node["tags"] == ["entry_point", "python"]
+
+
+async def test_api_architecture_uncurated_defaults(client: AsyncClient, app) -> None:
+ """Flag-off contract: uncurated repos serve the new keys as safe defaults."""
+ repo_id = await _seed(client, app)
+
+ resp = await client.get(f"/api/graph/{repo_id}/architecture-view")
+ assert resp.status_code == 200
+ body = resp.json()
+
+ assert body["entry_points"] == []
+ assert body["entry_candidates"] == []
+ for layer in body["layers"]:
+ assert layer["sub_groups"] == []
+ for step in body["tour"]:
+ assert step["target_path"] is None
+ assert step["kind"] == ""
+
+
async def test_api_architecture_with_symbols(client: AsyncClient, app) -> None:
repo_id = await _seed(client, app)
diff --git a/tests/unit/server/test_graph.py b/tests/unit/server/test_graph.py
index 77a94e88f..508b946da 100644
--- a/tests/unit/server/test_graph.py
+++ b/tests/unit/server/test_graph.py
@@ -227,6 +227,206 @@ async def test_architecture_graph(client: AsyncClient, app) -> None:
assert data["edges"] == []
+# ---------------------------------------------------------------------------
+# Community slice (Phase G4 — constellation blossom)
+# ---------------------------------------------------------------------------
+
+
+async def _populate_two_communities(session_factory, repo_id: str) -> None:
+ """Two members in community 0, one in community 1, with a cross edge."""
+ async with get_session(session_factory) as session:
+ await crud.batch_upsert_graph_nodes(
+ session,
+ repo_id,
+ [
+ {
+ "node_id": "src/a.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 3,
+ "pagerank": 0.8,
+ "betweenness": 0.5,
+ "community_id": 0,
+ },
+ {
+ "node_id": "src/b.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 2,
+ "pagerank": 0.4,
+ "betweenness": 0.1,
+ "community_id": 0,
+ },
+ {
+ "node_id": "src/c.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 1,
+ "pagerank": 0.2,
+ "betweenness": 0.0,
+ "community_id": 1,
+ },
+ ],
+ )
+ await crud.batch_upsert_graph_edges(
+ session,
+ repo_id,
+ [
+ # Intra-community (0)
+ {"source_node_id": "src/a.py", "target_node_id": "src/b.py"},
+ # Cross-community (0 -> 1): pulls c.py in as a boundary stub
+ {"source_node_id": "src/b.py", "target_node_id": "src/c.py"},
+ ],
+ )
+
+
+async def test_community_slice_members_edges_and_boundary(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _populate_two_communities(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/graph/{repo['id']}/communities/0/slice")
+ assert resp.status_code == 200
+ data = resp.json()
+
+ assert data["community_id"] == 0
+ assert data["member_count"] == 2
+ assert data["truncated"] is False
+
+ by_id = {n["node_id"]: n for n in data["nodes"]}
+ # Both members present and NOT boundary
+ assert by_id["src/a.py"]["is_boundary"] is False
+ assert by_id["src/b.py"]["is_boundary"] is False
+ # Neighbor from community 1 pulled in as a boundary stub
+ assert by_id["src/c.py"]["is_boundary"] is True
+
+ # Edges: intra (a->b) + cross (b->c) both render
+ pairs = {(link["source"], link["target"]) for link in data["links"]}
+ assert ("src/a.py", "src/b.py") in pairs
+ assert ("src/b.py", "src/c.py") in pairs
+
+
+async def test_community_slice_member_signals(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _populate_two_communities(app.state.session_factory, repo["id"])
+ async with get_session(app.state.session_factory) as session:
+ await crud.upsert_git_metadata(
+ session,
+ repository_id=repo["id"],
+ file_path="src/a.py",
+ is_hotspot=True,
+ churn_percentile=0.99,
+ primary_owner_name="Bob",
+ commit_count_30d=5,
+ commit_count_90d=12,
+ )
+
+ resp = await client.get(f"/api/graph/{repo['id']}/communities/0/slice")
+ assert resp.status_code == 200
+ by_id = {n["node_id"]: n for n in resp.json()["nodes"]}
+ assert by_id["src/a.py"]["is_hotspot"] is True
+ assert by_id["src/a.py"]["primary_owner"] == "Bob"
+ # Boundary stub carries no signals
+ assert by_id["src/c.py"]["is_hotspot"] is False
+
+
+async def test_community_slice_excludes_non_member_edges(client: AsyncClient, app) -> None:
+ """The SQL membership filter must drop edges that touch no member.
+
+ Seeds an extra node ``src/d.py`` in community 1 and an edge c->d that
+ touches neither community-0 member. That edge must not appear in the slice,
+ and the slice result must otherwise match the baseline expectations.
+ """
+ repo = await create_test_repo(client)
+ async with get_session(app.state.session_factory) as session:
+ await crud.batch_upsert_graph_nodes(
+ session,
+ repo["id"],
+ [
+ {
+ "node_id": "src/a.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 3,
+ "pagerank": 0.8,
+ "community_id": 0,
+ },
+ {
+ "node_id": "src/b.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 2,
+ "pagerank": 0.4,
+ "community_id": 0,
+ },
+ {
+ "node_id": "src/c.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 1,
+ "pagerank": 0.2,
+ "community_id": 1,
+ },
+ {
+ "node_id": "src/d.py",
+ "node_type": "file",
+ "language": "python",
+ "symbol_count": 1,
+ "pagerank": 0.1,
+ "community_id": 1,
+ },
+ ],
+ )
+ await crud.batch_upsert_graph_edges(
+ session,
+ repo["id"],
+ [
+ # Intra-community 0 (touches members)
+ {"source_node_id": "src/a.py", "target_node_id": "src/b.py"},
+ # Cross 0->1 (touches a member -> boundary stub c.py)
+ {"source_node_id": "src/b.py", "target_node_id": "src/c.py"},
+ # Touches NO community-0 member: must be excluded entirely
+ {"source_node_id": "src/c.py", "target_node_id": "src/d.py"},
+ ],
+ )
+
+ resp = await client.get(f"/api/graph/{repo['id']}/communities/0/slice")
+ assert resp.status_code == 200
+ data = resp.json()
+
+ assert data["community_id"] == 0
+ assert data["member_count"] == 2
+ assert data["truncated"] is False
+
+ by_id = {n["node_id"]: n for n in data["nodes"]}
+ assert by_id["src/a.py"]["is_boundary"] is False
+ assert by_id["src/b.py"]["is_boundary"] is False
+ assert by_id["src/c.py"]["is_boundary"] is True
+ # d.py is only reachable via the excluded edge — it must not be pulled in.
+ assert "src/d.py" not in by_id
+
+ pairs = {(link["source"], link["target"]) for link in data["links"]}
+ assert ("src/a.py", "src/b.py") in pairs
+ assert ("src/b.py", "src/c.py") in pairs
+ # The non-member-touching edge is excluded.
+ assert ("src/c.py", "src/d.py") not in pairs
+
+
+async def test_community_slice_empty_community(client: AsyncClient, app) -> None:
+ repo = await create_test_repo(client)
+ await _populate_two_communities(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/graph/{repo['id']}/communities/999/slice")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["nodes"] == []
+ assert data["links"] == []
+ assert data["member_count"] == 0
+
+
@pytest.mark.asyncio
async def test_module_graph_aggregates_signals(client: AsyncClient, app) -> None:
repo = await create_test_repo(client)
diff --git a/tests/unit/server/test_job_executor.py b/tests/unit/server/test_job_executor.py
index 6e17479aa..f966db62f 100644
--- a/tests/unit/server/test_job_executor.py
+++ b/tests/unit/server/test_job_executor.py
@@ -8,13 +8,18 @@ are not re-indexed.
from __future__ import annotations
+from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, patch
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from repowise.core.persistence.crud import upsert_generation_job, upsert_repository
-from repowise.server.job_executor import _repo_exclude_patterns, execute_job
+from repowise.server.job_executor import (
+ _incremental_page_regen,
+ _repo_exclude_patterns,
+ execute_job,
+)
def _fake_result() -> SimpleNamespace:
@@ -154,3 +159,68 @@ async def test_execute_job_merges_config_yaml_excludes(session_factory, tmp_path
run_pipeline_mock.assert_awaited_once()
assert run_pipeline_mock.await_args.kwargs["exclude_patterns"] == ["tools/"]
+
+
+async def test_incremental_page_regen_passes_repo_path(tmp_path):
+ """Incremental regen must forward repo_path to generate_all.
+
+ Without it, generate_all can't load the curated knowledge-graph.json
+ artifact and silently falls back to community module grouping, which
+ overwrites curated module pages with the wrong ids.
+ """
+ repo_path = tmp_path
+ repowise_dir = repo_path / ".repowise"
+ repowise_dir.mkdir()
+ (repowise_dir / "state.json").write_text(
+ '{"last_sync_commit": "base-sha"}', encoding="utf-8"
+ )
+
+ result = SimpleNamespace(
+ file_count=10,
+ parsed_files=[],
+ source_map={},
+ graph_builder=SimpleNamespace(graph=lambda: object()),
+ repo_structure=object(),
+ repo_name="test-repo",
+ git_meta_map={},
+ )
+
+ # Stub git HEAD lookup to a sha != base so regen proceeds.
+ head_proc = SimpleNamespace(returncode=0, stdout="head-sha\n")
+
+ # Detector reports one changed/affected file so generation runs.
+ detector = MagicMock()
+ detector.get_changed_files.return_value = [object()]
+ affected = SimpleNamespace(regenerate=["foo.py"])
+ detector.get_affected_pages.return_value = affected
+
+ generator = MagicMock()
+ generator.generate_all = AsyncMock(return_value=[])
+
+ with (
+ patch("subprocess.run", return_value=head_proc),
+ patch(
+ "repowise.core.ingestion.ChangeDetector",
+ return_value=detector,
+ ),
+ patch(
+ "repowise.core.ingestion.change_detector.compute_adaptive_budget",
+ return_value=5,
+ ),
+ patch("repowise.core.generation.PageGenerator", return_value=generator),
+ patch("repowise.core.generation.ContextAssembler"),
+ patch("repowise.core.generation.GenerationConfig"),
+ patch("repowise.core.reasoning.resolve_reasoning", return_value="low"),
+ patch("repowise.core.repo_config.load_repo_config", return_value={}),
+ ):
+ await _incremental_page_regen(
+ Path(repo_path),
+ result,
+ llm_client=object(),
+ job_config={},
+ progress=None,
+ )
+
+ generator.generate_all.assert_awaited_once()
+ assert generator.generate_all.await_args.kwargs["repo_path"] == Path(repo_path)
diff --git a/tests/unit/server/test_modules_health.py b/tests/unit/server/test_modules_health.py
index 206b6926c..18e226b7c 100644
--- a/tests/unit/server/test_modules_health.py
+++ b/tests/unit/server/test_modules_health.py
@@ -74,3 +74,23 @@ async def test_get_module_health_detail(client: AsyncClient, app) -> None:
assert data["module_path"] == "src"
assert data["file_count"] == 2
assert any(o["name"] == "Alice" for o in data["owners"])
+
+
+async def test_get_module_health_nested_path_falls_back_to_parent(
+ client: AsyncClient, app
+) -> None:
+ """Path-shaped wiki module ids (``src/api``) roll up to the parent module.
+
+ Curated module pages key on the module's directory path; health rollups
+ aggregate by top-level dir, so a nested module path resolves through the
+ exact → single-file → parent fallback chain to its top-level aggregate.
+ """
+ repo = await create_test_repo(client)
+ await _seed(app.state.session_factory, repo["id"])
+
+ resp = await client.get(f"/api/repos/{repo['id']}/modules/health/{quote('src/api')}")
+ assert resp.status_code == 200
+ data = resp.json()
+ assert data["module_path"] == "src"
+ assert data["file_count"] == 2