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.

release: v0.4.0 — language-support upgrades across all Good-tier languages (#106)

Raghav Chamadiya05c0be938e5e
diff --git a/.gitignore b/.gitignore
index f814a6aaf..660a90fb6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -122,3 +122,6 @@ docs/COMPETITIVE_ANALYSIS.md
docs/GRAPH_INTELLIGENCE_UPGRADE.md
docs/LOCAL_DEV.md
docs/multi-repo/
+
+# Local-only language work tracker (not for git)
+docs/LANGUAGE_REMAINING_WORK.md
diff --git a/README.md b/README.md
index a206d36d6..c90a4857a 100644
--- a/README.md
+++ b/README.md
@@ -549,8 +549,8 @@ repowise reindex # rebuild vector store (no LLM calls)
| Tier | Languages | What works |
|------|-----------|------------|
-| **Full** | Python · TypeScript · JavaScript · Java · Go · Rust · C++ · C# | AST parsing, import resolution, named bindings, call resolution, heritage extraction, docstrings; .csproj/.sln-aware multi-project resolver and ASP.NET framework edges for C# |
-| **Good** | C · Kotlin · Ruby · Swift · Scala · PHP | AST parsing, import resolution, named bindings, call resolution, heritage (mixins, derive, extensions, traits), docstrings, dedicated resolvers |
+| **Full** | Python · TypeScript · JavaScript · Java · Go · Rust · C++ · C# | AST parsing, import resolution, named bindings, call resolution, heritage extraction, docstrings; multi-project workspace resolvers (`.csproj`/`.sln` for C#, `Cargo.toml [workspace]` for Rust, `go.mod` multi-module, `package.json` workspaces, etc.); framework-aware edges (Django, FastAPI, Flask, ASP.NET, Spring Boot, Express/NestJS, Gin/Echo/Chi, Axum/Actix); per-language dynamic-hint extractors for runtime-resolved DI / reflection / plugins |
+| **Good** | C · Kotlin · Ruby · Swift · Scala · PHP | AST parsing, import resolution, named bindings, call resolution, heritage (mixins, derive, extensions, traits), docstrings, dedicated workspace-aware resolvers (Gradle subprojects, Rails / Zeitwerk, SPM, SBT/Mill, composer PSR-4); Rails / Laravel framework edges for Ruby and PHP; per-language dynamic-hint extractors |
| **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · SQL · Terraform | Included in the file tree; special handlers extract endpoints/targets where applicable |
14 languages with full AST support, 8 of them at the Full tier. Adding a new language requires one `.scm` tree-sitter query file and one config entry. No changes to the parser core. See [Language Support](docs/LANGUAGE_SUPPORT.md) for details.
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 770f05fc7..6d140e6a5 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
---
-## [0.3.2] — Unreleased
+## [0.4.0] — Unreleased
### Added
@@ -26,8 +26,64 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Dead-code dynamic markers for C#** — `_DYNAMIC_IMPORT_MARKERS` learns reflection / DI / MEF / `InternalsVisibleTo` patterns so the dead-code analyser doesn't flag types only loaded by the framework at runtime.
- **Multi-project test fixtures** — `tests/fixtures/dotnet_solution/` (Api / Domain / Infrastructure with EF Core, controllers, minimal API, GlobalUsings) and `tests/fixtures/dotnet_workspace/` (3 repos demonstrating cross-repo `<ProjectReference>` + internal-NuGet patterns), with end-to-end coverage in `tests/integration/test_dotnet_solution.py`.
+#### Dead-code accuracy
+- **Dynamic-edge consumption in dead-code analysis** — graph edges of type `dynamic` / `dynamic_*` (emitted by every dynamic-hint extractor) now suppress dead-code findings automatically. `find_dynamic_edge_files()` enumerates files involved in those edges and unions the result with the existing source-text `_DYNAMIC_IMPORT_MARKERS` scan. Sub-types (`dynamic_uses`, `dynamic_imports`) are preserved on the graph edge instead of being squashed.
+- **Per-language dynamic-import markers** — `_DYNAMIC_IMPORT_MARKERS` extends to Go (`reflect.TypeOf`/`reflect.ValueOf`), Ruby (`Object.send`, `Kernel.const_get`, `.public_send`), PHP (`call_user_func*`, `new $class`, `ReflectionClass`), Kotlin (`KClass.createInstance`, `::class.java`), Swift (`NSClassFromString`, `Selector`, `#selector`, `NSStringFromClass`), and Scala (`Class.forName`, `runtimeMirror`, `reflect.runtime`).
+- **`detect_unused_internals` enabled by default** — private-symbol findings now surface in the standard dead-code report at confidence 0.65 with `safe_to_delete=False`. CLI defaults stay explicit-False so `repowise dead-code` is unchanged unless `--include-internals` is passed.
+
+#### Workspace-aware resolvers across the Good tier
+- **PHP composer PSR-4** — `resolvers/php_composer.py` reads `autoload.psr-4` and `autoload-dev.psr-4` from `composer.json`, builds a longest-prefix-wins namespace → directory map, and is consulted before stem fallback. Real Laravel/Symfony apps with `"App\\": "src/"` style maps now resolve.
+- **Go multi-module monorepos** — `resolve_go_import` walks every `go.mod` in the repo (skipping `vendor`/`node_modules`), records `(module_dir, module_path)` tuples on the resolver context, and matches imports by longest module prefix. Single-module back-compat preserved.
+- **TypeScript SFC + workspace package resolution** — `.vue`, `.svelte`, and `.astro` extensions probed only when the repo actually contains SFC files. npm/yarn/pnpm `workspaces` (array or object form, with glob expansion) are parsed from root `package.json` so `@scope/pkg` and `@scope/pkg/sub/path` resolve to the sibling workspace dir before falling back to `external:`.
+- **Kotlin Gradle subprojects** — `resolvers/kotlin_gradle.py` parses `settings.gradle(.kts)` `include(...)` declarations plus per-module `srcDirs(...)` overrides (defaults `src/main/kotlin`, `src/main/java`), then walks each source root recording `package` declarations into a `package_to_files` map.
+- **Ruby Rails / Zeitwerk autoloading** — gated on `config/application.rb`, `resolvers/ruby_rails.py` builds bare-name and namespaced-name maps over standard autoload roots (`app/*`, `lib/`). `ResolverContext.rails_lookup` exposes the index for callers (heritage, call resolution, framework edges).
+- **Swift SPM target → directory mapping** — `resolvers/swift_spm.py` regex-parses `.target(name: "X", path: "Y")`, `.executableTarget`, and `.testTarget` declarations across all `Package.swift` files in the repo (defaults `Sources/<Name>` for code, `Tests/<Name>` for tests).
+- **Scala SBT / Mill multi-project** — `resolvers/scala_build.py` autodetects the build tool (`build.sbt` vs `build.sc`) and parses subprojects (SBT `lazy val core = project.in(file("core"))`, Mill `object Foo extends ScalaModule`). Walks each project's `src/main/scala` (or `src/`) recording packages into `package_to_files`.
+- **Cargo workspace crate resolution** — `resolvers/rust_workspace.py` parses root `Cargo.toml` `[workspace] members = [...]` plus each member's `[package] name`. `resolve_rust_import` consults the index after the same-crate probe so `use sibling_crate::module` resolves to the sibling crate's `src/`. Cargo's `-` → `_` import-identifier rewrite is honoured.
+
+#### Framework-aware edges (every major web framework)
+- **Spring Boot (Java/Kotlin)** — `@Component`/`@Service`/`@Repository`/`@Controller`/`@RestController`/`@Configuration` bean classes wire to their injection sites via `@Autowired` field/constructor analysis. Interface-typed dependencies fall back to `parsed.heritage` to find implementing classes. `@Bean` factory methods in `@Configuration` classes link to their return-type files.
+- **Rails (Ruby)** — `config/routes.rb` is line-walked with namespace-stack tracking: `resources :users`, `get "/foo", to: "users#index"`, and nested `namespace :admin do … end` all resolve to controller files via the Zeitwerk autoload index. ActiveRecord `belongs_to`/`has_many`/`has_one` relationships link model files (with simple inflector-style singularisation).
+- **Laravel (PHP)** — `routes/web.php` and `routes/api.php` parse modern `[Foo::class, 'method']` and legacy `'Foo@method'` syntaxes, plus `Route::resource`. Service-provider `bind`/`singleton`/`instance` calls link providers to bound classes. Eloquent `hasMany`/`belongsTo`/`hasOne` link models. Class resolution uses the composer PSR-4 map first, falling back to stem.
+- **Express / NestJS (TS/JS)** — Express `app.use(routerVar)` mirrors the FastAPI router-var pattern (resolves imported names ending in `Router`/`router` to source file). NestJS `@Module({ controllers: [...], providers: [...], imports: [...] })` arrays parse into module → target edges using a class-name → file map.
+- **Gin / Echo / Chi (Go)** — `r.GET("/p", users.Index)` style handler references resolve via the Go import list (using the multi-module resolver) for package-qualified handlers, or via a function-name → file map for receiver methods. Lambda handlers are accepted as missed.
+- **Axum / Actix (Rust)** — Axum `Router::new().route("/p", get(handler))`, Actix `web::resource("/p").route(web::get().to(handler))` / `.service(handler)` / `.configure(routes::register)` all resolve to handler files via a function-name → file map.
+
+#### Per-language dynamic-hint extractors
+- **Spring (JVM)** — `applicationContext.getBean(Foo.class)` and named-bean lookups, plus `@Bean` factory return-types.
+- **Ruby** — `Object.send(:method)` / `.public_send`, `Kernel.const_get`, `define_method`, ActiveSupport `delegate :foo, to: :bar`.
+- **PHP** — `call_user_func`/`call_user_func_array`, `new ReflectionClass(Foo::class)`, container `get`/`app`/`resolve`/`make` with `::class` arguments, `new $variable` instantiation markers.
+- **Scala** — `Class.forName(...)`, `runtimeMirror` / `reflect.runtime` markers, named `given foo: Bar = ???` and `implicit val foo: Bar = ???` declarations.
+- **Swift** — `NSClassFromString("Foo")`, `NSStringFromClass(Foo)`, `Selector("name")`, `#selector(name)`, KVC `value(forKey: "key")`.
+- **C** — function-pointer assignment (`fp = some_function;` where the right-hand side is a known function name), `dlopen("./libfoo.so")`, `dlsym(handle, "name")`.
+- **Luau** — `game:GetService("Name")`, `setmetatable(t, {__index = Other})`, `require(game.Service.Path)` markers.
+- **Go** — `reflect.TypeOf(Foo{})`, `plugin.Open(...)`, `plugin.Lookup(...)`.
+
+#### Symbol-extraction coverage
+- **Java records** — `record Point(double x, double y) {}` now captured as a class-kind symbol with optional modifiers.
+- **Kotlin** — `typealias Foo = Bar` and top-level / class-level `val`/`var` properties (locals inside function bodies remain excluded).
+- **Scala 3** — `enum_definition`, `given_definition` (named givens), and `var_definition` are now captured. `class_definition` and `function_definition` also capture leading annotations (`@deprecated`, `@tailrec`).
+- **Swift** — `subscript_declaration` captured as a method-kind symbol.
+- **Ruby** — top-level / class-level constant assignments (`MAX_RETRIES = 3`).
+- **PHP** — `const_declaration` and `property_declaration` (with or without explicit visibility) at both file and class scope.
+- **C** — `typedef int MyInt;` and `typedef struct Foo Bar;` aliases now produce symbols.
+- **Java class/interface/record annotations** — `(modifiers) @symbol.modifiers` capture extended to `class_declaration`, `interface_declaration`, and `record_declaration` so framework decorators surface in the symbol view.
+
+#### Documentation extraction
+- **Java module-level Javadoc** — `extract_module_docstring` gains a Java branch that picks up a leading `/** ... */` block before the package/import declarations.
+- **Luau docstrings** — both `--[[ block comment ]]` and runs of `---` triple-dash lines are extracted at module and symbol scope.
+
+### Fixed
+- **Java interface inheritance** — `interface IFoo extends IBase` now produces a heritage relation; the extractor previously only recognised the `interfaces` field on `class_declaration` and missed `extends_interfaces` on `interface_declaration`.
+- **Go struct embedding** — `type Foo struct { Base }` correctly emits a heritage edge from `Foo` to `Base`. The Go heritage extractor now traverses the `field_declaration_list` child when no `body` field is present (matches the actual tree-sitter-go grammar layout).
+- **Swift `extension_declaration` heritage** — extension conformance declarations now contribute heritage relations (`extension_declaration` was missing from Swift's `heritage_node_types`).
+
### Changed
- **Language tier promotion** — C# moves from "Good" to "Full" in `README.md` and `docs/LANGUAGE_SUPPORT.md`. Eight languages now sit at Full tier (was: seven).
+- **Heritage / bindings / dead-code internals refactored into per-language subpackages** — `extractors/heritage.py` and `extractors/bindings.py` (previously 600+ LOC monoliths) and `analysis/dead_code.py` are now subpackages with one file per language plus a re-export shim. Public API (`extract_heritage`, `extract_import_bindings`, `DeadCodeAnalyzer`, etc.) is unchanged.
+
+### Tests
+- **+90 unit tests** covering workspace-aware resolvers (PHP, Go, TypeScript, Swift, Kotlin, Scala, Ruby, Rust), framework-edge extraction (Spring, Rails, Laravel, Express/NestJS, Gin/Echo/Chi, Axum/Actix), per-language dynamic-hint extractors, and Java/Ruby/Scala/PHP/Go heritage + binding extractors.
---
diff --git a/docs/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.md
index 1f2c9aa53..85cf08ab0 100644
--- a/docs/LANGUAGE_SUPPORT.md
+++ b/docs/LANGUAGE_SUPPORT.md
@@ -36,10 +36,10 @@ call resolution, named bindings, heritage extraction, and docstrings.
| Language | Extensions | Entry Points | Import Style |
|----------|-----------|-------------|-------------|
| **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'` / `require()` |
+| **TypeScript** | `.ts` `.tsx` | `index.ts` `main.ts` `app.ts` `server.ts` | `import { x } from 'y'` / `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` |
-| **Go** | `.go` | `main.go` `cmd/main.go` | `import "path"` with `go.mod` resolution |
+| **Go** | `.go` | `main.go` `cmd/main.go` | `import "path"` with multi-module `go.mod` discovery (longest-prefix match) |
| **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` | `#include` with `compile_commands.json` resolution |
| **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 |
@@ -50,7 +50,8 @@ All eight languages support:
- Named binding extraction (mapping imported names to source symbols)
- Heritage extraction (class/interface/trait/record inheritance chains)
- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen, XML doc)
-- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#)
+- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection; ASP.NET controllers / minimal API / EF Core DbContext for C#; Spring Boot DI + `@Bean` factories for Java/Kotlin; Rails routes + ActiveRecord relationships; Laravel routes + service providers + Eloquent; Express `app.use(router)` + NestJS `@Module` arrays; Gin/Echo/Chi router → handler files for Go; Axum/Actix `.route` → handler files for Rust)
+- Per-language dynamic-hint extractors (Django/Pytest/Node for Python+JS/TS; .NET DI/Activator/InternalsVisibleTo for C#; Spring `getBean`/`@Bean` factories for Java/Kotlin; Ruby `send`/`const_get`/`define_method`/`delegate`; PHP `call_user_func`/`ReflectionClass`/container `get`; Scala `Class.forName`/`given`/`implicit val`; Swift `NSClassFromString`/`Selector`/`#selector`/KVC; C function-pointer assignment + `dlopen`/`dlsym`; Luau `game:GetService`/`setmetatable __index`; Go `reflect.TypeOf`/`plugin.Open`/`plugin.Lookup`)
- For C# only: MSBuild project graph (`<ProjectReference>` / `<PackageReference>`), namespace → file mapping across projects, `global using` / `using static` / `using alias` propagation, ASP.NET HTTP and gRPC-dotnet contract extraction in workspace mode, cross-repo `<ProjectReference>` and internal-NuGet detection
### Good
@@ -63,11 +64,11 @@ resolvers for each language.
| Language | Extensions | Entry Points | Import Style |
|----------|-----------|-------------|-------------|
| **C** | `.c` | `main.c` | `#include` with `compile_commands.json` (shares C++ grammar) |
-| **Kotlin** | `.kt` `.kts` | `Main.kt` `Application.kt` | `import com.example.Foo` |
-| **Ruby** | `.rb` | `main.rb` `app.rb` `config.ru` | `require 'mod'` / `require_relative './mod'` |
-| **Swift** | `.swift` | `main.swift` `App.swift` | `import Foundation` |
-| **Scala** | `.scala` | `Main.scala` `App.scala` | `import pkg.{A, B => C}` |
-| **PHP** | `.php` | `index.php` `public/index.php` | `use Foo\Bar\Baz` |
+| **Kotlin** | `.kt` `.kts` | `Main.kt` `Application.kt` | `import com.example.Foo` with Gradle `settings.gradle(.kts)` subprojects + `sourceSets` overrides |
+| **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 |
+| **PHP** | `.php` | `index.php` `public/index.php` | `use Foo\Bar\Baz` with composer.json `autoload.psr-4` longest-prefix resolution |
### Config / Data
@@ -282,7 +283,9 @@ they all derive their language sets from the registry automatically.
## Architecture
-The language pipeline is fully modular:
+The language pipeline is fully modular. Per-language code lives in
+dedicated subpackages — adding a new language means dropping a file
+into each subpackage rather than editing monoliths.
```
ingestion/
@@ -291,8 +294,14 @@ ingestion/
visibility.py # symbol visibility (public/private/protected)
signatures.py # human-readable signature building
docstrings.py # module + symbol docstring extraction
- bindings.py # import name + alias binding extraction
- heritage.py # inheritance/interface/trait extraction
+ bindings/ # import name + alias binding extraction (per-lang)
+ __init__.py # extract_import_bindings dispatcher
+ python.py ts_js.py go.py rust.py java.py kotlin.py
+ ruby.py csharp.py swift.py scala.py php.py cpp.py
+ heritage/ # inheritance/interface/trait extraction (per-lang)
+ __init__.py # extract_heritage + HERITAGE_EXTRACTORS dispatcher
+ python.py ts_js.py java.py go.py rust.py cpp.py
+ kotlin.py ruby.py swift.py csharp.py scala.py php.py
resolvers/ # Per-language import resolution
python.py # dotted imports, __init__.py, src/ layout
typescript.py # multi-ext probe, tsconfig aliases
@@ -301,18 +310,33 @@ ingestion/
cpp.py # compile_commands.json include paths
kotlin.py # package-to-directory mapping
ruby.py # require/require_relative resolution
- csharp.py # namespace-based resolution
+ csharp.py / dotnet/ # namespace-based + MSBuild project graph
swift.py # module import resolution
scala.py # package-to-directory mapping
php.py # namespace/PSR-4 resolution
generic.py # stem-matching fallback
- framework_edges.py # Django, FastAPI, Flask, pytest detection
+ framework_edges.py # Django, FastAPI, Flask, pytest, ASP.NET detection
+ dynamic_hints/ # Per-language dynamic-edge extractors
+ base.py # DynamicHintExtractor + DynamicEdge
+ registry.py # HintRegistry
+ django.py pytest_hints.py node.py dotnet.py
+ spring.py ruby.py php.py scala.py swift.py c.py luau.py go.py
parser.py # ASTParser (language-agnostic orchestration)
graph.py # GraphBuilder (import/call/heritage resolution)
+
+analysis/
+ dead_code/ # Dead code detection (Phase 1 split)
+ __init__.py # re-exports DeadCodeAnalyzer + dataclasses
+ analyzer.py # DeadCodeAnalyzer class + four detection passes
+ models.py # DeadCodeKind, DeadCodeFindingData, DeadCodeReport
+ constants.py # never-flag globs, framework decorators, fixtures
+ dynamic_markers.py # per-language source-text dynamic markers
```
Adding a new language requires zero changes to `parser.py`, `graph.py`,
-`traverser.py`, `dead_code.py`, or any other core file.
+`traverser.py`, or any analysis core file. New language work consists of
+adding one file to each per-language subpackage and registering it in the
+relevant `__init__.py` dispatcher / dict.
---
diff --git a/packages/cli/src/repowise/cli/__init__.py b/packages/cli/src/repowise/cli/__init__.py
index 1b3c4b9b2..d4fc24869 100644
--- a/packages/cli/src/repowise/cli/__init__.py
+++ b/packages/cli/src/repowise/cli/__init__.py
@@ -6,4 +6,4 @@ git signals, dead code detection, architectural decisions, and
AI-generated documentation.
"""
-__version__ = "0.3.1"
+__version__ = "0.4.0"
diff --git a/packages/core/src/repowise/core/__init__.py b/packages/core/src/repowise/core/__init__.py
index 60ec9c612..1633b350a 100644
--- a/packages/core/src/repowise/core/__init__.py
+++ b/packages/core/src/repowise/core/__init__.py
@@ -6,4 +6,4 @@ generation engine. This is the heart of repowise — all other packages depend o
Namespace package: repowise.core is part of the repowise namespace.
"""
-__version__ = "0.3.1"
+__version__ = "0.4.0"
diff --git a/packages/core/src/repowise/core/analysis/dead_code/__init__.py b/packages/core/src/repowise/core/analysis/dead_code/__init__.py
new file mode 100644
index 000000000..10992c3af
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/__init__.py
@@ -0,0 +1,35 @@
+"""Dead code detection for repowise.
+
+Pure graph traversal + git metadata. No LLM calls. Must complete in
+< 10 seconds on real repos.
+
+Public API (preserved for backwards compatibility — all callers import
+from ``repowise.core.analysis.dead_code``):
+
+- ``DeadCodeAnalyzer`` — the orchestrator class.
+- ``DeadCodeKind`` — enum of finding kinds.
+- ``DeadCodeFindingData`` — per-finding payload.
+- ``DeadCodeReport`` — aggregate report returned by ``analyze()``.
+
+Internal layout (Phase 1 refactor):
+
+- ``analyzer.py`` — ``DeadCodeAnalyzer`` class + four detection methods.
+- ``models.py`` — public dataclasses + ``DeadCodeKind`` enum.
+- ``constants.py`` — never-flag globs, framework decorators, fixture
+ path segments, non-code languages.
+- ``dynamic_markers.py`` — ``_DYNAMIC_IMPORT_MARKERS`` source-text dict
+ + ``find_dynamic_import_files()`` scanner.
+ Phase 2 (A1/A2) work lands here.
+"""
+
+from __future__ import annotations
+
+from .analyzer import DeadCodeAnalyzer
+from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport
+
+__all__ = [
+ "DeadCodeAnalyzer",
+ "DeadCodeFindingData",
+ "DeadCodeKind",
+ "DeadCodeReport",
+]
diff --git a/packages/core/src/repowise/core/analysis/dead_code.py b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
similarity index 69%
rename from packages/core/src/repowise/core/analysis/dead_code.py
rename to packages/core/src/repowise/core/analysis/dead_code/analyzer.py
index 12e103ed4..9d3ff039d 100644
--- a/packages/core/src/repowise/core/analysis/dead_code.py
+++ b/packages/core/src/repowise/core/analysis/dead_code/analyzer.py
@@ -1,224 +1,41 @@
-"""Dead code detection for repowise.
+"""DeadCodeAnalyzer — pure graph + git-metadata dead-code detection.
-Pure graph traversal + SQL — no LLM calls. Must complete in < 10 seconds.
+All analysis is graph traversal + SQL. No LLM calls. Must complete in
+< 10 seconds.
-Detects unreachable files, unused exports, unused internals, and
-zombie packages using the dependency graph and git metadata.
+The four detection passes (unreachable files, unused exports, unused
+internals, zombie packages) live as methods on this class. Constants,
+data models, and dynamic-import markers live in sibling modules under
+this package.
"""
from __future__ import annotations
import fnmatch
-from dataclasses import dataclass
from datetime import UTC, datetime
-from enum import StrEnum
from pathlib import Path
from typing import Any
import structlog
-from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
-
-logger = structlog.get_logger(__name__)
-
-
-class DeadCodeKind(StrEnum):
- UNREACHABLE_FILE = "unreachable_file"
- UNUSED_EXPORT = "unused_export"
- UNUSED_INTERNAL = "unused_internal"
- ZOMBIE_PACKAGE = "zombie_package"
-
-
-@dataclass
-class DeadCodeFindingData:
- kind: DeadCodeKind
- file_path: str
- symbol_name: str | None
- symbol_kind: str | None
- confidence: float
- reason: str
- last_commit_at: datetime | None
- commit_count_90d: int
- lines: int
- package: str | None
- evidence: list[str]
- safe_to_delete: bool
- primary_owner: str | None
- age_days: int | None
-
-
-@dataclass
-class DeadCodeReport:
- repo_id: str
- analyzed_at: datetime
- total_findings: int
- findings: list[DeadCodeFindingData]
- deletable_lines: int
- confidence_summary: dict # {"high": N, "medium": N, "low": N}
-
-
-# Non-code languages that should never be flagged as dead code.
-# Derived from the centralised LanguageRegistry — passthrough config/infra
-# languages plus "unknown".
-_NON_CODE_LANGUAGES: frozenset[str] = frozenset(
- spec.tag
- for spec in _LANG_REGISTRY.all_specs()
- if spec.is_passthrough and (not spec.is_code or spec.is_infra) and spec.tag != "openapi"
-) | {"unknown"}
-
-# Patterns that should never be flagged as dead
-_NEVER_FLAG_PATTERNS = (
- "*__init__.py",
- "*__main__.py",
- "*conftest.py",
- "*alembic/env.py",
- "*manage.py",
- "*wsgi.py",
- "*asgi.py",
- "*migrations*",
- "*schema*",
- "*seed*",
- "*.d.ts",
- "*setup.py",
- "*setup.cfg",
- "*next.config.*",
- "*vite.config.*",
- "*tailwind.config.*",
- "*postcss.config.*",
- "*jest.config.*",
- "*vitest.config.*",
- # Next.js / Remix / SvelteKit framework route files — loaded by the
- # framework at runtime, never imported via module imports.
- "*/page.tsx",
- "*/page.ts",
- "*/page.jsx",
- "*/page.js",
- "*/layout.tsx",
- "*/layout.ts",
- "*/route.tsx",
- "*/route.ts",
- "*/loading.tsx",
- "*/error.tsx",
- "*/not-found.tsx",
- "*/template.tsx",
- "*/default.tsx",
- # Nuxt route pages
- "*/pages/*.vue",
-)
-
-# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)
-_FRAMEWORK_DECORATORS = (
- "pytest.fixture",
- "pytest.mark",
- # Flask
- "app.route",
- "blueprint.route",
- "bp.route",
- # FastAPI
- "router.get",
- "router.post",
- "router.put",
- "router.delete",
- "router.patch",
- "app.get",
- "app.post",
- # Django
- "admin.register",
- "receiver",
+from .constants import (
+ _DEFAULT_DYNAMIC_PATTERNS,
+ _FRAMEWORK_DECORATORS,
+ _NEVER_FLAG_PATTERNS,
+ _NON_CODE_LANGUAGES,
+ _is_fixture_path,
)
+from .dynamic_markers import find_dynamic_edge_files, find_dynamic_import_files
+from .models import DeadCodeFindingData, DeadCodeKind, DeadCodeReport
-# Default dynamic patterns (plugins, handlers, etc.)
-_DEFAULT_DYNAMIC_PATTERNS = (
- "*Plugin",
- "*Handler",
- "*Adapter",
- "*Middleware",
- "*Mixin",
- "*Command",
- "register_*",
- "on_*",
- # Common route/view patterns
- "*_view",
- "*_endpoint",
- "*_route",
- "*_callback",
- "*_signal",
- "*_task",
-)
-
-# Path segments that indicate test fixture / sample data directories.
-# Files under these directories are test data, not real code — they should
-# never be flagged as dead even if nothing imports them.
-_FIXTURE_PATH_SEGMENTS = (
- "fixture",
- "fixtures",
- "testdata",
- "test_data",
- "sample_repo",
- "mock_data",
- "test_assets",
-)
-
-
-def _is_fixture_path(path: str) -> bool:
- """Return True if path is under a test fixture / sample data directory."""
- path_lower = path.lower().replace("\\", "/")
- for seg in _FIXTURE_PATH_SEGMENTS:
- if f"/{seg}/" in path_lower or path_lower.startswith(f"{seg}/"):
- return True
- return False
+logger = structlog.get_logger(__name__)
class DeadCodeAnalyzer:
"""Detects unreachable files, unused exports, unused internals, and
zombie packages using the dependency graph and git metadata.
-
- All analysis is graph traversal + SQL. No LLM calls.
"""
- # Patterns in source that indicate dynamic/runtime imports, keyed by suffix.
- _DYNAMIC_IMPORT_MARKERS: dict[str, tuple[str, ...]] = {
- ".py": (
- "importlib.import_module",
- "__import__(",
- "importlib.reload",
- "pkgutil.iter_modules",
- ),
- ".js": ("import(", "require(", "require.resolve("),
- ".mjs": ("import(", "require("),
- ".cjs": ("require(", "require.resolve("),
- ".ts": ("import(", "require("),
- ".tsx": ("import(", "require("),
- ".java": ("Class.forName(", "ServiceLoader.load("),
- ".kt": ("Class.forName(", "ServiceLoader.load("),
- ".rb": ("autoload ", "const_get(", "send(:require"),
- ".php": ("class_exists(", "interface_exists("),
- ".go": ("plugin.Open(", "reflect.New("),
- ".cs": (
- # Reflection-driven type loading
- "Type.GetType(",
- "Activator.CreateInstance(",
- "Assembly.Load(",
- "Assembly.LoadFrom(",
- "Assembly.LoadFile(",
- "GetExecutingAssembly().GetTypes(",
- # Cross-assembly visibility — types named in the friend assembly
- # may be used externally even with no static call site.
- "[assembly: InternalsVisibleTo",
- # Trim-safe reflection annotation
- "[DynamicDependency",
- # MEF / VS extensibility composition
- "[Export",
- "[ImportMany",
- # DI registration: types registered here have no static caller
- # but the framework instantiates them at runtime. Three forms.
- "AddScoped<",
- "AddSingleton<",
- "AddTransient<",
- "AddHostedService<",
- ),
- }
-
def __init__(
self,
graph: Any, # nx.DiGraph
@@ -227,33 +44,9 @@ class DeadCodeAnalyzer:
) -> None:
self.graph = graph
self.git_meta_map = git_meta_map or {}
- self._dynamic_import_files = self._find_dynamic_import_files(parsed_files or {})
-
- @classmethod
- def _find_dynamic_import_files(cls, parsed_files: dict) -> set[str]:
- """Return set of file paths that contain dynamic import calls.
-
- When a repo uses ``importlib.import_module``, ``import()``,
- ``Class.forName()``, etc., unreachable modules in the same package
- may be loaded at runtime. We use this to lower confidence on those
- findings.
- """
- result: set[str] = set()
- for path, pf in parsed_files.items():
- try:
- abs_path = getattr(pf, "file_info", None)
- if abs_path is None:
- continue
- src_path = Path(abs_path.abs_path)
- markers = cls._DYNAMIC_IMPORT_MARKERS.get(src_path.suffix)
- if not markers:
- continue
- source = src_path.read_text(errors="ignore")
- if any(marker in source for marker in markers):
- result.add(path)
- except Exception:
- continue
- return result
+ self._dynamic_import_files = find_dynamic_import_files(
+ parsed_files or {}
+ ) | find_dynamic_edge_files(graph)
def analyze(self, config: dict | None = None) -> DeadCodeReport:
"""Full analysis. Returns report with all findings."""
@@ -269,13 +62,12 @@ class DeadCodeAnalyzer:
if cfg.get("detect_unused_exports", True):
findings.extend(self._detect_unused_exports(dynamic_patterns, whitelist))
- if cfg.get("detect_unused_internals", False):
+ if cfg.get("detect_unused_internals", True):
findings.extend(self._detect_unused_internals(dynamic_patterns, whitelist))
if cfg.get("detect_zombie_packages", True):
findings.extend(self._detect_zombie_packages(whitelist))
- # Apply min_confidence filter
min_conf = cfg.get("min_confidence", 0.4)
findings = [f for f in findings if f.confidence >= min_conf]
@@ -299,7 +91,6 @@ class DeadCodeAnalyzer:
self, affected_files: list[str], config: dict | None = None
) -> DeadCodeReport:
"""Partial analysis for incremental updates."""
- # For partial analysis, only check affected files and their neighbors
cfg = config or {}
findings: list[DeadCodeFindingData] = []
dynamic_patterns = cfg.get("dynamic_patterns", _DEFAULT_DYNAMIC_PATTERNS)
@@ -315,7 +106,6 @@ class DeadCodeAnalyzer:
if self._should_never_flag(node, whitelist):
continue
- # Check if file became unreachable
in_deg = self.graph.in_degree(node)
node_data = self.graph.nodes.get(node, {})
if (
@@ -398,23 +188,21 @@ class DeadCodeAnalyzer:
age_days = git_meta.get("age_days")
primary_owner = git_meta.get("primary_owner_name")
- # Confidence rules — differentiate by age and activity.
# _is_old uses strict >, so pass days-1 to get >= semantics.
if commit_90d == 0 and last_commit and self._is_old(last_commit, days=364):
confidence = 1.0 # Untouched for a year+ — very likely dead
elif commit_90d == 0 and last_commit and self._is_old(last_commit, days=179):
- confidence = 0.9 # Untouched for 6+ months
+ confidence = 0.9
elif commit_90d == 0 and last_commit and self._is_old(last_commit, days=89):
- confidence = 0.8 # Untouched for 3+ months
+ confidence = 0.8
elif commit_90d == 0 and age_days is not None and age_days < 30:
- confidence = 0.55 # Recently created but no imports — may be WIP
+ confidence = 0.55 # Recently created — may be WIP
elif commit_90d == 0:
- confidence = 0.7 # No recent activity, unknown age
+ confidence = 0.7
else:
confidence = 0.4
- # Reduce confidence when dynamic imports exist in the same package —
- # importlib.import_module / __import__ may load this file at runtime.
+ # Reduce confidence when dynamic imports exist in the same package.
if self._dynamic_import_files:
node_pkg = str(Path(node).parent)
for dif in self._dynamic_import_files:
@@ -422,7 +210,6 @@ class DeadCodeAnalyzer:
confidence = min(confidence, 0.4)
break
- # safe_to_delete only if confidence >= 0.7 AND not matching dynamic patterns
safe = confidence >= 0.7
if safe and self._matches_dynamic_patterns(node, dynamic_patterns):
safe = False
@@ -431,7 +218,7 @@ class DeadCodeAnalyzer:
if commit_90d == 0:
evidence.append("No commits in last 90 days")
if self._dynamic_import_files and confidence <= 0.4:
- evidence.append("Package uses dynamic imports (importlib/__import__)")
+ evidence.append("Package uses dynamic imports or runtime-resolved edges")
return DeadCodeFindingData(
kind=DeadCodeKind.UNREACHABLE_FILE,
@@ -472,7 +259,6 @@ class DeadCodeAnalyzer:
if self._should_never_flag(str(node), whitelist):
continue
- # Get symbols defined in this file via DEFINES edges to symbol nodes
symbols = [
self.graph.nodes[succ]
for succ in self.graph.successors(node)
@@ -489,23 +275,19 @@ class DeadCodeAnalyzer:
continue
sym_name = sym.get("name", "")
- # Skip framework decorators (if stored on symbol node)
decorators = sym.get("decorators", [])
if any(
d.startswith(prefix) for d in decorators for prefix in _FRAMEWORK_DECORATORS
):
continue
- # Skip dynamic patterns
if self._name_matches_dynamic(sym_name, dynamic_patterns):
continue
- # Skip deprecated-named symbols (lower confidence)
is_deprecated = any(
sym_name.endswith(suffix) for suffix in ("_DEPRECATED", "_LEGACY", "_COMPAT")
)
- # Check for importers of this specific symbol
has_importers = False
for pred in self.graph.predecessors(node):
edge_data = self.graph[pred][node]
@@ -517,7 +299,6 @@ class DeadCodeAnalyzer:
if has_importers:
continue
- # Confidence scoring
if is_deprecated:
confidence = 0.3
elif file_has_importers:
@@ -559,7 +340,7 @@ class DeadCodeAnalyzer:
) -> list[DeadCodeFindingData]:
"""Detect private/internal symbols with zero incoming call edges.
- Off by default (higher false-positive rate). Enable with
+ Off by default (higher false-positive rate). Enable with
``detect_unused_internals=True`` in the config dict.
"""
findings: list[DeadCodeFindingData] = []
@@ -569,7 +350,6 @@ class DeadCodeAnalyzer:
continue
if node_data.get("visibility") not in ("private", "internal"):
continue
- # Skip test files and fixtures
file_path = node_data.get("file_path", "")
if not file_path:
continue
@@ -582,13 +362,11 @@ class DeadCodeAnalyzer:
continue
sym_name = node_data.get("name", "")
- # Skip dunder methods and common patterns
if sym_name.startswith("__") and sym_name.endswith("__"):
continue
if self._name_matches_dynamic(sym_name, dynamic_patterns):
continue
- # Check for incoming CALL edges
has_callers = any(
self.graph.get_edge_data(pred, node, {}).get("edge_type") == "calls"
for pred in self.graph.predecessors(node)
@@ -624,7 +402,6 @@ class DeadCodeAnalyzer:
"""Detect monorepo packages with no incoming inter_package edges."""
findings = []
- # Find package nodes (directories with multiple files)
packages: dict[str, list[str]] = {}
for node in self.graph.nodes():
if str(node).startswith("external:"):
@@ -635,13 +412,12 @@ class DeadCodeAnalyzer:
packages.setdefault(pkg, []).append(str(node))
if len(packages) < 2:
- return findings # Not a monorepo
+ return findings
for pkg, files in packages.items():
if pkg in whitelist:
continue
- # Check if any file in this package is imported from outside the package
has_external_importers = False
for f in files:
for pred in self.graph.predecessors(f):
@@ -661,7 +437,6 @@ class DeadCodeAnalyzer:
for f in files
if f in self.graph
)
- # Aggregate git metadata across package files for enrichment
pkg_last_commit: datetime | None = None
pkg_total_commits_90d = 0
pkg_owner: str | None = None
@@ -715,7 +490,7 @@ class DeadCodeAnalyzer:
for pattern in _NEVER_FLAG_PATTERNS:
if fnmatch.fnmatch(path, pattern):
return True
- # Check if it's an __init__.py (re-export barrel)
+ # __init__.py is a re-export barrel
return Path(path).name == "__init__.py"
def _is_api_contract(self, node_data: dict) -> bool:
diff --git a/packages/core/src/repowise/core/analysis/dead_code/constants.py b/packages/core/src/repowise/core/analysis/dead_code/constants.py
new file mode 100644
index 000000000..6a0e91c24
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/constants.py
@@ -0,0 +1,120 @@
+"""Static configuration for dead-code detection.
+
+These tuples / frozensets shape what the analyzer treats as "always
+alive" (framework decorators, never-flag path globs) and where to skip
+entirely (test fixture directories, non-code languages).
+"""
+
+from __future__ import annotations
+
+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY
+
+
+# Non-code languages that should never be flagged as dead code.
+# Derived from the centralised LanguageRegistry — passthrough config/infra
+# languages plus "unknown".
+_NON_CODE_LANGUAGES: frozenset[str] = frozenset(
+ spec.tag
+ for spec in _LANG_REGISTRY.all_specs()
+ if spec.is_passthrough and (not spec.is_code or spec.is_infra) and spec.tag != "openapi"
+) | {"unknown"}
+
+# Patterns that should never be flagged as dead.
+_NEVER_FLAG_PATTERNS: tuple[str, ...] = (
+ "*__init__.py",
+ "*__main__.py",
+ "*conftest.py",
+ "*alembic/env.py",
+ "*manage.py",
+ "*wsgi.py",
+ "*asgi.py",
+ "*migrations*",
+ "*schema*",
+ "*seed*",
+ "*.d.ts",
+ "*setup.py",
+ "*setup.cfg",
+ "*next.config.*",
+ "*vite.config.*",
+ "*tailwind.config.*",
+ "*postcss.config.*",
+ "*jest.config.*",
+ "*vitest.config.*",
+ # Next.js / Remix / SvelteKit framework route files — loaded by the
+ # framework at runtime, never imported via module imports.
+ "*/page.tsx",
+ "*/page.ts",
+ "*/page.jsx",
+ "*/page.js",
+ "*/layout.tsx",
+ "*/layout.ts",
+ "*/route.tsx",
+ "*/route.ts",
+ "*/loading.tsx",
+ "*/error.tsx",
+ "*/not-found.tsx",
+ "*/template.tsx",
+ "*/default.tsx",
+ # Nuxt route pages
+ "*/pages/*.vue",
+)
+
+# Decorator patterns that indicate framework usage (route handlers, fixtures, etc.)
+_FRAMEWORK_DECORATORS: tuple[str, ...] = (
+ "pytest.fixture",
+ "pytest.mark",
+ # Flask
+ "app.route",
+ "blueprint.route",
+ "bp.route",
+ # FastAPI
+ "router.get",
+ "router.post",
+ "router.put",
+ "router.delete",
+ "router.patch",
+ "app.get",
+ "app.post",
+ # Django
+ "admin.register",
+ "receiver",
+)
+
+# Default dynamic patterns (plugins, handlers, etc.)
+_DEFAULT_DYNAMIC_PATTERNS: tuple[str, ...] = (
+ "*Plugin",
+ "*Handler",
+ "*Adapter",
+ "*Middleware",
+ "*Mixin",
+ "*Command",
+ "register_*",
+ "on_*",
+ # Common route/view patterns
+ "*_view",
+ "*_endpoint",
+ "*_route",
+ "*_callback",
+ "*_signal",
+ "*_task",
+)
+
+# Path segments that indicate test fixture / sample data directories.
+_FIXTURE_PATH_SEGMENTS: tuple[str, ...] = (
+ "fixture",
+ "fixtures",
+ "testdata",
+ "test_data",
+ "sample_repo",
+ "mock_data",
+ "test_assets",
+)
+
+
+def _is_fixture_path(path: str) -> bool:
+ """Return True if path is under a test fixture / sample data directory."""
+ path_lower = path.lower().replace("\\", "/")
+ for seg in _FIXTURE_PATH_SEGMENTS:
+ if f"/{seg}/" in path_lower or path_lower.startswith(f"{seg}/"):
+ return True
+ return False
diff --git a/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
new file mode 100644
index 000000000..e7bd03908
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/dynamic_markers.py
@@ -0,0 +1,153 @@
+"""Source-text markers for runtime / dynamic dispatch.
+
+When a repo uses ``importlib.import_module``, ``import()``,
+``Class.forName()``, etc., unreachable modules in the same package may
+be loaded at runtime. The dead-code analyzer scans for these markers to
+lower confidence on findings within their packages.
+
+Phase 2 work (A1/A2 in ``docs/LANGUAGE_REMAINING_WORK.md``) will:
+
+- expand the marker dicts to cover Go, Ruby, PHP, Kotlin, Swift, Scala,
+- and / or replace this text-scan with consumption of ``edge_type="dynamic"``
+ edges produced by the ``dynamic_hints`` extractors.
+
+Keep new entries grouped by file extension so the per-language audit
+in Phase 2 stays mechanical.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+
+# Patterns in source that indicate dynamic/runtime imports, keyed by suffix.
+_DYNAMIC_IMPORT_MARKERS: dict[str, tuple[str, ...]] = {
+ ".py": (
+ "importlib.import_module",
+ "__import__(",
+ "importlib.reload",
+ "pkgutil.iter_modules",
+ ),
+ ".js": ("import(", "require(", "require.resolve("),
+ ".mjs": ("import(", "require("),
+ ".cjs": ("require(", "require.resolve("),
+ ".ts": ("import(", "require("),
+ ".tsx": ("import(", "require("),
+ ".java": ("Class.forName(", "ServiceLoader.load("),
+ ".kt": (
+ "Class.forName(",
+ "ServiceLoader.load(",
+ "KClass.createInstance(",
+ "::class.java",
+ ),
+ ".rb": (
+ "autoload ",
+ "const_get(",
+ "send(:require",
+ "Object.send(",
+ "Kernel.const_get(",
+ ".public_send(",
+ ),
+ ".php": (
+ "class_exists(",
+ "interface_exists(",
+ "call_user_func(",
+ "call_user_func_array(",
+ "new $",
+ "ReflectionClass(",
+ ),
+ ".go": (
+ "plugin.Open(",
+ "reflect.New(",
+ "reflect.TypeOf(",
+ "reflect.ValueOf(",
+ ),
+ ".swift": (
+ "NSClassFromString(",
+ "Selector(",
+ "#selector(",
+ "NSStringFromClass(",
+ ),
+ ".scala": (
+ "Class.forName(",
+ "runtimeMirror(",
+ "reflect.runtime",
+ ),
+ ".cs": (
+ # Reflection-driven type loading
+ "Type.GetType(",
+ "Activator.CreateInstance(",
+ "Assembly.Load(",
+ "Assembly.LoadFrom(",
+ "Assembly.LoadFile(",
+ "GetExecutingAssembly().GetTypes(",
+ # Cross-assembly visibility — types named in the friend assembly
+ # may be used externally even with no static call site.
+ "[assembly: InternalsVisibleTo",
+ # Trim-safe reflection annotation
+ "[DynamicDependency",
+ # MEF / VS extensibility composition
+ "[Export",
+ "[ImportMany",
+ # DI registration: types registered here have no static caller
+ # but the framework instantiates them at runtime. Three forms.
+ "AddScoped<",
+ "AddSingleton<",
+ "AddTransient<",
+ "AddHostedService<",
+ ),
+}
+
+
+def find_dynamic_import_files(parsed_files: dict) -> set[str]:
+ """Return the set of file paths whose source contains a dynamic-import marker."""
+ result: set[str] = set()
+ for path, pf in parsed_files.items():
+ try:
+ file_info = getattr(pf, "file_info", None)
+ if file_info is None:
+ continue
+ src_path = Path(file_info.abs_path)
+ markers = _DYNAMIC_IMPORT_MARKERS.get(src_path.suffix)
+ if not markers:
+ continue
+ source = src_path.read_text(errors="ignore")
+ if any(marker in source for marker in markers):
+ result.add(path)
+ except Exception:
+ continue
+ return result
+
+
+def find_dynamic_edge_files(graph) -> set[str]:
+ """Return the set of file paths involved in dynamic graph edges.
+
+ An edge counts as dynamic when its ``edge_type`` is ``"dynamic"`` or
+ starts with ``"dynamic_"`` (semantic sub-types like ``"dynamic_uses"``,
+ ``"dynamic_imports"``, ``"url_route"`` after the graph-builder prefix).
+ Both endpoints contribute: the source's file and the target's file
+ (or the node id itself when nodes are file paths).
+ """
+ if graph is None:
+ return set()
+ result: set[str] = set()
+ try:
+ for u, v, data in graph.edges(data=True):
+ etype = data.get("edge_type", "")
+ if etype != "dynamic" and not etype.startswith("dynamic_"):
+ continue
+ for endpoint in (u, v):
+ if endpoint is None:
+ continue
+ endpoint_str = str(endpoint)
+ if endpoint_str.startswith("external:"):
+ continue
+ node_data = graph.nodes.get(endpoint, {})
+ file_path = node_data.get("file_path")
+ if file_path:
+ result.add(str(file_path))
+ else:
+ result.add(endpoint_str)
+ except Exception:
+ return result
+ return result
diff --git a/packages/core/src/repowise/core/analysis/dead_code/models.py b/packages/core/src/repowise/core/analysis/dead_code/models.py
new file mode 100644
index 000000000..a4c8e584d
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/dead_code/models.py
@@ -0,0 +1,42 @@
+"""Public dataclasses + enum for dead-code findings."""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime
+from enum import StrEnum
+
+
+class DeadCodeKind(StrEnum):
+ UNREACHABLE_FILE = "unreachable_file"
+ UNUSED_EXPORT = "unused_export"
+ UNUSED_INTERNAL = "unused_internal"
+ ZOMBIE_PACKAGE = "zombie_package"
+
+
+@dataclass
+class DeadCodeFindingData:
+ kind: DeadCodeKind
+ file_path: str
+ symbol_name: str | None
+ symbol_kind: str | None
+ confidence: float
+ reason: str
+ last_commit_at: datetime | None
+ commit_count_90d: int
+ lines: int
+ package: str | None
+ evidence: list[str]
+ safe_to_delete: bool
+ primary_owner: str | None
+ age_days: int | None
+
+
+@dataclass
+class DeadCodeReport:
+ repo_id: str
+ analyzed_at: datetime
+ total_findings: int
+ findings: list[DeadCodeFindingData]
+ deletable_lines: int
+ confidence_summary: dict # {"high": N, "medium": N, "low": N}
diff --git a/packages/core/src/repowise/core/generation/models.py b/packages/core/src/repowise/core/generation/models.py
index 2cddf8ca1..ca65093cd 100644
--- a/packages/core/src/repowise/core/generation/models.py
+++ b/packages/core/src/repowise/core/generation/models.py
@@ -290,7 +290,7 @@ class DeadCodeConfig:
enabled: bool = True
detect_unreachable_files: bool = True
detect_unused_exports: bool = True
- detect_unused_internals: bool = False
+ detect_unused_internals: bool = True
detect_zombie_packages: bool = True
min_confidence: float = 0.4
safe_to_delete_threshold: float = 0.7
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/c.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/c.py
new file mode 100644
index 000000000..57f4e5e30
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/c.py
@@ -0,0 +1,96 @@
+"""Dynamic-hint extractor for C function pointers and dlopen/dlsym."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {"build", "out", "node_modules", ".git", "third_party"}
+
+# fp = some_function; (assigning a function name to a variable — common C function-pointer wiring)
+_FN_PTR_ASSIGN_RE = re.compile(
+ r"\b(\w+)\s*=\s*([a-z_]\w*)\s*;",
+)
+# dlsym(handle, "name")
+_DLSYM_RE = re.compile(r"dlsym\s*\(\s*\w+\s*,\s*[\"']([A-Za-z_]\w*)[\"']")
+# dlopen("./libfoo.so", ...)
+_DLOPEN_RE = re.compile(r"dlopen\s*\(\s*[\"']([^\"']+)[\"']")
+
+_FUNC_DEF_RE = re.compile(
+ r"^\s*(?:static\s+|extern\s+|inline\s+)*[\w\*\s]+\s+([a-z_]\w*)\s*\([^;]*\)\s*\{",
+ re.MULTILINE,
+)
+
+
+class CDynamicHints(DynamicHintExtractor):
+ """Discover C function-pointer assignments and dlopen/dlsym usage."""
+
+ name = "c"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ edges: list[DynamicEdge] = []
+
+ func_to_files: dict[str, list[str]] = {}
+ sources: list[tuple[Path, str]] = []
+ repo_root_resolved = repo_root.resolve()
+ for ext in (".c", ".h"):
+ for src in repo_root.rglob(f"*{ext}"):
+ try:
+ rel_path = src.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ rel = rel_path.as_posix()
+ sources.append((src, text))
+ for match in _FUNC_DEF_RE.finditer(text):
+ func_to_files.setdefault(match.group(1), []).append(rel)
+
+ for src, text in sources:
+ try:
+ rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ continue
+
+ seen: set[tuple[str, str]] = set()
+
+ for match in _FN_PTR_ASSIGN_RE.finditer(text):
+ # Right-hand side must be a known function name to count as
+ # a function-pointer assignment (filters out variable copies).
+ name = match.group(2)
+ if name in func_to_files:
+ for target in func_to_files[name]:
+ key = (target, "fn_ptr")
+ if key in seen or target == rel:
+ continue
+ seen.add(key)
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:fn_ptr",
+ ))
+
+ for match in _DLSYM_RE.finditer(text):
+ for target in func_to_files.get(match.group(1), []):
+ if target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:dlsym",
+ ))
+
+ for match in _DLOPEN_RE.finditer(text):
+ edges.append(DynamicEdge(
+ source=rel,
+ target=f"external:dlopen:{match.group(1)}",
+ edge_type="dynamic_imports",
+ hint_source=f"{self.name}:dlopen",
+ ))
+
+ return edges
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
index 7492c858d..b6036cbbd 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/dotnet.py
@@ -57,17 +57,19 @@ class DotNetDynamicHints(DynamicHintExtractor):
# parsing and operates on raw file text.
type_to_file: dict[str, str] = {}
cs_files: list[tuple[Path, str]] = [] # (path, text)
+ repo_root_resolved = repo_root.resolve()
for cs in repo_root.rglob("*.cs"):
- if any(part in _SKIP_DIRS for part in cs.parts):
+ try:
+ rel_path = cs.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
continue
try:
text = cs.read_text(encoding="utf-8-sig", errors="ignore")
except OSError:
continue
- try:
- rel = cs.resolve().relative_to(repo_root.resolve()).as_posix()
- except ValueError:
- continue
+ rel = rel_path.as_posix()
cs_files.append((cs, text))
# Only index publicly-declared top-level types — generic regex; a
# collision falls back to the first match seen.
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py
new file mode 100644
index 000000000..bafabf19e
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/go.py
@@ -0,0 +1,85 @@
+"""Dynamic-hint extractor for Go reflect/plugin patterns."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {"vendor", "node_modules", ".git", "bin"}
+
+# reflect.TypeOf(Foo{}) / reflect.New(reflect.TypeOf(Foo{}))
+_REFLECT_TYPEOF_RE = re.compile(r"reflect\.TypeOf\s*\(\s*([A-Za-z_]\w*)")
+# plugin.Open("./plugin.so")
+_PLUGIN_OPEN_RE = re.compile(r"plugin\.Open\s*\(\s*[\"']([^\"']+)[\"']")
+# plugin.Lookup("Foo")
+_PLUGIN_LOOKUP_RE = re.compile(r"\.Lookup\s*\(\s*[\"']([A-Za-z_]\w*)[\"']")
+
+_TYPE_DECL_RE = re.compile(r"^\s*type\s+([A-Z]\w*)\s+", re.MULTILINE)
+_FUNC_DECL_RE = re.compile(r"^\s*func\s+(?:\(\s*\w+\s+\*?\w+\s*\)\s*)?([A-Z]\w*)", re.MULTILINE)
+
+
+class GoDynamicHints(DynamicHintExtractor):
+ """Discover Go reflect.TypeOf / plugin.Open / plugin.Lookup."""
+
+ name = "go"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ edges: list[DynamicEdge] = []
+
+ type_to_file: dict[str, str] = {}
+ func_to_file: dict[str, str] = {}
+ sources: list[tuple[Path, str]] = []
+ repo_root_resolved = repo_root.resolve()
+ for src in repo_root.rglob("*.go"):
+ try:
+ rel_path = src.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ rel = rel_path.as_posix()
+ sources.append((src, text))
+ for match in _TYPE_DECL_RE.finditer(text):
+ type_to_file.setdefault(match.group(1), rel)
+ for match in _FUNC_DECL_RE.finditer(text):
+ func_to_file.setdefault(match.group(1), rel)
+
+ for src, text in sources:
+ try:
+ rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ continue
+
+ for match in _REFLECT_TYPEOF_RE.finditer(text):
+ target = type_to_file.get(match.group(1))
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:reflect_typeof",
+ ))
+
+ for match in _PLUGIN_OPEN_RE.finditer(text):
+ edges.append(DynamicEdge(
+ source=rel,
+ target=f"external:go_plugin:{match.group(1)}",
+ edge_type="dynamic_imports",
+ hint_source=f"{self.name}:plugin_open",
+ ))
+
+ for match in _PLUGIN_LOOKUP_RE.finditer(text):
+ target = func_to_file.get(match.group(1)) or type_to_file.get(match.group(1))
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:plugin_lookup",
+ ))
+
+ return edges
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/luau.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/luau.py
new file mode 100644
index 000000000..c7fb430fd
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/luau.py
@@ -0,0 +1,88 @@
+"""Dynamic-hint extractor for Luau / Roblox patterns."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {".git", "node_modules", "out", "build", "Packages"}
+
+# game:GetService("ReplicatedStorage")
+_GET_SERVICE_RE = re.compile(r"game\s*:\s*GetService\s*\(\s*[\"']([A-Za-z_]\w*)[\"']")
+# setmetatable(t, {__index = Other})
+_SETMETATABLE_RE = re.compile(
+ r"setmetatable\s*\([^,]+,\s*\{[^}]*__index\s*=\s*([A-Za-z_]\w*)"
+)
+# require(script.Foo) — already handled by static resolver, here we capture
+# absolute Roblox paths that fall through.
+_REQUIRE_GAME_RE = re.compile(r"require\s*\(\s*game[.:]([A-Za-z_][\w.:]*)\)")
+
+
+class LuauDynamicHints(DynamicHintExtractor):
+ """Discover Luau metatable / GetService / Roblox-instance patterns."""
+
+ name = "luau"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ edges: list[DynamicEdge] = []
+
+ sources: list[tuple[Path, str]] = []
+ repo_root_resolved = repo_root.resolve()
+ # luau plus lua extensions
+ for ext in (".luau", ".lua"):
+ for src in repo_root.rglob(f"*{ext}"):
+ try:
+ rel_path = src.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ sources.append((src, text))
+
+ # Build a map of file stem → file path for metatable __index resolution
+ stem_to_file: dict[str, str] = {}
+ for src, _ in sources:
+ try:
+ rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ continue
+ stem_to_file.setdefault(src.stem, rel)
+
+ for src, text in sources:
+ try:
+ rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ continue
+
+ for match in _GET_SERVICE_RE.finditer(text):
+ edges.append(DynamicEdge(
+ source=rel,
+ target=f"external:roblox_service:{match.group(1)}",
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:get_service",
+ ))
+
+ for match in _SETMETATABLE_RE.finditer(text):
+ target = stem_to_file.get(match.group(1))
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:metatable_index",
+ ))
+
+ for match in _REQUIRE_GAME_RE.finditer(text):
+ edges.append(DynamicEdge(
+ source=rel,
+ target=f"external:roblox_path:{match.group(1)}",
+ edge_type="dynamic_imports",
+ hint_source=f"{self.name}:require_game",
+ ))
+
+ return edges
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/php.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/php.py
new file mode 100644
index 000000000..7c3ae720f
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/php.py
@@ -0,0 +1,100 @@
+"""Dynamic-hint extractor for PHP reflective / container patterns."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {"vendor", "node_modules", ".git", "storage", "bootstrap"}
+
+# call_user_func(['Foo', 'method']) / call_user_func('Foo::method')
+_CALL_USER_FUNC_RE = re.compile(
+ r"call_user_func(?:_array)?\s*\(\s*(?:\[\s*[\"']([A-Z]\w*)[\"']\s*,\s*[\"']\w+[\"']\s*\]|[\"']([A-Z]\w*)::\w+[\"'])"
+)
+# new ReflectionClass(Foo::class) / new ReflectionClass('Foo')
+_REFLECTION_CLASS_RE = re.compile(
+ r"new\s+ReflectionClass\s*\(\s*(?:([A-Z]\w*)::class|[\"']([A-Z]\w*)[\"'])"
+)
+# $container->get(Foo::class) / app(Foo::class) / resolve(Foo::class)
+_CONTAINER_GET_RE = re.compile(
+ r"(?:->\s*get|\bapp|\bresolve|\bmake)\s*\(\s*([A-Z]\w*)::class"
+)
+# new $varname(...) — pure variable instantiation, no static target
+_NEW_DOLLAR_RE = re.compile(r"new\s+\$\w+\s*\(")
+
+_CLASS_DECL_RE = re.compile(r"^\s*(?:abstract\s+|final\s+)?(?:class|interface|trait|enum)\s+([A-Z]\w*)", re.MULTILINE)
+
+
+class PhpDynamicHints(DynamicHintExtractor):
+ """Discover PHP reflection, container, and dynamic-instantiation patterns."""
+
+ name = "php"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ edges: list[DynamicEdge] = []
+
+ type_to_file: dict[str, str] = {}
+ php_files: list[tuple[Path, str]] = []
+ repo_root_resolved = repo_root.resolve()
+ for src in repo_root.rglob("*.php"):
+ try:
+ rel_path = src.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ rel = rel_path.as_posix()
+ php_files.append((src, text))
+ for match in _CLASS_DECL_RE.finditer(text):
+ type_to_file.setdefault(match.group(1), rel)
+
+ for src, text in php_files:
+ try:
+ rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ continue
+
+ for match in _CALL_USER_FUNC_RE.finditer(text):
+ name = match.group(1) or match.group(2)
+ target = type_to_file.get(name)
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:call_user_func",
+ ))
+
+ for match in _REFLECTION_CLASS_RE.finditer(text):
+ name = match.group(1) or match.group(2)
+ target = type_to_file.get(name)
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:reflection_class",
+ ))
+
+ for match in _CONTAINER_GET_RE.finditer(text):
+ target = type_to_file.get(match.group(1))
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:container_get",
+ ))
+
+ if _NEW_DOLLAR_RE.search(text):
+ edges.append(DynamicEdge(
+ source=rel,
+ target=f"external:php_dynamic:new_var",
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:new_var",
+ ))
+
+ return edges
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 de7ccaa3c..db1a20e5f 100644
--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/registry.py
@@ -5,10 +5,18 @@ from pathlib import Path
import structlog
from .base import DynamicEdge, DynamicHintExtractor
+from .c import CDynamicHints
from .django import DjangoDynamicHints
from .dotnet import DotNetDynamicHints
-from .pytest_hints import PytestDynamicHints
+from .go import GoDynamicHints
+from .luau import LuauDynamicHints
from .node import NodeDynamicHints
+from .php import PhpDynamicHints
+from .pytest_hints import PytestDynamicHints
+from .ruby import RubyDynamicHints
+from .scala import ScalaDynamicHints
+from .spring import SpringDynamicHints
+from .swift import SwiftDynamicHints
log = structlog.get_logger(__name__)
@@ -20,6 +28,14 @@ class HintRegistry:
PytestDynamicHints(),
NodeDynamicHints(),
DotNetDynamicHints(),
+ SpringDynamicHints(),
+ RubyDynamicHints(),
+ PhpDynamicHints(),
+ ScalaDynamicHints(),
+ SwiftDynamicHints(),
+ CDynamicHints(),
+ LuauDynamicHints(),
+ GoDynamicHints(),
]
def extract_all(self, repo_root: Path) -> list[DynamicEdge]:
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/ruby.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/ruby.py
new file mode 100644
index 000000000..5d0e0b268
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/ruby.py
@@ -0,0 +1,103 @@
+"""Dynamic-hint extractor for Ruby reflective patterns."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {"vendor", "node_modules", ".git", "tmp", "log"}
+
+# Object.send(:method) / .send("method") / .public_send(...)
+_SEND_RE = re.compile(r"\.(?:public_)?send\s*\(\s*[:\"']([A-Za-z_]\w*)")
+# Kernel.const_get / Object.const_get / SomeModule.const_get
+_CONST_GET_RE = re.compile(r"const_get\s*\(\s*[:\"']?([A-Z]\w*)")
+# define_method(:name) — runtime method definition
+_DEFINE_METHOD_RE = re.compile(r"define_method\s*\(\s*[:\"']([A-Za-z_]\w*)")
+# delegate :foo, to: :bar — ActiveSupport
+_DELEGATE_RE = re.compile(r"delegate\s+:([A-Za-z_]\w*)\s*,\s*to:\s*:([A-Za-z_]\w*)")
+
+# Constant/class declarations: class Foo / module Foo / Foo = Class.new
+_CLASS_DECL_RE = re.compile(r"^\s*(?:class|module)\s+([A-Z]\w*)", re.MULTILINE)
+_METHOD_DECL_RE = re.compile(r"^\s*def\s+(?:self\.)?([A-Za-z_]\w*)", re.MULTILINE)
+
+
+class RubyDynamicHints(DynamicHintExtractor):
+ """Discover Ruby reflective method dispatch and constant lookup."""
+
+ name = "ruby"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ edges: list[DynamicEdge] = []
+
+ const_to_file: dict[str, str] = {}
+ method_to_files: dict[str, list[str]] = {}
+ rb_files: list[tuple[Path, str]] = []
+ repo_root_resolved = repo_root.resolve()
+ for src in repo_root.rglob("*.rb"):
+ try:
+ rel_path = src.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ rel = rel_path.as_posix()
+ rb_files.append((src, text))
+ for match in _CLASS_DECL_RE.finditer(text):
+ const_to_file.setdefault(match.group(1), rel)
+ for match in _METHOD_DECL_RE.finditer(text):
+ method_to_files.setdefault(match.group(1), []).append(rel)
+
+ for src, text in rb_files:
+ try:
+ rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ continue
+
+ seen_targets: set[tuple[str, str]] = set()
+
+ def _emit(target: str, hint: str) -> None:
+ key = (target, hint)
+ if key in seen_targets:
+ return
+ seen_targets.add(key)
+ if target != rel:
+ edges.append(
+ DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:{hint}",
+ )
+ )
+
+ for match in _SEND_RE.finditer(text):
+ for target in method_to_files.get(match.group(1), []):
+ _emit(target, "send")
+
+ for match in _CONST_GET_RE.finditer(text):
+ target = const_to_file.get(match.group(1))
+ if target:
+ _emit(target, "const_get")
+
+ for match in _DEFINE_METHOD_RE.finditer(text):
+ # Self-emission only — define_method declares a method on the
+ # current scope. Record as external symbol marker.
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=f"external:ruby_method:{match.group(1)}",
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:define_method",
+ )
+ )
+
+ for match in _DELEGATE_RE.finditer(text):
+ for target in method_to_files.get(match.group(1), []):
+ _emit(target, "delegate")
+
+ return edges
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/scala.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/scala.py
new file mode 100644
index 000000000..a789c23d1
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/scala.py
@@ -0,0 +1,93 @@
+"""Dynamic-hint extractor for Scala reflection and implicit/given patterns."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {"target", "project", ".bloop", ".metals", "node_modules", ".git"}
+
+_CLASS_FORNAME_RE = re.compile(r"Class\.forName\s*\(\s*[\"']([\w.]+)[\"']")
+_RUNTIME_MIRROR_RE = re.compile(r"runtimeMirror\s*\(")
+_REFLECT_RUNTIME_RE = re.compile(r"reflect\.runtime\b")
+# given Foo: Bar = ... / implicit val foo: Bar = ...
+_GIVEN_DECL_RE = re.compile(r"\bgiven\s+(\w+)?\s*:\s*([A-Z]\w*)")
+_IMPLICIT_VAL_RE = re.compile(r"\bimplicit\s+val\s+\w+\s*:\s*([A-Z]\w*)")
+
+_TYPE_DECL_RE = re.compile(r"\b(?:class|trait|object|enum)\s+([A-Z]\w*)")
+
+
+class ScalaDynamicHints(DynamicHintExtractor):
+ """Discover Scala reflective class loads + implicit/given resolution markers."""
+
+ name = "scala"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ edges: list[DynamicEdge] = []
+
+ type_to_file: dict[str, str] = {}
+ sources: list[tuple[Path, str]] = []
+ repo_root_resolved = repo_root.resolve()
+ for src in repo_root.rglob("*.scala"):
+ try:
+ rel_path = src.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ rel = rel_path.as_posix()
+ sources.append((src, text))
+ for match in _TYPE_DECL_RE.finditer(text):
+ type_to_file.setdefault(match.group(1), rel)
+
+ def _short(name: str) -> str:
+ return name.rsplit(".", 1)[-1]
+
+ for src, text in sources:
+ try:
+ rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ continue
+
+ for match in _CLASS_FORNAME_RE.finditer(text):
+ target = type_to_file.get(_short(match.group(1)))
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:class_forname",
+ ))
+
+ if _RUNTIME_MIRROR_RE.search(text) or _REFLECT_RUNTIME_RE.search(text):
+ edges.append(DynamicEdge(
+ source=rel,
+ target=f"external:scala_reflect",
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:runtime_mirror",
+ ))
+
+ for match in _GIVEN_DECL_RE.finditer(text):
+ target = type_to_file.get(match.group(2))
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:given",
+ ))
+
+ for match in _IMPLICIT_VAL_RE.finditer(text):
+ target = type_to_file.get(match.group(1))
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:implicit_val",
+ ))
+
+ return edges
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/spring.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/spring.py
new file mode 100644
index 000000000..300a7c66c
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/spring.py
@@ -0,0 +1,106 @@
+"""Dynamic-hint extractor for Spring DI patterns (Java/Kotlin)."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {"build", "target", "out", "node_modules", ".git", ".gradle", ".idea"}
+
+_TYPE_DECL_RE = re.compile(
+ r"\b(?:class|interface|record|enum)\s+([A-Z]\w*)"
+)
+_KOTLIN_TYPE_DECL_RE = re.compile(
+ r"\b(?:class|interface|object)\s+([A-Z]\w*)"
+)
+
+# applicationContext.getBean(Foo.class) / getBean("foo", Foo.class)
+_GETBEAN_CLASS_RE = re.compile(r"getBean\s*\(\s*(?:[\"'][^\"']*[\"']\s*,\s*)?([A-Z]\w*)\s*(?:\.class|::class(?:\.java)?)")
+# getBean("beanName") — name-based, can't resolve to a class file
+_GETBEAN_STRING_RE = re.compile(r"getBean\s*\(\s*[\"']([^\"']+)[\"']\s*\)")
+
+# @Bean factory return type — pick the line preceding @Bean for the method signature
+_BEAN_METHOD_RE = re.compile(
+ r"@Bean[^\n]*\n[^\n]*?\b(?:public\s+|private\s+|protected\s+|static\s+|final\s+)*"
+ r"([A-Z]\w*)\s+\w+\s*\(",
+)
+_BEAN_METHOD_KOTLIN_RE = re.compile(
+ r"@Bean[^\n]*\n[^\n]*?\bfun\s+\w+\s*\([^)]*\)\s*:\s*([A-Z]\w*)",
+)
+
+
+class SpringDynamicHints(DynamicHintExtractor):
+ """Discover Spring `getBean`/`@Bean` runtime-resolved dependencies."""
+
+ name = "spring"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ edges: list[DynamicEdge] = []
+
+ type_to_file: dict[str, str] = {}
+ sources: list[tuple[Path, str, str]] = [] # (path, text, lang)
+ repo_root_resolved = repo_root.resolve()
+ for ext, lang in ((".java", "java"), (".kt", "kotlin")):
+ for src in repo_root.rglob(f"*{ext}"):
+ try:
+ rel_path = src.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ rel = rel_path.as_posix()
+ sources.append((src, text, lang))
+ pattern = _KOTLIN_TYPE_DECL_RE if lang == "kotlin" else _TYPE_DECL_RE
+ for match in pattern.finditer(text):
+ type_to_file.setdefault(match.group(1), rel)
+
+ # Gate: only fire if any file imports org.springframework
+ if not any("org.springframework" in t for _, t, _ in sources):
+ return edges
+
+ for src, text, lang in sources:
+ try:
+ rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ continue
+
+ for match in _GETBEAN_CLASS_RE.finditer(text):
+ target = type_to_file.get(match.group(1))
+ if target and target != rel:
+ edges.append(
+ DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:get_bean",
+ )
+ )
+
+ for match in _GETBEAN_STRING_RE.finditer(text):
+ edges.append(
+ DynamicEdge(
+ source=rel,
+ target=f"external:bean:{match.group(1)}",
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:get_bean_string",
+ )
+ )
+
+ bean_re = _BEAN_METHOD_KOTLIN_RE if lang == "kotlin" else _BEAN_METHOD_RE
+ for match in bean_re.finditer(text):
+ target = type_to_file.get(match.group(1))
+ if target and target != rel:
+ edges.append(
+ DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:bean_factory",
+ )
+ )
+
+ return edges
diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/swift.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/swift.py
new file mode 100644
index 000000000..e0a6e5977
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/swift.py
@@ -0,0 +1,106 @@
+"""Dynamic-hint extractor for Swift reflective and selector patterns."""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+
+from .base import DynamicEdge, DynamicHintExtractor
+
+_SKIP_DIRS = {".build", "Pods", "DerivedData", ".git", "node_modules"}
+
+_NSCLASS_FROM_STRING_RE = re.compile(r"NSClassFromString\s*\(\s*[\"']([A-Z]\w*)[\"']")
+_NSSTRING_FROM_CLASS_RE = re.compile(r"NSStringFromClass\s*\(\s*([A-Z]\w*)")
+_SELECTOR_INIT_RE = re.compile(r"Selector\s*\(\s*[\"']([A-Za-z_]\w*)")
+_HASH_SELECTOR_RE = re.compile(r"#selector\s*\(\s*([A-Za-z_]\w*(?:\.[A-Za-z_]\w*)?)")
+# value(forKey: "name") / setValue(_, forKey: "name")
+_KVC_RE = re.compile(r"\bvalue\s*\(\s*forKey\s*:\s*[\"']([A-Za-z_]\w*)[\"']")
+
+_TYPE_DECL_RE = re.compile(
+ r"\b(?:class|struct|enum|actor|protocol)\s+([A-Z]\w*)"
+)
+_FUNC_DECL_RE = re.compile(r"\bfunc\s+([A-Za-z_]\w*)")
+
+
+class SwiftDynamicHints(DynamicHintExtractor):
+ """Discover Swift NSClassFromString / Selector / KVC dynamic dispatch."""
+
+ name = "swift"
+
+ def extract(self, repo_root: Path) -> list[DynamicEdge]:
+ edges: list[DynamicEdge] = []
+
+ type_to_file: dict[str, str] = {}
+ func_to_files: dict[str, list[str]] = {}
+ sources: list[tuple[Path, str]] = []
+ repo_root_resolved = repo_root.resolve()
+ for src in repo_root.rglob("*.swift"):
+ try:
+ rel_path = src.resolve().relative_to(repo_root_resolved)
+ except ValueError:
+ continue
+ if any(part in _SKIP_DIRS for part in rel_path.parts):
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ continue
+ rel = rel_path.as_posix()
+ sources.append((src, text))
+ for match in _TYPE_DECL_RE.finditer(text):
+ type_to_file.setdefault(match.group(1), rel)
+ for match in _FUNC_DECL_RE.finditer(text):
+ func_to_files.setdefault(match.group(1), []).append(rel)
+
+ for src, text in sources:
+ try:
+ rel = src.resolve().relative_to(repo_root.resolve()).as_posix()
+ except ValueError:
+ continue
+
+ for match in _NSCLASS_FROM_STRING_RE.finditer(text):
+ target = type_to_file.get(match.group(1))
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:nsclass_from_string",
+ ))
+
+ for match in _NSSTRING_FROM_CLASS_RE.finditer(text):
+ target = type_to_file.get(match.group(1))
+ if target and target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:nsstring_from_class",
+ ))
+
+ for match in _SELECTOR_INIT_RE.finditer(text):
+ for target in func_to_files.get(match.group(1), []):
+ if target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:selector",
+ ))
+
+ for match in _HASH_SELECTOR_RE.finditer(text):
+ name = match.group(1).rsplit(".", 1)[-1]
+ for target in func_to_files.get(name, []):
+ if target != rel:
+ edges.append(DynamicEdge(
+ source=rel, target=target,
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:hash_selector",
+ ))
+
+ for match in _KVC_RE.finditer(text):
+ edges.append(DynamicEdge(
+ source=rel,
+ target=f"external:swift_kvc:{match.group(1)}",
+ edge_type="dynamic_uses",
+ hint_source=f"{self.name}:kvc",
+ ))
+
+ return edges
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings.py b/packages/core/src/repowise/core/ingestion/extractors/bindings.py
deleted file mode 100644
index 90f94b0e1..000000000
--- a/packages/core/src/repowise/core/ingestion/extractors/bindings.py
+++ /dev/null
@@ -1,527 +0,0 @@
-"""Per-language import binding extraction."""
-
-from __future__ import annotations
-
-from pathlib import PurePosixPath
-
-from tree_sitter import Node
-
-from ..models import NamedBinding
-from .helpers import node_text
-
-
-def extract_import_bindings(
- stmt_node: Node, src: str, lang: str
-) -> tuple[list[str], list[NamedBinding]]:
- """Extract imported names and structured bindings from an import statement.
-
- Returns (imported_names, bindings) where imported_names is the backward-
- compatible list of local names and bindings carries alias/source detail.
- """
- if lang == "python":
- return extract_python_bindings(stmt_node, src)
- if lang in ("typescript", "javascript"):
- return extract_ts_js_bindings(stmt_node, src)
- if lang == "go":
- return extract_go_bindings(stmt_node, src)
- if lang == "rust":
- return extract_rust_bindings(stmt_node, src)
- if lang == "java":
- return extract_java_bindings(stmt_node, src)
- if lang in ("cpp", "c"):
- return extract_cpp_bindings(stmt_node, src)
- if lang == "kotlin":
- return extract_kotlin_bindings(stmt_node, src)
- if lang == "ruby":
- return extract_ruby_bindings(stmt_node, src)
- if lang == "csharp":
- return extract_csharp_bindings(stmt_node, src)
- if lang == "swift":
- return extract_swift_bindings(stmt_node, src)
- if lang == "scala":
- return extract_scala_bindings(stmt_node, src)
- if lang == "php":
- return extract_php_bindings(stmt_node, src)
- return [], []
-
-
-def extract_python_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from Python import/import_from statements."""
- names: list[str] = []
- bindings: list[NamedBinding] = []
- is_from_import = stmt_node.type == "import_from_statement"
- first_dotted_seen = False
-
- for child in stmt_node.children:
- if child.type == "wildcard_import":
- return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
-
- if child.type == "aliased_import":
- name_node = child.child_by_field_name("name") or (
- child.children[0] if child.children else None
- )
- alias_node = child.child_by_field_name("alias")
- if name_node:
- exported = node_text(name_node, src)
- local = node_text(alias_node, src) if alias_node else exported
- if is_from_import:
- # from X import Y as Z
- names.append(local)
- bindings.append(
- NamedBinding(local_name=local, exported_name=exported, source_file=None)
- )
- else:
- # import X.Y as Z — module alias
- bare = exported.split(".")[-1]
- local = node_text(alias_node, src) if alias_node else bare
- names.append(local)
- bindings.append(
- NamedBinding(
- local_name=local,
- exported_name=None,
- source_file=None,
- is_module_alias=True,
- )
- )
-
- elif child.type == "dotted_name":
- text = node_text(child, src)
- bare = text.split(".")[-1]
- if is_from_import and not first_dotted_seen:
- # First dotted_name in from-import is the module path — skip
- first_dotted_seen = True
- continue
- names.append(bare)
- if is_from_import:
- bindings.append(NamedBinding(local_name=bare, exported_name=bare, source_file=None))
- else:
- # import X.Y.Z — module alias
- bindings.append(
- NamedBinding(
- local_name=bare,
- exported_name=None,
- source_file=None,
- is_module_alias=True,
- )
- )
-
- return names, bindings
-
-
-def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from TypeScript/JavaScript import statements."""
- names: list[str] = []
- bindings: list[NamedBinding] = []
-
- for child in stmt_node.children:
- if child.type != "import_clause":
- continue
- for sub in child.children:
- if sub.type == "identifier":
- # default import: import React from 'react'
- local = node_text(sub, src)
- names.append(local)
- bindings.append(
- NamedBinding(local_name=local, exported_name="default", source_file=None)
- )
- elif sub.type == "named_imports":
- for spec in sub.children:
- if spec.type != "import_specifier":
- continue
- name_node = spec.child_by_field_name("name") or (
- spec.children[0] if spec.children else None
- )
- alias_node = spec.child_by_field_name("alias")
- if name_node:
- exported = node_text(name_node, src)
- local = node_text(alias_node, src) if alias_node else exported
- names.append(local)
- bindings.append(
- NamedBinding(local_name=local, exported_name=exported, source_file=None)
- )
- elif sub.type == "namespace_import":
- # import * as ns from 'mod'
- ns_name = None
- for ns_child in sub.children:
- if ns_child.type == "identifier":
- ns_name = node_text(ns_child, src)
- if ns_name:
- names.append(ns_name)
- bindings.append(
- NamedBinding(
- local_name=ns_name,
- exported_name=None,
- source_file=None,
- is_module_alias=True,
- )
- )
- else:
- names.append("*")
- bindings.append(
- NamedBinding(local_name="*", exported_name=None, source_file=None)
- )
-
- return names, bindings
-
-
-def extract_go_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from Go import specs."""
- # Go import_spec: optional alias identifier + string literal path
- alias_node = stmt_node.child_by_field_name("name")
- path_node = stmt_node.child_by_field_name("path")
-
- if path_node is None:
- # Fallback: find the first string literal child
- for child in stmt_node.children:
- if child.type == "interpreted_string_literal":
- path_node = child
- break
- if path_node is None:
- return [], []
-
- path_text = node_text(path_node, src).strip("\"'` ")
- default_name = path_text.rsplit("/", 1)[-1]
-
- if alias_node:
- alias = node_text(alias_node, src)
- if alias == ".":
- return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
- if alias == "_":
- return [], []
- return [alias], [
- NamedBinding(
- local_name=alias, exported_name=None, source_file=None, is_module_alias=True
- )
- ]
-
- return [default_name], [
- NamedBinding(
- local_name=default_name,
- exported_name=None,
- source_file=None,
- is_module_alias=True,
- )
- ]
-
-
-def extract_rust_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from Rust use declarations."""
- arg_node = stmt_node.child_by_field_name("argument")
- if arg_node is None:
- # Fallback: first meaningful child
- for child in stmt_node.children:
- if child.type not in ("use", ";", "pub", "visibility_modifier"):
- arg_node = child
- break
- if arg_node is None:
- return [], []
-
- names: list[str] = []
- bindings: list[NamedBinding] = []
- _parse_rust_use_tree(arg_node, src, names, bindings, depth=0)
- return names, bindings
-
-
-def _parse_rust_use_tree(
- node: Node,
- src: str,
- names: list[str],
- bindings: list[NamedBinding],
- depth: int,
-) -> None:
- """Recursively parse a Rust use-tree into named bindings."""
- if depth > 10:
- return
-
- if node.type == "use_as_clause":
- path_child = node.child_by_field_name("path") or (
- node.children[0] if node.children else None
- )
- alias_child = node.child_by_field_name("alias") or (
- node.children[-1] if len(node.children) >= 2 else None
- )
- if path_child and alias_child and path_child != alias_child:
- exported = node_text(path_child, src).rsplit("::", 1)[-1]
- local = node_text(alias_child, src)
- names.append(local)
- bindings.append(
- NamedBinding(local_name=local, exported_name=exported, source_file=None)
- )
- return
-
- if node.type == "use_wildcard":
- names.append("*")
- bindings.append(NamedBinding(local_name="*", exported_name=None, source_file=None))
- return
-
- if node.type == "use_list":
- for child in node.children:
- if child.type in ("{", "}", ","):
- continue
- _parse_rust_use_tree(child, src, names, bindings, depth + 1)
- return
-
- if node.type == "scoped_use_list":
- # e.g., std::collections::{HashMap, BTreeMap}
- for child in node.children:
- if child.type == "use_list":
- _parse_rust_use_tree(child, src, names, bindings, depth + 1)
- return
-
- # scoped_identifier or identifier — bare name, last segment
- text = node_text(node, src)
- bare = text.rsplit("::", 1)[-1]
- if bare and bare != "*":
- names.append(bare)
- bindings.append(NamedBinding(local_name=bare, exported_name=bare, source_file=None))
-
-
-def extract_java_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from Java import declarations."""
- # Java: import com.example.Foo; -> local_name="Foo"
- for child in stmt_node.children:
- if child.type == "scoped_identifier":
- full = node_text(child, src)
- local = full.rsplit(".", 1)[-1]
- if local == "*":
- return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
- return [local], [NamedBinding(local_name=local, exported_name=local, source_file=None)]
- if child.type == "asterisk":
- return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
- return [], []
-
-
-def extract_kotlin_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from Kotlin import declarations."""
- for child in stmt_node.children:
- if child.type == "qualified_identifier":
- full = node_text(child, src)
- parts = full.split(".")
- local = parts[-1]
- if local == "*":
- return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
- return [local], [NamedBinding(local_name=local, exported_name=local, source_file=None)]
- return [], []
-
-
-def extract_ruby_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from Ruby require/require_relative calls."""
- method_node = None
- for child in stmt_node.children:
- if child.type == "identifier":
- method_node = child
- break
- method_name = node_text(method_node, src) if method_node else ""
- if method_name not in ("require", "require_relative"):
- return [], []
-
- for child in stmt_node.children:
- if child.type == "argument_list":
- for arg in child.children:
- if arg.type == "string":
- for sub in arg.children:
- if sub.type == "string_content":
- path = node_text(sub, src)
- stem = PurePosixPath(path).stem
- return [stem], [
- NamedBinding(
- local_name=stem,
- exported_name=None,
- source_file=path,
- is_module_alias=True,
- )
- ]
- return [], []
-
-
-def extract_csharp_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from C# using directives.
-
- Recognises:
- using Foo; -> NamedBinding(local="Foo", exported="Foo")
- using Foo.Bar.Baz; -> NamedBinding(local="Baz", exported="Foo.Bar.Baz")
- using Alias = Foo.Bar.Type; -> NamedBinding(local="Alias", exported=..., is_module_alias=True)
- global using Foo; -> NamedBinding(..., is_global=True)
- using static Foo.Bar; -> NamedBinding(..., is_static_import=True)
- global using static Foo.Bar; -> both flags True
-
- The ``global`` and ``static`` modifiers appear as keyword child nodes
- of ``using_directive`` in tree-sitter-c-sharp >= 0.23.
- """
- alias: str | None = None
- namespace = ""
- is_global = False
- is_static = False
- saw_equals = False
- pending_identifier: str | None = None # the identifier seen before `=`, if any
-
- for child in stmt_node.children:
- # Modifier keywords / structural tokens.
- if not child.is_named:
- tok = node_text(child, src)
- if tok == "global":
- is_global = True
- continue
- if tok == "static":
- is_static = True
- continue
- if tok == "=":
- saw_equals = True
- if pending_identifier is not None:
- alias = pending_identifier
- pending_identifier = None
- continue
- continue
- # name_equals appears in some grammar versions as a wrapper for
- # `(identifier) =`. Older 0.23 grammars emit the identifier as a
- # bare sibling and the `=` as an anonymous token — handled above.
- if child.type == "name_equals":
- for sub in child.children:
- if sub.type == "identifier":
- alias = node_text(sub, src)
- continue
- if child.type == "identifier":
- text = node_text(child, src)
- if saw_equals:
- # Identifier on the right of `=` is the alias target.
- namespace = text
- else:
- # Could be the alias (if `=` follows) or a single-name namespace.
- # Stash it and decide once we know.
- pending_identifier = text
- continue
- if child.type == "qualified_name":
- namespace = node_text(child, src)
-
- # If we never saw `=`, the pending identifier (if any) is the namespace.
- if pending_identifier is not None and not namespace:
- namespace = pending_identifier
-
- if not namespace:
- return [], []
- local = alias if alias else namespace.rsplit(".", 1)[-1]
- return [local], [
- NamedBinding(
- local_name=local,
- exported_name=namespace,
- source_file=None,
- is_module_alias=alias is not None,
- is_global=is_global,
- is_static_import=is_static,
- )
- ]
-
-
-def extract_swift_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from Swift import declarations."""
- for child in stmt_node.children:
- if child.type == "identifier":
- full = node_text(child, src)
- local = full.split(".")[-1]
- return [local], [
- NamedBinding(
- local_name=local,
- exported_name=None,
- source_file=None,
- is_module_alias=True,
- )
- ]
- return [], []
-
-
-def extract_scala_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from Scala import declarations."""
- names: list[str] = []
- bindings: list[NamedBinding] = []
-
- # Get full import text, strip "import " prefix
- full_text = node_text(stmt_node, src).strip()
- if full_text.startswith("import "):
- full_text = full_text[7:].strip()
-
- # Check for selectors: import pkg.{A, B => C}
- has_selectors = False
- for child in stmt_node.children:
- if child.type == "namespace_selectors":
- has_selectors = True
- for sel_child in child.children:
- if sel_child.type == "arrow_renamed_identifier":
- # B => C
- parts = node_text(sel_child, src).split("=>")
- if len(parts) == 2:
- exported = parts[0].strip()
- local = parts[1].strip()
- names.append(local)
- bindings.append(
- NamedBinding(local_name=local, exported_name=exported, source_file=None)
- )
- elif sel_child.type == "identifier":
- local = node_text(sel_child, src)
- names.append(local)
- bindings.append(
- NamedBinding(local_name=local, exported_name=local, source_file=None)
- )
- elif child.type == "namespace_wildcard":
- has_selectors = True
- names.append("*")
- bindings.append(NamedBinding(local_name="*", exported_name=None, source_file=None))
-
- if not has_selectors:
- # Simple import: import pkg.ClassName — extract last segment
- parts = full_text.split(".")
- local = parts[-1].strip()
- if local and local != "_":
- names.append(local)
- bindings.append(NamedBinding(local_name=local, exported_name=local, source_file=None))
-
- return names, bindings
-
-
-def extract_php_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from PHP use declarations."""
- names: list[str] = []
- bindings: list[NamedBinding] = []
-
- for child in stmt_node.children:
- if child.type == "namespace_use_clause":
- qualified = ""
- alias = None
- saw_as = False
- for sub in child.children:
- if sub.type == "qualified_name":
- qualified = node_text(sub, src)
- elif sub.type == "as":
- saw_as = True
- elif sub.type == "name" and saw_as:
- alias = node_text(sub, src)
-
- if not qualified:
- continue
-
- # Get the last segment of the namespace path
- local = qualified.rsplit("\\", 1)[-1] if "\\" in qualified else qualified
- effective_local = alias if alias else local
- names.append(effective_local)
- bindings.append(
- NamedBinding(local_name=effective_local, exported_name=qualified, source_file=None)
- )
-
- return names, bindings
-
-
-def extract_cpp_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
- """Extract bindings from C/C++ ``#include`` directives."""
- for child in stmt_node.children:
- if child.type in ("system_lib_string", "string_literal"):
- raw = node_text(child, src).strip().strip('<>"')
- if raw:
- stem = PurePosixPath(raw).stem
- return [stem], [
- NamedBinding(
- local_name=stem,
- exported_name=None,
- source_file=raw,
- is_module_alias=True,
- )
- ]
- return [], []
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/__init__.py
new file mode 100644
index 000000000..738b9debc
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/__init__.py
@@ -0,0 +1,80 @@
+"""Per-language import-binding extraction.
+
+Public API:
+
+- ``extract_import_bindings`` — language-dispatching entry point used by
+ the parser. Returns ``(imported_names, bindings)`` where
+ ``imported_names`` is the backward-compatible list of local names and
+ ``bindings`` carries alias/source detail.
+- Each per-language ``extract_<lang>_bindings`` is also re-exported so
+ callers (e.g. tests) can drive a single language directly.
+
+Add a new language by creating ``<lang>.py`` with an
+``extract_<lang>_bindings`` function and wiring it into the
+``_DISPATCH`` map below.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from .cpp import extract_cpp_bindings
+from .csharp import extract_csharp_bindings
+from .go import extract_go_bindings
+from .java import extract_java_bindings
+from .kotlin import extract_kotlin_bindings
+from .php import extract_php_bindings
+from .python import extract_python_bindings
+from .ruby import extract_ruby_bindings
+from .rust import extract_rust_bindings
+from .scala import extract_scala_bindings
+from .swift import extract_swift_bindings
+from .ts_js import extract_ts_js_bindings
+
+
+_DISPATCH: dict[str, Callable[[Node, str], tuple[list[str], list[NamedBinding]]]] = {
+ "python": extract_python_bindings,
+ "typescript": extract_ts_js_bindings,
+ "javascript": extract_ts_js_bindings,
+ "go": extract_go_bindings,
+ "rust": extract_rust_bindings,
+ "java": extract_java_bindings,
+ "cpp": extract_cpp_bindings,
+ "c": extract_cpp_bindings,
+ "kotlin": extract_kotlin_bindings,
+ "ruby": extract_ruby_bindings,
+ "csharp": extract_csharp_bindings,
+ "swift": extract_swift_bindings,
+ "scala": extract_scala_bindings,
+ "php": extract_php_bindings,
+}
+
+
+def extract_import_bindings(
+ stmt_node: Node, src: str, lang: str
+) -> tuple[list[str], list[NamedBinding]]:
+ """Extract imported names and structured bindings from an import statement."""
+ extractor = _DISPATCH.get(lang)
+ if extractor is None:
+ return [], []
+ return extractor(stmt_node, src)
+
+
+__all__ = [
+ "extract_cpp_bindings",
+ "extract_csharp_bindings",
+ "extract_go_bindings",
+ "extract_import_bindings",
+ "extract_java_bindings",
+ "extract_kotlin_bindings",
+ "extract_php_bindings",
+ "extract_python_bindings",
+ "extract_ruby_bindings",
+ "extract_rust_bindings",
+ "extract_scala_bindings",
+ "extract_swift_bindings",
+ "extract_ts_js_bindings",
+]
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/cpp.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/cpp.py
new file mode 100644
index 000000000..c54f67a2a
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/cpp.py
@@ -0,0 +1,28 @@
+"""C / C++ include-binding extraction."""
+
+from __future__ import annotations
+
+from pathlib import PurePosixPath
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_cpp_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from C/C++ ``#include`` directives."""
+ for child in stmt_node.children:
+ if child.type in ("system_lib_string", "string_literal"):
+ raw = node_text(child, src).strip().strip('<>"')
+ if raw:
+ stem = PurePosixPath(raw).stem
+ return [stem], [
+ NamedBinding(
+ local_name=stem,
+ exported_name=None,
+ source_file=raw,
+ is_module_alias=True,
+ )
+ ]
+ return [], []
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/csharp.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/csharp.py
new file mode 100644
index 000000000..4f4c783b7
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/csharp.py
@@ -0,0 +1,75 @@
+"""C# import-binding extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_csharp_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from C# using directives.
+
+ Recognises:
+ using Foo; -> NamedBinding(local="Foo", exported="Foo")
+ using Foo.Bar.Baz; -> NamedBinding(local="Baz", exported="Foo.Bar.Baz")
+ using Alias = Foo.Bar.Type; -> NamedBinding(local="Alias", ..., is_module_alias=True)
+ global using Foo; -> NamedBinding(..., is_global=True)
+ using static Foo.Bar; -> NamedBinding(..., is_static_import=True)
+ global using static Foo.Bar; -> both flags True
+ """
+ alias: str | None = None
+ namespace = ""
+ is_global = False
+ is_static = False
+ saw_equals = False
+ pending_identifier: str | None = None
+
+ for child in stmt_node.children:
+ if not child.is_named:
+ tok = node_text(child, src)
+ if tok == "global":
+ is_global = True
+ continue
+ if tok == "static":
+ is_static = True
+ continue
+ if tok == "=":
+ saw_equals = True
+ if pending_identifier is not None:
+ alias = pending_identifier
+ pending_identifier = None
+ continue
+ continue
+ if child.type == "name_equals":
+ for sub in child.children:
+ if sub.type == "identifier":
+ alias = node_text(sub, src)
+ continue
+ if child.type == "identifier":
+ text = node_text(child, src)
+ if saw_equals:
+ namespace = text
+ else:
+ pending_identifier = text
+ continue
+ if child.type == "qualified_name":
+ namespace = node_text(child, src)
+
+ if pending_identifier is not None and not namespace:
+ namespace = pending_identifier
+
+ if not namespace:
+ return [], []
+ local = alias if alias else namespace.rsplit(".", 1)[-1]
+ return [local], [
+ NamedBinding(
+ local_name=local,
+ exported_name=namespace,
+ source_file=None,
+ is_module_alias=alias is not None,
+ is_global=is_global,
+ is_static_import=is_static,
+ )
+ ]
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/go.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/go.py
new file mode 100644
index 000000000..c2055fa24
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/go.py
@@ -0,0 +1,46 @@
+"""Go import-binding extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_go_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Go import specs."""
+ alias_node = stmt_node.child_by_field_name("name")
+ path_node = stmt_node.child_by_field_name("path")
+
+ if path_node is None:
+ for child in stmt_node.children:
+ if child.type == "interpreted_string_literal":
+ path_node = child
+ break
+ if path_node is None:
+ return [], []
+
+ path_text = node_text(path_node, src).strip("\"'` ")
+ default_name = path_text.rsplit("/", 1)[-1]
+
+ if alias_node:
+ alias = node_text(alias_node, src)
+ if alias == ".":
+ return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
+ if alias == "_":
+ return [], []
+ return [alias], [
+ NamedBinding(
+ local_name=alias, exported_name=None, source_file=None, is_module_alias=True
+ )
+ ]
+
+ return [default_name], [
+ NamedBinding(
+ local_name=default_name,
+ exported_name=None,
+ source_file=None,
+ is_module_alias=True,
+ )
+ ]
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/java.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/java.py
new file mode 100644
index 000000000..6ee5e3de5
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/java.py
@@ -0,0 +1,22 @@
+"""Java import-binding extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_java_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Java import declarations."""
+ for child in stmt_node.children:
+ if child.type == "scoped_identifier":
+ full = node_text(child, src)
+ local = full.rsplit(".", 1)[-1]
+ if local == "*":
+ return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
+ return [local], [NamedBinding(local_name=local, exported_name=local, source_file=None)]
+ if child.type == "asterisk":
+ return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
+ return [], []
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/kotlin.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/kotlin.py
new file mode 100644
index 000000000..096a59cbe
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/kotlin.py
@@ -0,0 +1,21 @@
+"""Kotlin import-binding extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_kotlin_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Kotlin import declarations."""
+ for child in stmt_node.children:
+ if child.type == "qualified_identifier":
+ full = node_text(child, src)
+ parts = full.split(".")
+ local = parts[-1]
+ if local == "*":
+ return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
+ return [local], [NamedBinding(local_name=local, exported_name=local, source_file=None)]
+ return [], []
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/php.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/php.py
new file mode 100644
index 000000000..75a420cad
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/php.py
@@ -0,0 +1,41 @@
+"""PHP import-binding extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_php_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from PHP use declarations."""
+ names: list[str] = []
+ bindings: list[NamedBinding] = []
+
+ for child in stmt_node.children:
+ if child.type == "namespace_use_clause":
+ qualified = ""
+ alias = None
+ saw_as = False
+ for sub in child.children:
+ if sub.type == "qualified_name":
+ qualified = node_text(sub, src)
+ elif sub.type == "as":
+ saw_as = True
+ elif sub.type == "name" and saw_as:
+ alias = node_text(sub, src)
+
+ if not qualified:
+ continue
+
+ local = qualified.rsplit("\\", 1)[-1] if "\\" in qualified else qualified
+ effective_local = alias if alias else local
+ names.append(effective_local)
+ bindings.append(
+ NamedBinding(
+ local_name=effective_local, exported_name=qualified, source_file=None
+ )
+ )
+
+ return names, bindings
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py
new file mode 100644
index 000000000..2b444739f
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/python.py
@@ -0,0 +1,67 @@
+"""Python import-binding extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_python_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Python import/import_from statements."""
+ names: list[str] = []
+ bindings: list[NamedBinding] = []
+ is_from_import = stmt_node.type == "import_from_statement"
+ first_dotted_seen = False
+
+ for child in stmt_node.children:
+ if child.type == "wildcard_import":
+ return ["*"], [NamedBinding(local_name="*", exported_name=None, source_file=None)]
+
+ if child.type == "aliased_import":
+ name_node = child.child_by_field_name("name") or (
+ child.children[0] if child.children else None
+ )
+ alias_node = child.child_by_field_name("alias")
+ if name_node:
+ exported = node_text(name_node, src)
+ local = node_text(alias_node, src) if alias_node else exported
+ if is_from_import:
+ names.append(local)
+ bindings.append(
+ NamedBinding(local_name=local, exported_name=exported, source_file=None)
+ )
+ else:
+ bare = exported.split(".")[-1]
+ local = node_text(alias_node, src) if alias_node else bare
+ names.append(local)
+ bindings.append(
+ NamedBinding(
+ local_name=local,
+ exported_name=None,
+ source_file=None,
+ is_module_alias=True,
+ )
+ )
+
+ elif child.type == "dotted_name":
+ text = node_text(child, src)
+ bare = text.split(".")[-1]
+ if is_from_import and not first_dotted_seen:
+ first_dotted_seen = True
+ continue
+ names.append(bare)
+ if is_from_import:
+ bindings.append(NamedBinding(local_name=bare, exported_name=bare, source_file=None))
+ else:
+ bindings.append(
+ NamedBinding(
+ local_name=bare,
+ exported_name=None,
+ source_file=None,
+ is_module_alias=True,
+ )
+ )
+
+ return names, bindings
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/ruby.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/ruby.py
new file mode 100644
index 000000000..85a0ce7df
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/ruby.py
@@ -0,0 +1,40 @@
+"""Ruby import-binding extraction."""
+
+from __future__ import annotations
+
+from pathlib import PurePosixPath
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_ruby_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Ruby require/require_relative calls."""
+ method_node = None
+ for child in stmt_node.children:
+ if child.type == "identifier":
+ method_node = child
+ break
+ method_name = node_text(method_node, src) if method_node else ""
+ if method_name not in ("require", "require_relative"):
+ return [], []
+
+ for child in stmt_node.children:
+ if child.type == "argument_list":
+ for arg in child.children:
+ if arg.type == "string":
+ for sub in arg.children:
+ if sub.type == "string_content":
+ path = node_text(sub, src)
+ stem = PurePosixPath(path).stem
+ return [stem], [
+ NamedBinding(
+ local_name=stem,
+ exported_name=None,
+ source_file=path,
+ is_module_alias=True,
+ )
+ ]
+ return [], []
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/rust.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/rust.py
new file mode 100644
index 000000000..11418fa78
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/rust.py
@@ -0,0 +1,77 @@
+"""Rust import-binding extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_rust_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Rust use declarations."""
+ arg_node = stmt_node.child_by_field_name("argument")
+ if arg_node is None:
+ for child in stmt_node.children:
+ if child.type not in ("use", ";", "pub", "visibility_modifier"):
+ arg_node = child
+ break
+ if arg_node is None:
+ return [], []
+
+ names: list[str] = []
+ bindings: list[NamedBinding] = []
+ _parse_rust_use_tree(arg_node, src, names, bindings, depth=0)
+ return names, bindings
+
+
+def _parse_rust_use_tree(
+ node: Node,
+ src: str,
+ names: list[str],
+ bindings: list[NamedBinding],
+ depth: int,
+) -> None:
+ """Recursively parse a Rust use-tree into named bindings."""
+ if depth > 10:
+ return
+
+ if node.type == "use_as_clause":
+ path_child = node.child_by_field_name("path") or (
+ node.children[0] if node.children else None
+ )
+ alias_child = node.child_by_field_name("alias") or (
+ node.children[-1] if len(node.children) >= 2 else None
+ )
+ if path_child and alias_child and path_child != alias_child:
+ exported = node_text(path_child, src).rsplit("::", 1)[-1]
+ local = node_text(alias_child, src)
+ names.append(local)
+ bindings.append(
+ NamedBinding(local_name=local, exported_name=exported, source_file=None)
+ )
+ return
+
+ if node.type == "use_wildcard":
+ names.append("*")
+ bindings.append(NamedBinding(local_name="*", exported_name=None, source_file=None))
+ return
+
+ if node.type == "use_list":
+ for child in node.children:
+ if child.type in ("{", "}", ","):
+ continue
+ _parse_rust_use_tree(child, src, names, bindings, depth + 1)
+ return
+
+ if node.type == "scoped_use_list":
+ for child in node.children:
+ if child.type == "use_list":
+ _parse_rust_use_tree(child, src, names, bindings, depth + 1)
+ return
+
+ text = node_text(node, src)
+ bare = text.rsplit("::", 1)[-1]
+ if bare and bare != "*":
+ names.append(bare)
+ bindings.append(NamedBinding(local_name=bare, exported_name=bare, source_file=None))
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/scala.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/scala.py
new file mode 100644
index 000000000..adca0d269
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/scala.py
@@ -0,0 +1,54 @@
+"""Scala import-binding extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_scala_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Scala import declarations."""
+ names: list[str] = []
+ bindings: list[NamedBinding] = []
+
+ full_text = node_text(stmt_node, src).strip()
+ if full_text.startswith("import "):
+ full_text = full_text[7:].strip()
+
+ has_selectors = False
+ for child in stmt_node.children:
+ if child.type == "namespace_selectors":
+ has_selectors = True
+ for sel_child in child.children:
+ if sel_child.type == "arrow_renamed_identifier":
+ parts = node_text(sel_child, src).split("=>")
+ if len(parts) == 2:
+ exported = parts[0].strip()
+ local = parts[1].strip()
+ names.append(local)
+ bindings.append(
+ NamedBinding(
+ local_name=local, exported_name=exported, source_file=None
+ )
+ )
+ elif sel_child.type == "identifier":
+ local = node_text(sel_child, src)
+ names.append(local)
+ bindings.append(
+ NamedBinding(local_name=local, exported_name=local, source_file=None)
+ )
+ elif child.type == "namespace_wildcard":
+ has_selectors = True
+ names.append("*")
+ bindings.append(NamedBinding(local_name="*", exported_name=None, source_file=None))
+
+ if not has_selectors:
+ parts = full_text.split(".")
+ local = parts[-1].strip()
+ if local and local != "_":
+ names.append(local)
+ bindings.append(NamedBinding(local_name=local, exported_name=local, source_file=None))
+
+ return names, bindings
diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings/swift.py b/packages/core/src/repowise/core/ingestion/extractors/bindings/swift.py
new file mode 100644
index 000000000..abcd8fe97
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/swift.py
@@ -0,0 +1,25 @@
+"""Swift import-binding extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_swift_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from Swift import declarations."""
+ for child in stmt_node.children:
+ if child.type == "identifier":
+ full = node_text(child, src)
+ local = full.split(".")[-1]
+ return [local], [
+ NamedBinding(
+ local_name=local,
+ exported_name=None,
+ source_file=None,
+ is_module_alias=True,
+ )
+ ]
+ return [], []
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
new file mode 100644
index 000000000..20e73d0f5
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings/ts_js.py
@@ -0,0 +1,64 @@
+"""TypeScript / JavaScript import-binding extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import NamedBinding
+from ..helpers import node_text
+
+
+def extract_ts_js_bindings(stmt_node: Node, src: str) -> tuple[list[str], list[NamedBinding]]:
+ """Extract bindings from TypeScript/JavaScript import statements."""
+ names: list[str] = []
+ bindings: list[NamedBinding] = []
+
+ for child in stmt_node.children:
+ if child.type != "import_clause":
+ continue
+ for sub in child.children:
+ if sub.type == "identifier":
+ local = node_text(sub, src)
+ names.append(local)
+ bindings.append(
+ NamedBinding(local_name=local, exported_name="default", source_file=None)
+ )
+ elif sub.type == "named_imports":
+ for spec in sub.children:
+ if spec.type != "import_specifier":
+ continue
+ name_node = spec.child_by_field_name("name") or (
+ spec.children[0] if spec.children else None
+ )
+ alias_node = spec.child_by_field_name("alias")
+ if name_node:
+ exported = node_text(name_node, src)
+ local = node_text(alias_node, src) if alias_node else exported
+ names.append(local)
+ bindings.append(
+ NamedBinding(
+ local_name=local, exported_name=exported, source_file=None
+ )
+ )
+ elif sub.type == "namespace_import":
+ ns_name = None
+ for ns_child in sub.children:
+ if ns_child.type == "identifier":
+ ns_name = node_text(ns_child, src)
+ if ns_name:
+ names.append(ns_name)
+ bindings.append(
+ NamedBinding(
+ local_name=ns_name,
+ exported_name=None,
+ source_file=None,
+ is_module_alias=True,
+ )
+ )
+ else:
+ names.append("*")
+ bindings.append(
+ NamedBinding(local_name="*", exported_name=None, source_file=None)
+ )
+
+ return names, bindings
diff --git a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
index 651e5fc43..a834b33fb 100644
--- a/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
+++ b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py
@@ -175,6 +175,35 @@ def extract_module_docstring(root: Node, src: str, lang: str) -> str | None:
):
break
+ elif lang == "java":
+ for child in root.children:
+ if child.type in ("comment", "block_comment", "line_comment"):
+ text = node_text(child, src).strip()
+ if text.startswith("/**"):
+ return clean_jsdoc(text)
+ elif child.type not in ("comment", "package_declaration", "import_declaration"):
+ break
+
+ elif lang == "luau":
+ # --[[ block comment ]] or run of leading --- comments
+ triple_dash_lines: list[str] = []
+ for child in root.children:
+ if child.type == "comment":
+ text = node_text(child, src).strip()
+ if text.startswith("--[["):
+ inner = text[4:]
+ if inner.endswith("]]"):
+ inner = inner[:-2]
+ return inner.strip()
+ if text.startswith("---"):
+ triple_dash_lines.append(text.lstrip("- ").strip())
+ continue
+ continue
+ else:
+ break
+ if triple_dash_lines:
+ return "\n".join(triple_dash_lines)
+
return None
@@ -277,6 +306,31 @@ def extract_symbol_docstring(def_node: Node, src: str, lang: str) -> str | None:
# PHPDoc: /** ... */
return find_preceding_block_comment(def_node, src, "/**")
+ elif lang == "luau":
+ # Luau: --[[ block ]] or --- triple-dash lines preceding the symbol
+ parent = def_node.parent
+ if parent is None:
+ return None
+ siblings = list(parent.children)
+ idx = next((i for i, s in enumerate(siblings) if s.id == def_node.id), -1)
+ if idx <= 0:
+ return None
+ lines: list[str] = []
+ i = idx - 1
+ while i >= 0 and siblings[i].type == "comment":
+ text = node_text(siblings[i], src).strip()
+ if text.startswith("--[["):
+ inner = text[4:]
+ if inner.endswith("]]"):
+ inner = inner[:-2]
+ return inner.strip()
+ if text.startswith("---"):
+ lines.insert(0, text.lstrip("- ").strip())
+ i -= 1
+ else:
+ break
+ return "\n".join(lines) if lines else None
+
return None
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage.py b/packages/core/src/repowise/core/ingestion/extractors/heritage.py
deleted file mode 100644
index fdbd0a025..000000000
--- a/packages/core/src/repowise/core/ingestion/extractors/heritage.py
+++ /dev/null
@@ -1,623 +0,0 @@
-"""Per-language heritage (inheritance/interface/trait) extraction."""
-
-from __future__ import annotations
-
-from collections.abc import Callable
-
-from tree_sitter import Node
-
-from ..languages.registry import REGISTRY as _LANG_REGISTRY
-from ..models import HeritageRelation
-from .helpers import node_text
-
-
-def heritage_node_types_for(lang: str) -> frozenset[str]:
- """Return the set of AST node types that can carry heritage info for *lang*."""
- spec = _LANG_REGISTRY.get(lang)
- return spec.heritage_node_types if spec else frozenset()
-
-
-def extract_heritage(
- tree: object,
- query: object,
- config: object,
- file_info: object,
- src: str,
- *,
- run_query: Callable,
-) -> list[HeritageRelation]:
- """Extract inheritance/implementation relationships from class definitions.
-
- Walks the same @symbol.def captures used by _extract_symbols, extracting
- superclass/interface/trait information from the definition AST nodes.
- """
- if query is None:
- return []
-
- lang = file_info.language # type: ignore[attr-defined]
- heritage_types = heritage_node_types_for(lang)
- if not heritage_types:
- return []
-
- from ..language_data import get_builtin_parents
-
- _parent_builtins = get_builtin_parents(lang)
-
- relations: list[HeritageRelation] = []
- seen: set[tuple[int, str]] = set()
-
- for capture_dict in run_query(query, tree.root_node): # type: ignore[attr-defined]
- def_nodes = capture_dict.get("symbol.def", [])
- name_nodes = capture_dict.get("symbol.name", [])
-
- if not def_nodes or not name_nodes:
- continue
-
- def_node = def_nodes[0]
- if def_node.type not in heritage_types:
- continue
-
- name = node_text(name_nodes[0], src)
- if not name:
- continue
-
- line = def_node.start_point[0] + 1
- dedup_key = (line, name)
- if dedup_key in seen:
- continue
- seen.add(dedup_key)
-
- extractor = HERITAGE_EXTRACTORS.get(lang)
- if extractor:
- extractor(def_node, name, line, src, relations)
-
- # Filter out builtin/stdlib parent types
- if _parent_builtins:
- relations = [r for r in relations if r.parent_name not in _parent_builtins]
-
- return relations
-
-
-# ---------------------------------------------------------------------------
-# Per-language heritage extractors
-# ---------------------------------------------------------------------------
-
-
-def _extract_python_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """Python: class Foo(Bar, Baz, metaclass=Meta)."""
- superclasses = def_node.child_by_field_name("superclasses")
- if superclasses is None:
- for child in def_node.children:
- if child.type == "argument_list":
- superclasses = child
- break
- if superclasses is None:
- return
-
- for child in superclasses.children:
- if child.type in ("(", ")", ","):
- continue
- if child.type == "keyword_argument":
- continue
- parent = node_text(child, src).strip()
- if parent:
- bare = parent.split(".")[-1]
- out.append(
- HeritageRelation(child_name=name, parent_name=bare, kind="extends", line=line)
- )
-
-
-def _extract_ts_js_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """TypeScript/JavaScript: class Foo extends Bar implements IFoo, IBar."""
- for child in def_node.children:
- if child.type == "class_heritage":
- for clause in child.children:
- if clause.type == "extends_clause":
- for type_node in clause.children:
- if type_node.type in ("extends", ","):
- continue
- parent = node_text(type_node, src).strip()
- if parent:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="extends",
- line=line,
- )
- )
- elif clause.type == "implements_clause":
- for type_node in clause.children:
- if type_node.type in ("implements", ","):
- continue
- parent = node_text(type_node, src).strip()
- if parent:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="implements",
- line=line,
- )
- )
- # interface extends: interface Foo extends Bar
- if child.type == "extends_type_clause":
- for type_node in child.children:
- if type_node.type in ("extends", ","):
- continue
- parent = node_text(type_node, src).strip()
- if parent:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="extends",
- line=line,
- )
- )
-
-
-def _extract_java_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """Java: class Foo extends Bar implements IFoo, IBar."""
- superclass = def_node.child_by_field_name("superclass")
- if superclass:
- parent = node_text(superclass, src).strip()
- parent = parent.removeprefix("extends").strip()
- if parent:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent.split(".")[-1],
- kind="extends",
- line=line,
- )
- )
-
- interfaces = def_node.child_by_field_name("interfaces")
- if interfaces:
- for child in interfaces.children:
- if child.type in ("implements", "extends", ",", "type_list"):
- if child.type == "type_list":
- for type_node in child.children:
- if type_node.type != ",":
- parent = node_text(type_node, src).strip().split(".")[-1]
- if parent:
- kind = (
- "implements"
- if def_node.type == "class_declaration"
- else "extends"
- )
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind=kind,
- line=line,
- )
- )
- continue
- parent = node_text(child, src).strip().split(".")[-1]
- if parent and parent not in ("implements", "extends"):
- kind = "implements" if def_node.type == "class_declaration" else "extends"
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind=kind,
- line=line,
- )
- )
-
-
-def _extract_go_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """Go: struct embedding (type Foo struct { Bar; baz.Qux })."""
- type_node = def_node.child_by_field_name("type")
- if type_node is None:
- return
-
- if type_node.type == "struct_type":
- body = type_node.child_by_field_name("body") or type_node
- if body is None:
- return
- for field_decl in body.children:
- if field_decl.type != "field_declaration":
- continue
- name_node = field_decl.child_by_field_name("name")
- type_child = field_decl.child_by_field_name("type")
- if name_node is None and type_child is not None:
- parent = node_text(type_child, src).strip().lstrip("*")
- bare = parent.split(".")[-1]
- if bare:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=bare,
- kind="mixin",
- line=line,
- )
- )
-
- elif type_node.type == "interface_type":
- for child in type_node.children:
- if child.type in ("{", "}", "\n"):
- continue
- if child.type in ("type_identifier", "qualified_type"):
- parent = node_text(child, src).strip()
- bare = parent.split(".")[-1]
- if bare:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=bare,
- kind="extends",
- line=line,
- )
- )
-
-
-def _extract_rust_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """Rust: impl Trait for Type, trait Foo: Bar + Baz, #[derive(Trait)]."""
- if def_node.type == "impl_item":
- trait_node = def_node.child_by_field_name("trait")
- type_node = def_node.child_by_field_name("type")
- if trait_node and type_node:
- trait_name = node_text(trait_node, src).strip().rsplit("::", 1)[-1]
- type_name = node_text(type_node, src).strip()
- if trait_name and type_name:
- out.append(
- HeritageRelation(
- child_name=type_name,
- parent_name=trait_name,
- kind="trait_impl",
- line=line,
- )
- )
-
- elif def_node.type == "trait_item":
- bounds = def_node.child_by_field_name("bounds")
- if bounds:
- for child in bounds.children:
- if child.type in ("+", ":"):
- continue
- parent = node_text(child, src).strip().rsplit("::", 1)[-1]
- if parent:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="extends",
- line=line,
- )
- )
-
- elif def_node.type in ("struct_item", "enum_item"):
- # Check preceding siblings for #[derive(Trait1, Trait2)]
- prev = def_node.prev_named_sibling
- while prev is not None and prev.type == "attribute_item":
- attr_text = node_text(prev, src).strip()
- if "derive(" in attr_text:
- # Extract trait names from token_tree
- for child in prev.children:
- if child.type == "attribute":
- for sub in child.children:
- if sub.type == "token_tree":
- for tok in sub.children:
- if tok.type == "identifier":
- trait_name = node_text(tok, src).strip()
- if trait_name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=trait_name,
- kind="derive",
- line=line,
- )
- )
- prev = prev.prev_named_sibling
-
-
-def _extract_cpp_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """C++: class Foo : public Bar, protected Baz."""
- for child in def_node.children:
- if child.type == "base_class_clause":
- for base in child.children:
- if base.type in (":", ","):
- continue
- text = node_text(base, src).strip()
- for prefix in ("public", "protected", "private", "virtual"):
- text = text.removeprefix(prefix).strip()
- bare = text.split("::")[-1].strip()
- if bare:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=bare,
- kind="extends",
- line=line,
- )
- )
-
-
-def _extract_kotlin_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """Kotlin: class Foo : Bar(), IFoo."""
- for child in def_node.children:
- if child.type == "delegation_specifier":
- for delegate in child.children:
- text = node_text(delegate, src).strip()
- bare = text.split("(")[0].split(".")[-1].strip()
- if bare and bare != name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=bare,
- kind="extends",
- line=line,
- )
- )
- elif child.type == "delegation_specifiers":
- for delegate in child.children:
- if delegate.type in (":", ","):
- continue
- text = node_text(delegate, src).strip()
- bare = text.split("(")[0].split(".")[-1].strip()
- if bare and bare != name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=bare,
- kind="extends",
- line=line,
- )
- )
-
-
-def _extract_ruby_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """Ruby: class Foo < Bar; include Mod; extend Mod; prepend Mod."""
- superclass = def_node.child_by_field_name("superclass")
- if superclass:
- parent = node_text(superclass, src).strip()
- parent = parent.removeprefix("<").strip()
- bare = parent.split("::")[-1]
- if bare:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=bare,
- kind="extends",
- line=line,
- )
- )
-
- # include/extend/prepend — call nodes inside body_statement
- _mixin_methods = {"include", "extend", "prepend"}
- for child in def_node.children:
- if child.type == "body_statement":
- for stmt in child.children:
- if stmt.type != "call":
- continue
- method_node = stmt.child_by_field_name("method")
- if method_node is None:
- # Fallback: first identifier child
- for sc in stmt.children:
- if sc.type == "identifier":
- method_node = sc
- break
- if method_node is None:
- continue
- method_name = node_text(method_node, src).strip()
- if method_name not in _mixin_methods:
- continue
- args = stmt.child_by_field_name("arguments")
- if args is None:
- for sc in stmt.children:
- if sc.type == "argument_list":
- args = sc
- break
- if args is None:
- continue
- for arg in args.children:
- if arg.type == "constant":
- mixin_name = node_text(arg, src).strip().split("::")[-1]
- if mixin_name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=mixin_name,
- kind="mixin",
- line=stmt.start_point[0] + 1,
- )
- )
-
-
-def _extract_swift_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """Swift: ``class Foo: Bar, Protocol1`` — inheritance via ``:`` separator."""
- for child in def_node.children:
- if child.type == "inheritance_specifier":
- for type_child in child.children:
- if type_child.type == "user_type":
- for id_node in type_child.children:
- if id_node.type == "type_identifier":
- parent = node_text(id_node, src).strip()
- if parent and parent != name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="extends",
- line=line,
- )
- )
-
-
-def _extract_csharp_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """C#: ``class Foo : Bar, IFoo`` and ``record Point(...) : BaseRecord(...)``.
-
- Classification heuristic — C# uses a single ``base_list`` with no syntactic
- distinction between ``extends`` (the optional single base class) and
- ``implements`` (zero or more interfaces). We classify by:
-
- 1. The first non-interface-named base is the extends target. C#
- requires the base class to come first when present, so position
- is a strong hint.
- 2. Names matching the I[A-Z]... convention or known framework
- interfaces (``System.IDisposable`` etc.) are treated as
- ``implements``.
- 3. Records can also appear in the base list with an argument list:
- ``record Point(int X) : Base(X)`` — the ``argument_list`` child
- is ignored, only the type identifier matters.
-
- The classification is best-effort. A future post-pass that resolves
- each parent_name to its declared kind (class vs interface) could
- refine this.
- """
- # Index children for record primary-constructor base call.
- base_list = None
- for child in def_node.children:
- if child.type == "base_list":
- base_list = child
- break
- if base_list is None:
- return
-
- seen_extends = False # Only the first non-interface-looking base counts as extends.
- for base in base_list.children:
- if base.type in (":", ",") or not base.is_named:
- continue
- # Records: `: Base(X, Y)` is a primary_constructor_base_type wrapping
- # the type name and an argument list. Skip the argument list.
- if base.type == "argument_list":
- continue
- text = node_text(base, src).strip()
- # Strip generic args and outer namespace qualification.
- bare = text.split("<")[0].split("(")[0].strip()
- bare = bare.rsplit(".", 1)[-1].strip()
- if not bare or bare == name:
- continue
- looks_interface = bare.startswith("I") and len(bare) > 1 and bare[1].isupper()
- if looks_interface or seen_extends:
- kind = "implements"
- else:
- kind = "extends"
- seen_extends = True
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=bare,
- kind=kind,
- line=line,
- )
- )
-
-
-def _extract_scala_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """Scala: ``class Foo extends Bar with Trait1 with Trait2``."""
- for child in def_node.children:
- if child.type == "extends_clause":
- saw_with = False
- for sub in child.children:
- if sub.type == "extends":
- continue
- if sub.type == "with":
- saw_with = True
- continue
- if sub.type == "type_identifier":
- parent = node_text(sub, src).strip()
- if parent and parent != name:
- kind = "implements" if saw_with else "extends"
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind=kind,
- line=line,
- )
- )
-
-
-def _extract_php_heritage(
- def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
-) -> None:
- """PHP: ``class Foo extends Bar implements IFoo, IBar; use TraitName;``."""
- for child in def_node.children:
- if child.type == "base_clause":
- for sub in child.children:
- if sub.type == "name":
- parent = node_text(sub, src).strip()
- if parent and parent != name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="extends",
- line=line,
- )
- )
- elif child.type == "class_interface_clause":
- for sub in child.children:
- if sub.type == "name":
- parent = node_text(sub, src).strip()
- if parent and parent != name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=parent,
- kind="implements",
- line=line,
- )
- )
- elif child.type == "declaration_list":
- # use TraitName; inside class body
- for stmt in child.children:
- if stmt.type == "use_declaration":
- for sub in stmt.children:
- if sub.type == "name":
- trait_name = node_text(sub, src).strip()
- if trait_name and trait_name != name:
- out.append(
- HeritageRelation(
- child_name=name,
- parent_name=trait_name,
- kind="mixin",
- line=stmt.start_point[0] + 1,
- )
- )
-
-
-HERITAGE_EXTRACTORS: dict[str, Callable[..., None]] = {
- "python": _extract_python_heritage,
- "typescript": _extract_ts_js_heritage,
- "javascript": _extract_ts_js_heritage,
- "java": _extract_java_heritage,
- "go": _extract_go_heritage,
- "rust": _extract_rust_heritage,
- "cpp": _extract_cpp_heritage,
- "c": lambda *_: None,
- "kotlin": _extract_kotlin_heritage,
- "ruby": _extract_ruby_heritage,
- "csharp": _extract_csharp_heritage,
- "swift": _extract_swift_heritage,
- "scala": _extract_scala_heritage,
- "php": _extract_php_heritage,
-}
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
new file mode 100644
index 000000000..aa464034c
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/__init__.py
@@ -0,0 +1,122 @@
+"""Per-language heritage (inheritance/interface/trait) extraction.
+
+Public API:
+
+- ``extract_heritage`` — language-dispatching entry point invoked by the
+ parser.
+- ``HERITAGE_EXTRACTORS`` — language → extractor function map. Exposed
+ for tests and tooling that need direct access.
+- ``heritage_node_types_for`` — returns the AST node types that can
+ carry heritage info for a given language (driven by ``LanguageSpec``).
+
+Each language lives in its own module under this package; add a new
+language by creating ``<lang>.py`` with an ``_extract_<lang>_heritage``
+function and registering it in ``HERITAGE_EXTRACTORS`` below.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable
+
+from ...languages.registry import REGISTRY as _LANG_REGISTRY
+from ...models import HeritageRelation
+from ..helpers import node_text
+from .cpp import _extract_cpp_heritage
+from .csharp import _extract_csharp_heritage
+from .go import _extract_go_heritage
+from .java import _extract_java_heritage
+from .kotlin import _extract_kotlin_heritage
+from .php import _extract_php_heritage
+from .python import _extract_python_heritage
+from .ruby import _extract_ruby_heritage
+from .rust import _extract_rust_heritage
+from .scala import _extract_scala_heritage
+from .swift import _extract_swift_heritage
+from .ts_js import _extract_ts_js_heritage
+
+
+def heritage_node_types_for(lang: str) -> frozenset[str]:
+ """Return the set of AST node types that can carry heritage info for *lang*."""
+ spec = _LANG_REGISTRY.get(lang)
+ return spec.heritage_node_types if spec else frozenset()
+
+
+HERITAGE_EXTRACTORS: dict[str, Callable[..., None]] = {
+ "python": _extract_python_heritage,
+ "typescript": _extract_ts_js_heritage,
+ "javascript": _extract_ts_js_heritage,
+ "java": _extract_java_heritage,
+ "go": _extract_go_heritage,
+ "rust": _extract_rust_heritage,
+ "cpp": _extract_cpp_heritage,
+ "c": lambda *_: None,
+ "kotlin": _extract_kotlin_heritage,
+ "ruby": _extract_ruby_heritage,
+ "csharp": _extract_csharp_heritage,
+ "swift": _extract_swift_heritage,
+ "scala": _extract_scala_heritage,
+ "php": _extract_php_heritage,
+}
+
+
+def extract_heritage(
+ tree: object,
+ query: object,
+ config: object,
+ file_info: object,
+ src: str,
+ *,
+ run_query: Callable,
+) -> list[HeritageRelation]:
+ """Extract inheritance/implementation relationships from class definitions.
+
+ Walks the same @symbol.def captures used by _extract_symbols, extracting
+ superclass/interface/trait information from the definition AST nodes.
+ """
+ if query is None:
+ return []
+
+ lang = file_info.language # type: ignore[attr-defined]
+ heritage_types = heritage_node_types_for(lang)
+ if not heritage_types:
+ return []
+
+ from ...language_data import get_builtin_parents
+
+ _parent_builtins = get_builtin_parents(lang)
+
+ relations: list[HeritageRelation] = []
+ seen: set[tuple[int, str]] = set()
+
+ for capture_dict in run_query(query, tree.root_node): # type: ignore[attr-defined]
+ def_nodes = capture_dict.get("symbol.def", [])
+ name_nodes = capture_dict.get("symbol.name", [])
+
+ if not def_nodes or not name_nodes:
+ continue
+
+ def_node = def_nodes[0]
+ if def_node.type not in heritage_types:
+ continue
+
+ name = node_text(name_nodes[0], src)
+ if not name:
+ continue
+
+ line = def_node.start_point[0] + 1
+ dedup_key = (line, name)
+ if dedup_key in seen:
+ continue
+ seen.add(dedup_key)
+
+ extractor = HERITAGE_EXTRACTORS.get(lang)
+ if extractor:
+ extractor(def_node, name, line, src, relations)
+
+ if _parent_builtins:
+ relations = [r for r in relations if r.parent_name not in _parent_builtins]
+
+ return relations
+
+
+__all__ = ["HERITAGE_EXTRACTORS", "extract_heritage", "heritage_node_types_for"]
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py
new file mode 100644
index 000000000..f5d6aafca
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/cpp.py
@@ -0,0 +1,32 @@
+"""C++ heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_cpp_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """C++: class Foo : public Bar, protected Baz."""
+ for child in def_node.children:
+ if child.type == "base_class_clause":
+ for base in child.children:
+ if base.type in (":", ","):
+ continue
+ text = node_text(base, src).strip()
+ for prefix in ("public", "protected", "private", "virtual"):
+ text = text.removeprefix(prefix).strip()
+ bare = text.split("::")[-1].strip()
+ if bare:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=bare,
+ kind="extends",
+ line=line,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/csharp.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/csharp.py
new file mode 100644
index 000000000..f75eef4cc
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/csharp.py
@@ -0,0 +1,62 @@
+"""C# heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_csharp_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """C#: ``class Foo : Bar, IFoo`` and ``record Point(...) : BaseRecord(...)``.
+
+ C# uses a single ``base_list`` with no syntactic distinction between
+ ``extends`` (the optional single base class) and ``implements`` (zero
+ or more interfaces). We classify by:
+
+ 1. The first non-interface-named base is the extends target. C#
+ requires the base class to come first when present, so position
+ is a strong hint.
+ 2. Names matching the I[A-Z]... convention or known framework
+ interfaces (``System.IDisposable`` etc.) are treated as
+ ``implements``.
+ 3. Records can also appear in the base list with an argument list:
+ ``record Point(int X) : Base(X)`` — the ``argument_list`` child
+ is ignored, only the type identifier matters.
+ """
+ base_list = None
+ for child in def_node.children:
+ if child.type == "base_list":
+ base_list = child
+ break
+ if base_list is None:
+ return
+
+ seen_extends = False # Only the first non-interface-looking base counts as extends.
+ for base in base_list.children:
+ if base.type in (":", ",") or not base.is_named:
+ continue
+ if base.type == "argument_list":
+ continue
+ text = node_text(base, src).strip()
+ bare = text.split("<")[0].split("(")[0].strip()
+ bare = bare.rsplit(".", 1)[-1].strip()
+ if not bare or bare == name:
+ continue
+ looks_interface = bare.startswith("I") and len(bare) > 1 and bare[1].isupper()
+ if looks_interface or seen_extends:
+ kind = "implements"
+ else:
+ kind = "extends"
+ seen_extends = True
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=bare,
+ kind=kind,
+ line=line,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/go.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/go.py
new file mode 100644
index 000000000..98b2e2b6a
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/go.py
@@ -0,0 +1,61 @@
+"""Go heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_go_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Go: struct embedding (type Foo struct { Bar; baz.Qux })."""
+ type_node = def_node.child_by_field_name("type")
+ if type_node is None:
+ return
+
+ if type_node.type == "struct_type":
+ body = type_node.child_by_field_name("body")
+ if body is None:
+ for child in type_node.children:
+ if child.type == "field_declaration_list":
+ body = child
+ break
+ if body is None:
+ return
+ for field_decl in body.children:
+ if field_decl.type != "field_declaration":
+ continue
+ name_node = field_decl.child_by_field_name("name")
+ type_child = field_decl.child_by_field_name("type")
+ if name_node is None and type_child is not None:
+ parent = node_text(type_child, src).strip().lstrip("*")
+ bare = parent.split(".")[-1]
+ if bare:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=bare,
+ kind="mixin",
+ line=line,
+ )
+ )
+
+ elif type_node.type == "interface_type":
+ for child in type_node.children:
+ if child.type in ("{", "}", "\n"):
+ continue
+ if child.type in ("type_identifier", "qualified_type"):
+ parent = node_text(child, src).strip()
+ bare = parent.split(".")[-1]
+ if bare:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=bare,
+ kind="extends",
+ line=line,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py
new file mode 100644
index 000000000..466fa621e
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/java.py
@@ -0,0 +1,68 @@
+"""Java heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_java_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Java: class Foo extends Bar implements IFoo, IBar."""
+ superclass = def_node.child_by_field_name("superclass")
+ if superclass:
+ parent = node_text(superclass, src).strip()
+ parent = parent.removeprefix("extends").strip()
+ if parent:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent.split(".")[-1],
+ kind="extends",
+ line=line,
+ )
+ )
+
+ interfaces = def_node.child_by_field_name("interfaces")
+ # Java interface declarations use `extends_interfaces` for the parent list.
+ if interfaces is None:
+ for child in def_node.children:
+ if child.type == "extends_interfaces":
+ interfaces = child
+ break
+ if interfaces:
+ for child in interfaces.children:
+ if child.type in ("implements", "extends", ",", "type_list"):
+ if child.type == "type_list":
+ for type_node in child.children:
+ if type_node.type != ",":
+ parent = node_text(type_node, src).strip().split(".")[-1]
+ if parent:
+ kind = (
+ "implements"
+ if def_node.type == "class_declaration"
+ else "extends"
+ )
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind=kind,
+ line=line,
+ )
+ )
+ continue
+ parent = node_text(child, src).strip().split(".")[-1]
+ if parent and parent not in ("implements", "extends"):
+ kind = "implements" if def_node.type == "class_declaration" else "extends"
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind=kind,
+ line=line,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/kotlin.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/kotlin.py
new file mode 100644
index 000000000..05ac5b140
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/kotlin.py
@@ -0,0 +1,43 @@
+"""Kotlin heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_kotlin_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Kotlin: class Foo : Bar(), IFoo."""
+ for child in def_node.children:
+ if child.type == "delegation_specifier":
+ for delegate in child.children:
+ text = node_text(delegate, src).strip()
+ bare = text.split("(")[0].split(".")[-1].strip()
+ if bare and bare != name:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=bare,
+ kind="extends",
+ line=line,
+ )
+ )
+ elif child.type == "delegation_specifiers":
+ for delegate in child.children:
+ if delegate.type in (":", ","):
+ continue
+ text = node_text(delegate, src).strip()
+ bare = text.split("(")[0].split(".")[-1].strip()
+ if bare and bare != name:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=bare,
+ kind="extends",
+ line=line,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/php.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/php.py
new file mode 100644
index 000000000..c3f612ba0
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/php.py
@@ -0,0 +1,57 @@
+"""PHP heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_php_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """PHP: ``class Foo extends Bar implements IFoo, IBar; use TraitName;``."""
+ for child in def_node.children:
+ if child.type == "base_clause":
+ for sub in child.children:
+ if sub.type == "name":
+ parent = node_text(sub, src).strip()
+ if parent and parent != name:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind="extends",
+ line=line,
+ )
+ )
+ elif child.type == "class_interface_clause":
+ for sub in child.children:
+ if sub.type == "name":
+ parent = node_text(sub, src).strip()
+ if parent and parent != name:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind="implements",
+ line=line,
+ )
+ )
+ elif child.type == "declaration_list":
+ # use TraitName; inside class body
+ for stmt in child.children:
+ if stmt.type == "use_declaration":
+ for sub in stmt.children:
+ if sub.type == "name":
+ trait_name = node_text(sub, src).strip()
+ if trait_name and trait_name != name:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=trait_name,
+ kind="mixin",
+ line=stmt.start_point[0] + 1,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/python.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/python.py
new file mode 100644
index 000000000..43f3caf0a
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/python.py
@@ -0,0 +1,34 @@
+"""Python heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_python_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Python: class Foo(Bar, Baz, metaclass=Meta)."""
+ superclasses = def_node.child_by_field_name("superclasses")
+ if superclasses is None:
+ for child in def_node.children:
+ if child.type == "argument_list":
+ superclasses = child
+ break
+ if superclasses is None:
+ return
+
+ for child in superclasses.children:
+ if child.type in ("(", ")", ","):
+ continue
+ if child.type == "keyword_argument":
+ continue
+ parent = node_text(child, src).strip()
+ if parent:
+ bare = parent.split(".")[-1]
+ out.append(
+ HeritageRelation(child_name=name, parent_name=bare, kind="extends", line=line)
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/ruby.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/ruby.py
new file mode 100644
index 000000000..709ff680c
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/ruby.py
@@ -0,0 +1,67 @@
+"""Ruby heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+_MIXIN_METHODS = {"include", "extend", "prepend"}
+
+
+def _extract_ruby_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Ruby: class Foo < Bar; include Mod; extend Mod; prepend Mod."""
+ superclass = def_node.child_by_field_name("superclass")
+ if superclass:
+ parent = node_text(superclass, src).strip()
+ parent = parent.removeprefix("<").strip()
+ bare = parent.split("::")[-1]
+ if bare:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=bare,
+ kind="extends",
+ line=line,
+ )
+ )
+
+ for child in def_node.children:
+ if child.type == "body_statement":
+ for stmt in child.children:
+ if stmt.type != "call":
+ continue
+ method_node = stmt.child_by_field_name("method")
+ if method_node is None:
+ for sc in stmt.children:
+ if sc.type == "identifier":
+ method_node = sc
+ break
+ if method_node is None:
+ continue
+ method_name = node_text(method_node, src).strip()
+ if method_name not in _MIXIN_METHODS:
+ continue
+ args = stmt.child_by_field_name("arguments")
+ if args is None:
+ for sc in stmt.children:
+ if sc.type == "argument_list":
+ args = sc
+ break
+ if args is None:
+ continue
+ for arg in args.children:
+ if arg.type == "constant":
+ mixin_name = node_text(arg, src).strip().split("::")[-1]
+ if mixin_name:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=mixin_name,
+ kind="mixin",
+ line=stmt.start_point[0] + 1,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
new file mode 100644
index 000000000..58a2ecaf1
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/rust.py
@@ -0,0 +1,70 @@
+"""Rust heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_rust_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Rust: impl Trait for Type, trait Foo: Bar + Baz, #[derive(Trait)]."""
+ if def_node.type == "impl_item":
+ trait_node = def_node.child_by_field_name("trait")
+ type_node = def_node.child_by_field_name("type")
+ if trait_node and type_node:
+ trait_name = node_text(trait_node, src).strip().rsplit("::", 1)[-1]
+ type_name = node_text(type_node, src).strip()
+ if trait_name and type_name:
+ out.append(
+ HeritageRelation(
+ child_name=type_name,
+ parent_name=trait_name,
+ kind="trait_impl",
+ line=line,
+ )
+ )
+
+ elif def_node.type == "trait_item":
+ bounds = def_node.child_by_field_name("bounds")
+ if bounds:
+ for child in bounds.children:
+ if child.type in ("+", ":"):
+ continue
+ parent = node_text(child, src).strip().rsplit("::", 1)[-1]
+ if parent:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind="extends",
+ line=line,
+ )
+ )
+
+ elif def_node.type in ("struct_item", "enum_item"):
+ # Walk preceding siblings for #[derive(Trait1, Trait2)]
+ prev = def_node.prev_named_sibling
+ while prev is not None and prev.type == "attribute_item":
+ attr_text = node_text(prev, src).strip()
+ if "derive(" in attr_text:
+ for child in prev.children:
+ if child.type == "attribute":
+ for sub in child.children:
+ if sub.type == "token_tree":
+ for tok in sub.children:
+ if tok.type == "identifier":
+ trait_name = node_text(tok, src).strip()
+ if trait_name:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=trait_name,
+ kind="derive",
+ line=line,
+ )
+ )
+ prev = prev.prev_named_sibling
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/scala.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/scala.py
new file mode 100644
index 000000000..febd22647
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/scala.py
@@ -0,0 +1,35 @@
+"""Scala heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_scala_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Scala: ``class Foo extends Bar with Trait1 with Trait2``."""
+ for child in def_node.children:
+ if child.type == "extends_clause":
+ saw_with = False
+ for sub in child.children:
+ if sub.type == "extends":
+ continue
+ if sub.type == "with":
+ saw_with = True
+ continue
+ if sub.type == "type_identifier":
+ parent = node_text(sub, src).strip()
+ if parent and parent != name:
+ kind = "implements" if saw_with else "extends"
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind=kind,
+ line=line,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/swift.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/swift.py
new file mode 100644
index 000000000..3ae4d8dd1
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/swift.py
@@ -0,0 +1,30 @@
+"""Swift heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_swift_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """Swift: ``class Foo: Bar, Protocol1`` — inheritance via ``:`` separator."""
+ for child in def_node.children:
+ if child.type == "inheritance_specifier":
+ for type_child in child.children:
+ if type_child.type == "user_type":
+ for id_node in type_child.children:
+ if id_node.type == "type_identifier":
+ parent = node_text(id_node, src).strip()
+ if parent and parent != name:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind="extends",
+ line=line,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage/ts_js.py b/packages/core/src/repowise/core/ingestion/extractors/heritage/ts_js.py
new file mode 100644
index 000000000..13de8292c
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage/ts_js.py
@@ -0,0 +1,60 @@
+"""TypeScript / JavaScript heritage extraction."""
+
+from __future__ import annotations
+
+from tree_sitter import Node
+
+from ...models import HeritageRelation
+from ..helpers import node_text
+
+
+def _extract_ts_js_heritage(
+ def_node: Node, name: str, line: int, src: str, out: list[HeritageRelation]
+) -> None:
+ """TypeScript/JavaScript: class Foo extends Bar implements IFoo, IBar."""
+ for child in def_node.children:
+ if child.type == "class_heritage":
+ for clause in child.children:
+ if clause.type == "extends_clause":
+ for type_node in clause.children:
+ if type_node.type in ("extends", ","):
+ continue
+ parent = node_text(type_node, src).strip()
+ if parent:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind="extends",
+ line=line,
+ )
+ )
+ elif clause.type == "implements_clause":
+ for type_node in clause.children:
+ if type_node.type in ("implements", ","):
+ continue
+ parent = node_text(type_node, src).strip()
+ if parent:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind="implements",
+ line=line,
+ )
+ )
+ # interface extends: interface Foo extends Bar
+ if child.type == "extends_type_clause":
+ for type_node in child.children:
+ if type_node.type in ("extends", ","):
+ continue
+ parent = node_text(type_node, src).strip()
+ if parent:
+ out.append(
+ HeritageRelation(
+ child_name=name,
+ parent_name=parent,
+ kind="extends",
+ line=line,
+ )
+ )
diff --git a/packages/core/src/repowise/core/ingestion/framework_edges.py b/packages/core/src/repowise/core/ingestion/framework_edges.py
index 68d39a407..bc1cfbc9a 100644
--- a/packages/core/src/repowise/core/ingestion/framework_edges.py
+++ b/packages/core/src/repowise/core/ingestion/framework_edges.py
@@ -53,6 +53,36 @@ def add_framework_edges(
if aspnet_in_stack or _has_aspnet_imports(parsed_files):
count += _add_aspnet_edges(graph, parsed_files, path_set)
+ if "rails" in stack_lower or "config/application.rb" in path_set:
+ count += _add_rails_edges(graph, parsed_files, ctx, path_set)
+
+ if (
+ "laravel" in stack_lower
+ or "routes/web.php" in path_set
+ or "routes/api.php" in path_set
+ ):
+ count += _add_laravel_edges(graph, parsed_files, ctx, path_set)
+
+ spring_in_stack = any(
+ token in stack_lower for token in ("spring", "springboot", "spring-boot", "spring boot")
+ )
+ if spring_in_stack or _has_spring_imports(parsed_files):
+ count += _add_spring_edges(graph, parsed_files, path_set)
+
+ express_in_stack = any(
+ token in stack_lower for token in ("express", "nestjs", "nest", "nest.js")
+ )
+ if express_in_stack or _has_express_imports(parsed_files):
+ count += _add_express_edges(graph, parsed_files, ctx, path_set)
+
+ go_router_in_stack = any(token in stack_lower for token in ("gin", "echo", "chi"))
+ if go_router_in_stack or _has_go_router_imports(parsed_files):
+ count += _add_go_router_edges(graph, parsed_files, path_set)
+
+ rust_router_in_stack = any(token in stack_lower for token in ("axum", "actix", "actix-web"))
+ if rust_router_in_stack or _has_rust_router_imports(parsed_files):
+ count += _add_rust_router_edges(graph, parsed_files, path_set)
+
return count
@@ -338,3 +368,599 @@ def _add_aspnet_edges(
count += 1
return count
+
+
+# ---------------------------------------------------------------------------
+# Helpers shared across the F1–F6 slices
+# ---------------------------------------------------------------------------
+
+
+def _read_text(parsed: Any) -> str:
+ try:
+ return Path(parsed.file_info.abs_path).read_text(encoding="utf-8", errors="ignore")
+ except OSError:
+ return ""
+
+
+def _build_class_to_file(parsed_files: dict[str, Any], languages: tuple[str, ...]) -> dict[str, str]:
+ """Map declared class/interface/struct/enum/record names → file path."""
+ result: dict[str, str] = {}
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in languages:
+ continue
+ for sym in parsed.symbols:
+ if sym.kind in ("class", "interface", "struct", "record", "enum", "trait"):
+ result.setdefault(sym.name, path)
+ return result
+
+
+def _build_function_to_file(
+ parsed_files: dict[str, Any], languages: tuple[str, ...]
+) -> dict[str, list[str]]:
+ """Map declared function/method names → list of file paths declaring them."""
+ result: dict[str, list[str]] = {}
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in languages:
+ continue
+ for sym in parsed.symbols:
+ if sym.kind in ("function", "method"):
+ result.setdefault(sym.name, []).append(path)
+ return result
+
+
+# ---------------------------------------------------------------------------
+# F2 — Rails framework edges
+# ---------------------------------------------------------------------------
+
+
+_RAILS_RESOURCES_RE = re.compile(r"\bresources?\s+:(\w+)")
+_RAILS_GET_TO_RE = re.compile(
+ r"\b(?:get|post|put|patch|delete|match)\s+[^\n]+?(?:to:\s*|=>\s*)['\"]([\w/]+)#\w+['\"]"
+)
+_RAILS_NAMESPACE_RE = re.compile(r"\bnamespace\s+:(\w+)\b")
+_RAILS_AR_RELATION_RE = re.compile(r"\b(?:belongs_to|has_many|has_one|has_and_belongs_to_many)\s+:(\w+)")
+
+
+def _singularize(word: str) -> str:
+ """Very rough Rails inflector — sufficient for routes/AR lookups."""
+ if word.endswith("ies") and len(word) > 3:
+ return word[:-3] + "y"
+ if word.endswith("ses") or word.endswith("xes") or word.endswith("zes"):
+ return word[:-2]
+ if word.endswith("s") and not word.endswith("ss"):
+ return word[:-1]
+ return word
+
+
+def _camelize(word: str) -> str:
+ return "".join(part.capitalize() for part in word.split("_"))
+
+
+def _add_rails_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+) -> int:
+ count = 0
+
+ # ---- routes.rb → controller files ----
+ routes_path = "config/routes.rb"
+ if routes_path in path_set:
+ try:
+ text = Path(parsed_files[routes_path].file_info.abs_path).read_text(
+ encoding="utf-8", errors="ignore"
+ )
+ except (OSError, KeyError):
+ text = ""
+ if text:
+ # Parse line-by-line to track namespace nesting (indent-agnostic; we
+ # use the order of opening keywords vs `end`).
+ namespace_stack: list[str] = []
+ for raw_line in text.splitlines():
+ line = raw_line.strip()
+ if not line or line.startswith("#"):
+ continue
+ ns_match = _RAILS_NAMESPACE_RE.search(line)
+ if ns_match and ("do" in line or line.endswith("do")):
+ namespace_stack.append(ns_match.group(1))
+ continue
+ if line == "end" and namespace_stack:
+ namespace_stack.pop()
+ continue
+ # resources :users → users_controller
+ for m in _RAILS_RESOURCES_RE.finditer(line):
+ resource = m.group(1)
+ target = _resolve_rails_controller(ctx, namespace_stack, resource, path_set)
+ if target and _add_edge_if_new(graph, routes_path, target):
+ count += 1
+ # get "/foo", to: "users#index"
+ for m in _RAILS_GET_TO_RE.finditer(line):
+ ctrl_path = m.group(1)
+ target = _resolve_rails_controller_path(ctx, namespace_stack, ctrl_path, path_set)
+ if target and _add_edge_if_new(graph, routes_path, target):
+ count += 1
+
+ # ---- ActiveRecord relationships: model → model ----
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "ruby":
+ continue
+ if "/models/" not in path and not path.startswith("app/models/"):
+ continue
+ text = _read_text(parsed)
+ if not text:
+ continue
+ for m in _RAILS_AR_RELATION_RE.finditer(text):
+ assoc_name = m.group(1)
+ target = _resolve_rails_relation(ctx, assoc_name, path_set)
+ if target and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ return count
+
+
+def _resolve_rails_controller(
+ ctx: ResolverContext, namespace_stack: list[str], resource: str, path_set: set[str]
+) -> str | None:
+ """`resources :users` (with optional `namespace :admin do`) → controller path."""
+ namespace_segs = [seg for seg in namespace_stack]
+ candidate_path = "/".join([*namespace_segs, f"{resource}_controller"])
+ expected = f"app/controllers/{candidate_path}.rb"
+ if expected in path_set:
+ return expected
+ # Try via Rails autoload index (heritage)
+ constant = "::".join(_camelize(seg) for seg in [*namespace_segs, f"{resource}_controller"])
+ return ctx.rails_lookup(constant)
+
+
+def _resolve_rails_controller_path(
+ ctx: ResolverContext, namespace_stack: list[str], controller_token: str, path_set: set[str]
+) -> str | None:
+ """`to: "users#index"` or `to: "admin/users#index"` → controller path."""
+ expected = f"app/controllers/{controller_token}_controller.rb"
+ if expected in path_set:
+ return expected
+ parts = controller_token.split("/")
+ constant = "::".join(_camelize(p) for p in [*parts[:-1], f"{parts[-1]}_controller"])
+ return ctx.rails_lookup(constant)
+
+
+def _resolve_rails_relation(
+ ctx: ResolverContext, assoc_name: str, path_set: set[str]
+) -> str | None:
+ """`belongs_to :user` / `has_many :orders` → model file."""
+ singular = _singularize(assoc_name)
+ expected = f"app/models/{singular}.rb"
+ if expected in path_set:
+ return expected
+ return ctx.rails_lookup(_camelize(singular))
+
+
+# ---------------------------------------------------------------------------
+# F3 — Laravel framework edges
+# ---------------------------------------------------------------------------
+
+
+_LARAVEL_ROUTE_ARRAY_RE = re.compile(
+ r"Route::(?:get|post|put|patch|delete|any|match|resource|apiResource)\s*\([^,]*,\s*\[\s*([\w\\]+)::class"
+)
+_LARAVEL_ROUTE_LEGACY_RE = re.compile(
+ r"Route::(?:get|post|put|patch|delete|any|match)\s*\([^,]*,\s*['\"]([\w\\]+)@\w+['\"]"
+)
+_LARAVEL_ROUTE_RESOURCE_RE = re.compile(
+ r"Route::(?:resource|apiResource)\s*\(\s*['\"][^'\"]+['\"]\s*,\s*([\w\\]+)::class"
+)
+_LARAVEL_BIND_RE = re.compile(
+ r"->\s*(?:bind|singleton|instance)\s*\(\s*([\w\\]+)::class\s*,\s*([\w\\]+)::class"
+)
+_LARAVEL_ELOQUENT_RE = re.compile(
+ r"\$this->\s*(?:hasMany|hasOne|belongsTo|belongsToMany|morphMany|morphOne|morphTo)\s*\(\s*([\w\\]+)::class"
+)
+
+
+def _resolve_laravel_class(
+ ctx: ResolverContext, fqn: str, class_to_file: dict[str, str], path_set: set[str]
+) -> str | None:
+ """Resolve `Foo\\Bar\\Baz` (or short `Bar`) to repo-relative .php path."""
+ from .resolvers.php_composer import resolve_via_psr4
+
+ if "\\" in fqn:
+ result = resolve_via_psr4(fqn, ctx)
+ if result and result in path_set:
+ return result
+ short = fqn.rsplit("\\", 1)[-1]
+ return class_to_file.get(short)
+
+
+def _add_laravel_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+) -> int:
+ count = 0
+ class_to_file = _build_class_to_file(parsed_files, ("php",))
+
+ # ---- routes/web.php / routes/api.php → controllers ----
+ for routes_path in ("routes/web.php", "routes/api.php"):
+ if routes_path not in path_set:
+ continue
+ try:
+ text = Path(parsed_files[routes_path].file_info.abs_path).read_text(
+ encoding="utf-8", errors="ignore"
+ )
+ except (OSError, KeyError):
+ continue
+ seen_targets: set[str] = set()
+ for regex in (
+ _LARAVEL_ROUTE_ARRAY_RE,
+ _LARAVEL_ROUTE_LEGACY_RE,
+ _LARAVEL_ROUTE_RESOURCE_RE,
+ ):
+ for m in regex.finditer(text):
+ target = _resolve_laravel_class(ctx, m.group(1), class_to_file, path_set)
+ if target and target in path_set and target not in seen_targets:
+ seen_targets.add(target)
+ if _add_edge_if_new(graph, routes_path, target):
+ count += 1
+
+ # ---- Service providers → bound classes ----
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "php":
+ continue
+ if not path.endswith("ServiceProvider.php"):
+ continue
+ text = _read_text(parsed)
+ if not text:
+ continue
+ for m in _LARAVEL_BIND_RE.finditer(text):
+ for fqn in (m.group(1), m.group(2)):
+ target = _resolve_laravel_class(ctx, fqn, class_to_file, path_set)
+ if target and target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ # ---- Eloquent relationships: model → related model ----
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "php":
+ continue
+ text = _read_text(parsed)
+ if not text:
+ continue
+ for m in _LARAVEL_ELOQUENT_RE.finditer(text):
+ target = _resolve_laravel_class(ctx, m.group(1), class_to_file, path_set)
+ if target and target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ return count
+
+
+# ---------------------------------------------------------------------------
+# F1 — Spring Boot framework edges
+# ---------------------------------------------------------------------------
+
+
+_SPRING_BEAN_ANNOT = ("@Component", "@Service", "@Repository", "@Controller", "@RestController", "@Configuration")
+_SPRING_AUTOWIRED_FIELD_RE = re.compile(
+ r"@Autowired\s+(?:private|protected|public|final|\s)*\s*([A-Z]\w*)\s+\w+"
+)
+_SPRING_CTOR_PARAM_RE = re.compile(r"\b([A-Z]\w*)\s+\w+\s*[,)]")
+_SPRING_BEAN_METHOD_RE = re.compile(
+ r"@Bean\b[^\n]*\n\s*(?:public|protected|private|static|final|\s)+\s*([A-Z]\w*)\s+\w+\s*\("
+)
+_SPRING_BEAN_METHOD_KOTLIN_RE = re.compile(
+ r"@Bean\b[^\n]*\n\s*(?:public|protected|private|internal|fun|open|\s)+\s*\w+\s*\([^)]*\)\s*:\s*([A-Z]\w*)"
+)
+
+
+def _has_spring_imports(parsed_files: dict[str, Any]) -> bool:
+ for parsed in parsed_files.values():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ for imp in parsed.imports:
+ if imp.module_path.startswith("org.springframework"):
+ return True
+ return False
+
+
+def _add_spring_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ path_set: set[str],
+) -> int:
+ count = 0
+ class_to_file = _build_class_to_file(parsed_files, ("java", "kotlin"))
+
+ # Build interface → list of impl files map from heritage
+ impl_map: dict[str, list[str]] = {}
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ for rel in parsed.heritage:
+ if rel.kind in ("implements", "extends"):
+ impl_map.setdefault(rel.parent_name, []).append(path)
+
+ def _resolve_type(type_name: str) -> list[str]:
+ results: list[str] = []
+ own = class_to_file.get(type_name)
+ if own:
+ results.append(own)
+ for impl in impl_map.get(type_name, []):
+ if impl not in results:
+ results.append(impl)
+ return results
+
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in ("java", "kotlin"):
+ continue
+ text = _read_text(parsed)
+ if not text:
+ continue
+ is_bean = any(annot in text for annot in _SPRING_BEAN_ANNOT)
+ if not is_bean:
+ continue
+
+ # @Autowired field injection
+ for m in _SPRING_AUTOWIRED_FIELD_RE.finditer(text):
+ type_name = m.group(1)
+ for target in _resolve_type(type_name):
+ if target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ # Constructor parameter injection: collect param types from any @Autowired
+ # constructor or any single public constructor in a bean (Spring 4.3+ omits
+ # the annotation when the class has only one constructor).
+ for ctor_match in re.finditer(
+ r"(?:@Autowired\s*\n\s*)?(?:public|protected|private|\s)*"
+ + re.escape(Path(path).stem)
+ + r"\s*\(([^)]*)\)",
+ text,
+ ):
+ params = ctor_match.group(1)
+ if not params.strip():
+ continue
+ for pm in _SPRING_CTOR_PARAM_RE.finditer(params + ","):
+ type_name = pm.group(1)
+ if type_name in ("String", "Integer", "Long", "Boolean", "Double", "Float"):
+ continue
+ for target in _resolve_type(type_name):
+ if target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ # @Bean factory methods → return-type file
+ if "@Configuration" in text:
+ for m in _SPRING_BEAN_METHOD_RE.finditer(text):
+ for target in _resolve_type(m.group(1)):
+ if target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+ for m in _SPRING_BEAN_METHOD_KOTLIN_RE.finditer(text):
+ for target in _resolve_type(m.group(1)):
+ if target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ return count
+
+
+# ---------------------------------------------------------------------------
+# F4 — Express / NestJS framework edges
+# ---------------------------------------------------------------------------
+
+
+_EXPRESS_USE_RE = re.compile(r"\.\s*use\s*\(\s*(?:['\"][^'\"]+['\"]\s*,\s*)?(\w+)\s*[,)]")
+_NEST_MODULE_RE = re.compile(r"@Module\s*\(\s*\{([^}]*)\}\s*\)", re.DOTALL)
+_NEST_ARRAY_FIELD_RE = re.compile(
+ r"\b(?:controllers|providers|imports|exports)\s*:\s*\[([^\]]*)\]"
+)
+_IDENT_RE = re.compile(r"\b([A-Z]\w*)\b")
+
+
+def _has_express_imports(parsed_files: dict[str, Any]) -> bool:
+ for parsed in parsed_files.values():
+ if parsed.file_info.language not in ("typescript", "javascript"):
+ continue
+ for imp in parsed.imports:
+ mp = imp.module_path
+ if mp == "express" or mp.startswith("@nestjs/"):
+ return True
+ return False
+
+
+def _add_express_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ ctx: ResolverContext,
+ path_set: set[str],
+) -> int:
+ count = 0
+ class_to_file = _build_class_to_file(parsed_files, ("typescript", "javascript"))
+
+ # ---- Express: app.use(routerVar) ----
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language not in ("typescript", "javascript"):
+ continue
+ text = _read_text(parsed)
+ if not text:
+ continue
+
+ # Build local var → source file map for this file
+ var_to_file: dict[str, str] = {}
+ for imp in parsed.imports:
+ for name in imp.imported_names:
+ resolved = resolve_import(
+ imp.module_path,
+ path,
+ parsed.file_info.language,
+ ctx,
+ )
+ if resolved and resolved in path_set:
+ var_to_file[name] = resolved
+
+ if "express" in text or any(
+ imp.module_path == "express" for imp in parsed.imports
+ ):
+ for m in _EXPRESS_USE_RE.finditer(text):
+ var_name = m.group(1)
+ target = var_to_file.get(var_name)
+ if target and target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ # ---- NestJS: @Module({ controllers: [...], providers: [...], imports: [...] }) ----
+ for mod_match in _NEST_MODULE_RE.finditer(text):
+ body = mod_match.group(1)
+ for arr_match in _NEST_ARRAY_FIELD_RE.finditer(body):
+ for ident_match in _IDENT_RE.finditer(arr_match.group(1)):
+ cls = ident_match.group(1)
+ target = var_to_file.get(cls) or class_to_file.get(cls)
+ if target and target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ return count
+
+
+# ---------------------------------------------------------------------------
+# F5 — Gin / Echo / Chi framework edges (Go)
+# ---------------------------------------------------------------------------
+
+
+_GO_ROUTER_PKG_PATTERNS = (
+ "github.com/gin-gonic/gin",
+ "github.com/labstack/echo",
+ "github.com/go-chi/chi",
+)
+_GO_ROUTE_CALL_RE = re.compile(
+ r"\.\s*(?:GET|POST|PUT|DELETE|PATCH|OPTIONS|HEAD|HandleFunc|Handle|Any)"
+ r"\s*\(\s*[\"'][^\"']*[\"']\s*,\s*([\w.]+)"
+)
+
+
+def _has_go_router_imports(parsed_files: dict[str, Any]) -> bool:
+ for parsed in parsed_files.values():
+ if parsed.file_info.language != "go":
+ continue
+ for imp in parsed.imports:
+ mp = imp.module_path
+ if any(mp.startswith(pkg) for pkg in _GO_ROUTER_PKG_PATTERNS):
+ return True
+ return False
+
+
+def _add_go_router_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ path_set: set[str],
+) -> int:
+ count = 0
+ func_to_files = _build_function_to_file(parsed_files, ("go",))
+ class_to_file = _build_class_to_file(parsed_files, ("go",))
+
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "go":
+ continue
+ text = _read_text(parsed)
+ if not text:
+ continue
+ if not any(
+ imp.module_path.startswith(pkg)
+ for pkg in _GO_ROUTER_PKG_PATTERNS
+ for imp in parsed.imports
+ ):
+ # Allow if some other go file in the repo imports a router (router
+ # setup may be split across files); be conservative and only emit
+ # edges for files that themselves reference router calls.
+ pass
+
+ for m in _GO_ROUTE_CALL_RE.finditer(text):
+ handler = m.group(1)
+ targets = _resolve_go_handler(handler, parsed, func_to_files, class_to_file)
+ for target in targets:
+ if target != path and target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ return count
+
+
+def _resolve_go_handler(
+ handler: str,
+ parsed: Any,
+ func_to_files: dict[str, list[str]],
+ class_to_file: dict[str, str],
+) -> list[str]:
+ """Resolve `pkg.Func` / `recv.Method` / `Func` to candidate file paths."""
+ if "." in handler:
+ prefix, name = handler.rsplit(".", 1)
+ # First: was prefix imported as a package?
+ for imp in parsed.imports:
+ short = imp.module_path.rsplit("/", 1)[-1]
+ if short == prefix and imp.resolved_file:
+ # Find file declaring `name` whose path starts with the resolved package dir
+ pkg_dir = "/".join(imp.resolved_file.split("/")[:-1])
+ results = [
+ p
+ for p in func_to_files.get(name, [])
+ if p.startswith(pkg_dir + "/") or p == imp.resolved_file
+ ]
+ if results:
+ return results
+ # Second: receiver-method — try the receiver's type file
+ type_file = class_to_file.get(prefix.title())
+ if type_file:
+ return [type_file]
+ # Third: fall back to any file declaring the bare name
+ return list(func_to_files.get(name, []))
+ return list(func_to_files.get(handler, []))
+
+
+# ---------------------------------------------------------------------------
+# F6 — Axum / Actix framework edges (Rust)
+# ---------------------------------------------------------------------------
+
+
+_RUST_AXUM_ROUTE_RE = re.compile(
+ r"\.\s*route\s*\(\s*[\"'][^\"']*[\"']\s*,\s*"
+ r"(?:get|post|put|delete|patch|head|options|on)\s*\(\s*([\w:]+)\s*\)"
+)
+_RUST_ACTIX_TO_RE = re.compile(r"web::\s*(?:get|post|put|delete|patch|head)\(\)\s*\.\s*to\s*\(\s*([\w:]+)\s*\)")
+_RUST_ACTIX_SERVICE_RE = re.compile(r"\.\s*service\s*\(\s*([\w:]+)\s*\)")
+_RUST_SCOPE_CONFIGURE_RE = re.compile(r"\.\s*configure\s*\(\s*([\w:]+)\s*\)")
+
+
+def _has_rust_router_imports(parsed_files: dict[str, Any]) -> bool:
+ for parsed in parsed_files.values():
+ if parsed.file_info.language != "rust":
+ continue
+ for imp in parsed.imports:
+ mp = imp.module_path
+ if mp.startswith("axum") or mp.startswith("actix_web") or mp.startswith("actix-web"):
+ return True
+ return False
+
+
+def _add_rust_router_edges(
+ graph: nx.DiGraph,
+ parsed_files: dict[str, Any],
+ path_set: set[str],
+) -> int:
+ count = 0
+ func_to_files = _build_function_to_file(parsed_files, ("rust",))
+
+ def _resolve(handler: str) -> list[str]:
+ name = handler.rsplit("::", 1)[-1]
+ return list(func_to_files.get(name, []))
+
+ for path, parsed in parsed_files.items():
+ if parsed.file_info.language != "rust":
+ continue
+ text = _read_text(parsed)
+ if not text:
+ continue
+ for regex in (
+ _RUST_AXUM_ROUTE_RE,
+ _RUST_ACTIX_TO_RE,
+ _RUST_ACTIX_SERVICE_RE,
+ _RUST_SCOPE_CONFIGURE_RE,
+ ):
+ for m in regex.finditer(text):
+ for target in _resolve(m.group(1)):
+ if target != path and target in path_set and _add_edge_if_new(graph, path, target):
+ count += 1
+
+ return count
diff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.py
index 0ae32526c..e068ec4db 100644
--- a/packages/core/src/repowise/core/ingestion/graph.py
+++ b/packages/core/src/repowise/core/ingestion/graph.py
@@ -34,7 +34,7 @@ import structlog
from .models import ParsedFile
from .resolvers import ResolverContext, resolve_import
-from .resolvers.go import read_go_module_path
+from .resolvers.go import read_go_module_path, read_go_modules
log = structlog.get_logger(__name__)
@@ -202,13 +202,18 @@ class GraphBuilder:
stem_map = self._build_stem_map(path_set)
# Construct resolver context
+ go_modules = read_go_modules(self._repo_path)
ctx = ResolverContext(
path_set=path_set,
stem_map=stem_map,
graph=self._graph,
repo_path=self._repo_path,
tsconfig_resolver=self._tsconfig_resolver,
- go_module_path=read_go_module_path(self._repo_path),
+ go_module_path=(go_modules[-1][1] if go_modules else read_go_module_path(self._repo_path)),
+ go_modules=go_modules,
+ has_sfc_files=any(
+ p.endswith((".vue", ".svelte", ".astro")) for p in path_set
+ ),
parsed_files=self._parsed_files,
)
@@ -589,10 +594,14 @@ class GraphBuilder:
continue
if e.target not in self._graph:
self._graph.add_node(e.target)
+ sub_type = e.edge_type or "dynamic"
+ graph_edge_type = (
+ sub_type if sub_type.startswith("dynamic") else f"dynamic_{sub_type}"
+ )
self._graph.add_edge(
e.source,
e.target,
- edge_type="dynamic",
+ edge_type=graph_edge_type,
hint_source=e.hint_source,
weight=e.weight,
)
@@ -611,13 +620,18 @@ class GraphBuilder:
path_set = set(self._parsed_files.keys())
stem_map = self._build_stem_map(path_set)
+ go_modules = read_go_modules(self._repo_path)
ctx = ResolverContext(
path_set=path_set,
stem_map=stem_map,
graph=self._graph,
repo_path=self._repo_path,
tsconfig_resolver=self._tsconfig_resolver,
- go_module_path=read_go_module_path(self._repo_path),
+ go_module_path=(go_modules[-1][1] if go_modules else read_go_module_path(self._repo_path)),
+ go_modules=go_modules,
+ has_sfc_files=any(
+ p.endswith((".vue", ".svelte", ".astro")) for p in path_set
+ ),
parsed_files=self._parsed_files,
)
diff --git a/packages/core/src/repowise/core/ingestion/languages/registry.py b/packages/core/src/repowise/core/ingestion/languages/registry.py
index 8fe9d92cf..78f0b7789 100644
--- a/packages/core/src/repowise/core/ingestion/languages/registry.py
+++ b/packages/core/src/repowise/core/ingestion/languages/registry.py
@@ -796,7 +796,9 @@ _SPECS: tuple[LanguageSpec, ...] = (
extensions=frozenset({".swift"}),
grammar_package="tree_sitter_swift",
scm_file="swift.scm",
- heritage_node_types=frozenset({"class_declaration", "protocol_declaration"}),
+ heritage_node_types=frozenset(
+ {"class_declaration", "protocol_declaration", "extension_declaration"}
+ ),
manifest_files=("Package.swift",),
builtin_calls=frozenset(
{
diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.py
index b9d15da6c..1c96208dc 100644
--- a/packages/core/src/repowise/core/ingestion/parser.py
+++ b/packages/core/src/repowise/core/ingestion/parser.py
@@ -269,6 +269,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"class_declaration": "class",
"interface_declaration": "interface",
"enum_declaration": "enum",
+ "record_declaration": "class", # Java 16+ records
"method_declaration": "method",
"constructor_declaration": "function",
},
@@ -277,7 +278,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
visibility_fn=java_visibility,
parent_extraction="nesting",
parent_class_types=frozenset(
- {"class_declaration", "interface_declaration", "enum_declaration"}
+ {"class_declaration", "interface_declaration", "enum_declaration", "record_declaration"}
),
entry_point_patterns=["Main.java", "Application.java"],
),
@@ -323,6 +324,8 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"function_declaration": "function",
"class_declaration": "class",
"object_declaration": "class",
+ "type_alias": "type_alias",
+ "property_declaration": "variable",
},
import_node_types=["import"],
export_node_types=[],
@@ -337,6 +340,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"singleton_method": "function",
"class": "class",
"module": "module",
+ "assignment": "constant",
},
import_node_types=["call"],
export_node_types=[],
@@ -387,6 +391,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"function_declaration": "function",
"protocol_function_declaration": "function",
"property_declaration": "variable",
+ "subscript_declaration": "method",
},
import_node_types=["import_declaration"],
export_node_types=[],
@@ -403,6 +408,9 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"function_definition": "function",
"function_declaration": "function",
"val_definition": "variable",
+ "var_definition": "variable",
+ "enum_definition": "enum",
+ "given_definition": "variable",
},
import_node_types=["import_declaration"],
export_node_types=[],
@@ -419,6 +427,8 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {
"enum_declaration": "enum",
"method_declaration": "method",
"function_definition": "function",
+ "const_declaration": "constant",
+ "property_declaration": "variable",
},
import_node_types=["namespace_use_declaration"],
export_node_types=[],
diff --git a/packages/core/src/repowise/core/ingestion/queries/c.scm b/packages/core/src/repowise/core/ingestion/queries/c.scm
index a0962b91a..158b5e12d 100644
--- a/packages/core/src/repowise/core/ingestion/queries/c.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/c.scm
@@ -34,6 +34,19 @@
declarator: (type_identifier) @symbol.name
) @symbol.def
+; typedef int MyInt; / typedef struct Foo Bar; (Q10 — primitive/named alias)
+(type_definition
+ type: (primitive_type)
+ declarator: (type_identifier) @symbol.name
+) @symbol.def
+
+(type_definition
+ type: (struct_specifier
+ name: (type_identifier)
+ )
+ declarator: (type_identifier) @symbol.name
+) @symbol.def
+
; #define MACRO_NAME ...
(preproc_def
name: (identifier) @symbol.name
diff --git a/packages/core/src/repowise/core/ingestion/queries/java.scm b/packages/core/src/repowise/core/ingestion/queries/java.scm
index cf2814a54..1b07b97b5 100644
--- a/packages/core/src/repowise/core/ingestion/queries/java.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/java.scm
@@ -11,14 +11,34 @@
name: (identifier) @symbol.name
) @symbol.def
+(class_declaration
+ (modifiers) @symbol.modifiers
+ name: (identifier) @symbol.name
+) @symbol.def
+
(interface_declaration
name: (identifier) @symbol.name
) @symbol.def
+(interface_declaration
+ (modifiers) @symbol.modifiers
+ name: (identifier) @symbol.name
+) @symbol.def
+
(enum_declaration
name: (identifier) @symbol.name
) @symbol.def
+; Java 16+ records: record Point(double x, double y) {}
+(record_declaration
+ name: (identifier) @symbol.name
+) @symbol.def
+
+(record_declaration
+ (modifiers) @symbol.modifiers
+ name: (identifier) @symbol.name
+) @symbol.def
+
(method_declaration
name: (identifier) @symbol.name
parameters: (formal_parameters) @symbol.params
diff --git a/packages/core/src/repowise/core/ingestion/queries/kotlin.scm b/packages/core/src/repowise/core/ingestion/queries/kotlin.scm
index 585c6b133..c54e5e223 100644
--- a/packages/core/src/repowise/core/ingestion/queries/kotlin.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/kotlin.scm
@@ -21,6 +21,28 @@
(identifier) @symbol.name
) @symbol.def
+; typealias Foo = Bar (Q2)
+(type_alias
+ (identifier) @symbol.name
+) @symbol.def
+
+; Top-level / class-level val/var properties (Q3) — excludes locals inside functions
+(source_file
+ (property_declaration
+ (variable_declaration
+ (identifier) @symbol.name
+ )
+ ) @symbol.def
+)
+
+(class_body
+ (property_declaration
+ (variable_declaration
+ (identifier) @symbol.name
+ )
+ ) @symbol.def
+)
+
; ---------------------------------------------------------------------------
; Imports
; ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/queries/php.scm b/packages/core/src/repowise/core/ingestion/queries/php.scm
index 5fed1da73..f8ef60052 100644
--- a/packages/core/src/repowise/core/ingestion/queries/php.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/php.scm
@@ -40,6 +40,22 @@
parameters: (formal_parameters) @symbol.params
) @symbol.def
+; PHP top-level / class-level constant declarations (Q9)
+(const_declaration
+ (const_element
+ (name) @symbol.name
+ )
+) @symbol.def
+
+; PHP class properties (Q9): public $x, private $y, fallback no-modifier
+(property_declaration
+ (property_element
+ (variable_name
+ (name) @symbol.name
+ )
+ )
+) @symbol.def
+
; ---------------------------------------------------------------------------
; Imports (use declarations + require/include)
; ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/queries/ruby.scm b/packages/core/src/repowise/core/ingestion/queries/ruby.scm
index 922e27f2f..b02963912 100644
--- a/packages/core/src/repowise/core/ingestion/queries/ruby.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/ruby.scm
@@ -20,6 +20,11 @@
name: (constant) @symbol.name
) @symbol.def
+; Top-level / class-level constant assignment (Q8): MAX = 3
+(assignment
+ left: (constant) @symbol.name
+) @symbol.def
+
; require 'module' / require_relative './sibling'
(call
method: (identifier) @_require_method
diff --git a/packages/core/src/repowise/core/ingestion/queries/scala.scm b/packages/core/src/repowise/core/ingestion/queries/scala.scm
index da63b8b1c..38868cb60 100644
--- a/packages/core/src/repowise/core/ingestion/queries/scala.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/scala.scm
@@ -11,6 +11,18 @@
name: (identifier) @symbol.name
) @symbol.def
+; Annotated class (Q11): @deprecated class Foo
+(class_definition
+ (annotation) @symbol.modifiers
+ name: (identifier) @symbol.name
+) @symbol.def
+
+; Annotated function (Q11): @tailrec def bar
+(function_definition
+ (annotation) @symbol.modifiers
+ name: (identifier) @symbol.name
+) @symbol.def
+
(trait_definition
name: (identifier) @symbol.name
) @symbol.def
@@ -33,6 +45,21 @@
pattern: (identifier) @symbol.name
) @symbol.def
+; Scala 3 enum (Q4)
+(enum_definition
+ name: (identifier) @symbol.name
+) @symbol.def
+
+; Scala 3 given (Q4) — named givens have an identifier child
+(given_definition
+ (identifier) @symbol.name
+) @symbol.def
+
+; Scala var definitions (Q5)
+(var_definition
+ pattern: (identifier) @symbol.name
+) @symbol.def
+
; ---------------------------------------------------------------------------
; Imports
; ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/queries/swift.scm b/packages/core/src/repowise/core/ingestion/queries/swift.scm
index d68147c77..f382d71fd 100644
--- a/packages/core/src/repowise/core/ingestion/queries/swift.scm
+++ b/packages/core/src/repowise/core/ingestion/queries/swift.scm
@@ -47,6 +47,11 @@
(simple_identifier) @symbol.name
) @symbol.def
+; Swift subscript (Q6) — capture the `subscript` keyword as the name
+(subscript_declaration
+ "subscript" @symbol.name
+) @symbol.def
+
; ---------------------------------------------------------------------------
; Imports
; ---------------------------------------------------------------------------
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/context.py b/packages/core/src/repowise/core/ingestion/resolvers/context.py
index 13c437549..cf7cb0abf 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/context.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/context.py
@@ -30,14 +30,31 @@ class ResolverContext:
# Language-specific state
tsconfig_resolver: Any | None = None
go_module_path: str | None = None
+ go_modules: tuple[tuple[str, str], ...] = () # (module_dir_posix, module_path), longest-first
+ has_sfc_files: bool = False # any .vue/.svelte/.astro present in path_set
parsed_files: dict | None = None # for Rust crate root detection
compile_commands_cache: dict[str, dict] | None = field(default=None, repr=False)
+ # Lazy per-language indexes are stashed via getattr/setattr (e.g.
+ # ``_php_psr4_map``, ``_ts_workspace_map``, ``_kotlin_index``,
+ # ``_ruby_rails_index``, ``_swift_targets``, ``_scala_index``). This
+ # mirrors the dotnet/index.py pattern and keeps language-specific bloat
+ # off the dataclass.
def stem_lookup(self, stem: str) -> str | None:
"""Return the highest-priority path for *stem*, or None."""
candidates = self.stem_map.get(stem)
return candidates[0] if candidates else None
+ def rails_lookup(self, name: str) -> str | None:
+ """Resolve a Rails constant (snake_cased) to a repo-relative file via
+ the lazy Zeitwerk autoload index. Returns None if not a Rails repo."""
+ from .ruby_rails import get_or_build_rails_index
+
+ index = get_or_build_rails_index(self)
+ if index is None:
+ return None
+ return index.lookup(name)
+
def add_external_node(self, module_path: str) -> str:
"""Register an external dependency node and return its key."""
key = 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 9a2786f12..78db5d5b7 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/go.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/go.py
@@ -6,14 +6,10 @@ from pathlib import Path
from .context import ResolverContext
+_GO_MOD_SKIP_DIRS = frozenset({"vendor", "node_modules", ".git"})
-def read_go_module_path(repo_path: Path | None) -> str | None:
- """Read the ``module`` directive from ``go.mod``, if present."""
- if repo_path is None:
- return None
- go_mod = repo_path / "go.mod"
- if not go_mod.is_file():
- return None
+
+def _read_module_directive(go_mod: Path) -> str | None:
try:
for line in go_mod.read_text(encoding="utf-8", errors="ignore").splitlines():
line = line.strip()
@@ -24,27 +20,83 @@ def read_go_module_path(repo_path: Path | None) -> str | None:
return None
+def read_go_module_path(repo_path: Path | None) -> str | None:
+ """Read the ``module`` directive from the root ``go.mod``, if present."""
+ if repo_path is None:
+ return None
+ go_mod = repo_path / "go.mod"
+ if not go_mod.is_file():
+ return None
+ return _read_module_directive(go_mod)
+
+
+def read_go_modules(repo_path: Path | None) -> tuple[tuple[str, str], ...]:
+ """Discover every ``go.mod`` under *repo_path* and return
+ ``((module_dir_posix, module_path), ...)`` sorted longest-module-path-first.
+
+ This supports Go monorepos with multiple modules (e.g.
+ ``services/foo/go.mod`` + ``libs/bar/go.mod``).
+ """
+ if repo_path is None or not repo_path.is_dir():
+ return ()
+ found: list[tuple[str, str]] = []
+ for go_mod in repo_path.rglob("go.mod"):
+ # Skip vendored / nested-package directories
+ rel_parts = go_mod.relative_to(repo_path).parts
+ if any(part in _GO_MOD_SKIP_DIRS for part in rel_parts):
+ continue
+ module_path = _read_module_directive(go_mod)
+ if not module_path:
+ continue
+ module_dir = go_mod.parent.relative_to(repo_path).as_posix()
+ if module_dir == ".":
+ module_dir = ""
+ found.append((module_dir, module_path))
+ # Longest module path first so prefix-matching prefers the most specific.
+ found.sort(key=lambda t: len(t[1]), reverse=True)
+ return tuple(found)
+
+
def resolve_go_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
"""Resolve a Go import path to a repo-relative file path."""
- # If we know the module path and the import starts with it,
- # strip the prefix to get the repo-relative package dir.
- if ctx.go_module_path and module_path.startswith(ctx.go_module_path):
- suffix = module_path[len(ctx.go_module_path) :]
- rel_dir = suffix.lstrip("/")
- # Find any Go file in that directory
+ # Multi-module: try each known module's prefix, longest first.
+ for module_dir, mod_path in ctx.go_modules:
+ if module_path == mod_path or module_path.startswith(mod_path + "/"):
+ suffix = module_path[len(mod_path) :].lstrip("/")
+ if module_dir and suffix:
+ rel_dir = f"{module_dir}/{suffix}"
+ else:
+ rel_dir = module_dir or suffix
+ for p in ctx.path_set:
+ 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}")):
+ return p
+ pkg_name = (rel_dir or suffix).rsplit("/", 1)[-1].lower()
+ if pkg_name:
+ result = ctx.stem_lookup(pkg_name)
+ if result:
+ return result
+ # Matched a module but found nothing — fall through to global
+ # stem map / external rather than breaking early.
+ break
+
+ # Single-module back-compat: use the legacy ``go_module_path`` field if
+ # ``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:
if p.endswith(".go"):
p_dir = str(Path(p).parent.as_posix())
- if p_dir == rel_dir or p_dir.endswith(f"/{rel_dir}"):
+ if p_dir == suffix or p_dir.endswith(f"/{suffix}"):
return p
- # Try stem matching as fallback for the package name
- pkg_name = rel_dir.rsplit("/", 1)[-1].lower() if rel_dir else ""
+ pkg_name = suffix.rsplit("/", 1)[-1].lower() if suffix else ""
if pkg_name:
result = ctx.stem_lookup(pkg_name)
if result:
return result
- # No go.mod match — fall back to stem matching on the last segment
+ # No module match — fall back to stem matching on the last segment.
stem = module_path.rsplit("/", 1)[-1].lower()
result = ctx.stem_lookup(stem)
if result:
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py
index 4249b2bfb..b06bb9fe3 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from pathlib import PurePosixPath
from .context import ResolverContext
+from .kotlin_gradle import resolve_via_kotlin_index
def resolve_kotlin_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
@@ -15,6 +16,13 @@ def resolve_kotlin_import(module_path: str, importer_path: str, ctx: ResolverCon
if local == "*":
return None
+ # Gradle-aware resolution: settings.gradle subprojects + per-module
+ # sourceSets parsing yields a {package → files} index. Consult it first
+ # so multi-module Android/JVM layouts resolve correctly.
+ gradle_match = resolve_via_kotlin_index(module_path, ctx)
+ if gradle_match is not None:
+ return gradle_match
+
# Try stem lookup on the class/function name
result = ctx.stem_lookup(local.lower())
if result and (result.endswith(".kt") or result.endswith(".kts")):
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/kotlin_gradle.py b/packages/core/src/repowise/core/ingestion/resolvers/kotlin_gradle.py
new file mode 100644
index 000000000..1de656e7c
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/kotlin_gradle.py
@@ -0,0 +1,187 @@
+"""Gradle multi-module / sourceSets index for Kotlin import resolution.
+
+Real Android and JVM projects use Gradle layouts where source roots live
+under per-module directories: ``app/src/main/kotlin/...``,
+``feature-foo/src/main/kotlin/...``. The default ``resolve_kotlin_import``
+relies on stem matching, which fails when two modules contain a class of
+the same name.
+
+This module:
+- enumerates Gradle subprojects from ``settings.gradle(.kts)`` ``include(...)``
+ declarations,
+- collects source roots per subproject (defaults: ``src/main/kotlin``,
+ ``src/main/java``; explicit ``srcDirs`` overrides honoured),
+- scans each source file's ``package`` declaration to build a
+ ``{fully.qualified.Name → [path, ...]}`` map.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+
+_INCLUDE_RE = re.compile(r'include\s*\(\s*((?:"[^"]+"\s*,?\s*)+)\)')
+_INCLUDE_ITEM_RE = re.compile(r'"([^"]+)"')
+_INCLUDE_LINE_RE = re.compile(r'include\s+([\'"])([^\'"]+)\1')
+_SRCDIRS_RE = re.compile(
+ r'srcDirs?\s*[=(]\s*((?:listOf|setOf)?\s*\(?\s*(?:"[^"]+"\s*,?\s*)+\)?)',
+ re.DOTALL,
+)
+_PACKAGE_RE = re.compile(r"^\s*package\s+([\w.]+)", re.MULTILINE)
+_DEFAULT_SRC_ROOTS = ("src/main/kotlin", "src/main/java")
+
+
+@dataclass
+class KotlinProjectIndex:
+ modules: dict[str, list[str]] = field(default_factory=dict)
+ package_to_files: dict[str, list[str]] = field(default_factory=dict)
+
+ def lookup_class(self, fqn: str) -> list[str]:
+ """Match ``com.example.Foo`` → files declaring ``package com.example``
+ and named ``Foo.kt``/``Foo.kts``.
+ """
+ if "." not in fqn:
+ return self.package_to_files.get(fqn, [])
+ package, local = fqn.rsplit(".", 1)
+ candidates = self.package_to_files.get(package, [])
+ local_lower = local.lower()
+ return [
+ p for p in candidates
+ if p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower() == local_lower
+ ]
+
+
+def _parse_settings(settings_file: Path) -> list[str]:
+ """Return Gradle module names from ``include(...)`` lines.
+
+ Module names use ``:foo:bar`` syntax; we keep them as-written so callers
+ can map ``:foo:bar`` → ``foo/bar`` directory.
+ """
+ if not settings_file.is_file():
+ return []
+ try:
+ text = settings_file.read_text(encoding="utf-8", errors="ignore")
+ except Exception:
+ return []
+ modules: list[str] = []
+ for match in _INCLUDE_RE.finditer(text):
+ for item in _INCLUDE_ITEM_RE.findall(match.group(1)):
+ modules.append(item.lstrip(":"))
+ for match in _INCLUDE_LINE_RE.finditer(text):
+ modules.append(match.group(2).lstrip(":"))
+ # Dedupe preserving order
+ seen: set[str] = set()
+ result: list[str] = []
+ for m in modules:
+ if m not in seen:
+ seen.add(m)
+ result.append(m)
+ return result
+
+
+def _module_dir(repo_path: Path, module_name: str) -> Path:
+ return repo_path / module_name.replace(":", "/")
+
+
+def _source_roots_for_module(module_dir: Path) -> list[str]:
+ """Return source-root paths (relative to module_dir) for *module_dir*.
+
+ Honours explicit ``srcDirs(...)`` overrides in ``build.gradle(.kts)``;
+ falls back to standard ``src/main/{kotlin,java}`` defaults.
+ """
+ overrides: list[str] = []
+ for build_name in ("build.gradle.kts", "build.gradle"):
+ build = module_dir / build_name
+ if not build.is_file():
+ continue
+ try:
+ text = build.read_text(encoding="utf-8", errors="ignore")
+ except Exception:
+ continue
+ for match in _SRCDIRS_RE.finditer(text):
+ for item in _INCLUDE_ITEM_RE.findall(match.group(1)):
+ overrides.append(item)
+ if overrides:
+ # Dedupe + return verbatim (caller resolves relative-to-module)
+ seen: set[str] = set()
+ return [o for o in overrides if not (o in seen or seen.add(o))]
+ return list(_DEFAULT_SRC_ROOTS)
+
+
+def build_kotlin_index(repo_path: Path | None) -> KotlinProjectIndex:
+ """Walk Gradle config + Kotlin sources to build the package-resolution index."""
+ index = KotlinProjectIndex()
+ if repo_path is None or not repo_path.is_dir():
+ return index
+
+ # Discover modules. Root-level Gradle build with no settings.gradle still
+ # counts as a single anonymous module rooted at repo_path.
+ settings_paths = [repo_path / "settings.gradle.kts", repo_path / "settings.gradle"]
+ modules: list[str] = []
+ for sp in settings_paths:
+ modules.extend(_parse_settings(sp))
+ if not modules:
+ # Single-module fallback: only consider the repo itself when a
+ # build.gradle is present.
+ if (
+ (repo_path / "build.gradle").is_file()
+ or (repo_path / "build.gradle.kts").is_file()
+ ):
+ modules = [""]
+
+ for module_name in modules:
+ mod_dir = _module_dir(repo_path, module_name) if module_name else repo_path
+ if not mod_dir.is_dir():
+ continue
+ roots = _source_roots_for_module(mod_dir)
+ rel_roots: list[str] = []
+ for root in roots:
+ root_path = (mod_dir / root).resolve()
+ if not root_path.is_dir():
+ continue
+ try:
+ rel = root_path.relative_to(repo_path.resolve()).as_posix()
+ except ValueError:
+ continue
+ rel_roots.append(rel)
+ # Walk Kotlin files under this root
+ for kt in root_path.rglob("*.kt"):
+ try:
+ rel_kt = kt.relative_to(repo_path.resolve()).as_posix()
+ except ValueError:
+ continue
+ try:
+ text = kt.read_text(encoding="utf-8", errors="ignore")
+ except Exception:
+ continue
+ pkg_match = _PACKAGE_RE.search(text)
+ if not pkg_match:
+ continue
+ package = pkg_match.group(1)
+ index.package_to_files.setdefault(package, []).append(rel_kt)
+ if rel_roots:
+ index.modules[module_name or "<root>"] = rel_roots
+ return index
+
+
+def get_or_build_kotlin_index(ctx: "ResolverContext") -> KotlinProjectIndex:
+ cached = getattr(ctx, "_kotlin_index", None)
+ if cached is not None:
+ return cached
+ index = build_kotlin_index(ctx.repo_path)
+ ctx._kotlin_index = index # type: ignore[attr-defined]
+ return index
+
+
+def resolve_via_kotlin_index(module_path: str, ctx: "ResolverContext") -> str | None:
+ index = get_or_build_kotlin_index(ctx)
+ matches = index.lookup_class(module_path)
+ if matches:
+ return matches[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 6256b15cf..531e77bc6 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/php.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/php.py
@@ -3,10 +3,18 @@
from __future__ import annotations
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."""
+ # 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.
+ psr4_match = resolve_via_psr4(module_path, ctx)
+ if psr4_match is not None:
+ return psr4_match
+
# Convert namespace separators to path separators
path_form = module_path.replace("\\", "/")
parts = path_form.split("/")
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/php_composer.py b/packages/core/src/repowise/core/ingestion/resolvers/php_composer.py
new file mode 100644
index 000000000..e6bc8e244
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/php_composer.py
@@ -0,0 +1,95 @@
+"""composer.json PSR-4 autoload parsing for PHP import resolution."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+
+def _normalise_dirs(value: object) -> list[str]:
+ """PSR-4 values may be a single string or a list of strings."""
+ if isinstance(value, str):
+ return [value.rstrip("/")]
+ if isinstance(value, list):
+ return [str(v).rstrip("/") for v in value if isinstance(v, str)]
+ return []
+
+
+def read_composer_psr4(repo_path: Path | None) -> dict[str, list[str]]:
+ """Read root ``composer.json`` and return ``{namespace_prefix: [dir, ...]}``.
+
+ Both ``autoload.psr-4`` and ``autoload-dev.psr-4`` are merged. Namespace
+ keys are returned with their trailing ``\\`` preserved (composer spec).
+ """
+ if repo_path is None:
+ return {}
+ composer = repo_path / "composer.json"
+ if not composer.is_file():
+ return {}
+ try:
+ data = json.loads(composer.read_text(encoding="utf-8", errors="ignore"))
+ except Exception:
+ return {}
+
+ result: dict[str, list[str]] = {}
+ for section in ("autoload", "autoload-dev"):
+ block = data.get(section) if isinstance(data, dict) else None
+ if not isinstance(block, dict):
+ continue
+ psr4 = block.get("psr-4")
+ if not isinstance(psr4, dict):
+ continue
+ for prefix, dirs in psr4.items():
+ if not isinstance(prefix, str):
+ continue
+ result.setdefault(prefix, []).extend(_normalise_dirs(dirs))
+ return result
+
+
+def get_or_build_psr4_map(ctx: "ResolverContext") -> dict[str, list[str]]:
+ cached = getattr(ctx, "_php_psr4_map", None)
+ if cached is not None:
+ return cached
+ psr4 = read_composer_psr4(ctx.repo_path)
+ ctx._php_psr4_map = psr4 # type: ignore[attr-defined]
+ return psr4
+
+
+def resolve_via_psr4(module_path: str, ctx: "ResolverContext") -> str | None:
+ """Try PSR-4 prefix matching from composer.json. Returns repo-relative
+ path or None.
+
+ *module_path* is the FQN as written in PHP (``Foo\\Bar\\Baz`` form).
+ """
+ psr4 = get_or_build_psr4_map(ctx)
+ if not psr4:
+ return None
+ fqn = module_path.replace("/", "\\")
+ # Longest-prefix match wins. Composer prefixes always end in `\\`.
+ best: tuple[str, list[str]] | None = None
+ for prefix, dirs in psr4.items():
+ if not prefix:
+ continue
+ if fqn.startswith(prefix) and (best is None or len(prefix) > len(best[0])):
+ best = (prefix, dirs)
+ if best is None:
+ return None
+ prefix, dirs = best
+ tail = fqn[len(prefix) :].replace("\\", "/")
+ if not tail:
+ return None
+ for base_dir in dirs:
+ candidate = f"{base_dir}/{tail}.php" if base_dir else f"{tail}.php"
+ if candidate in ctx.path_set:
+ return candidate
+ # 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:
+ 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 d447d9f67..f7312ab1a 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/ruby.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/ruby.py
@@ -31,4 +31,25 @@ def resolve_ruby_import(module_path: str, importer_path: str, ctx: ResolverConte
if p.endswith(rb_name) or PurePosixPath(p).name == PurePosixPath(rb_name).name:
return p
+ # Rails / Zeitwerk autoloading: ``require 'app/services/foo'`` style
+ # paths can also be resolved by walking the rails index's
+ # ``namespace_to_file`` map. Most Rails constant references are
+ # require-less and surface through ``ctx.rails_lookup`` from the call
+ # resolver / heritage extractor, not this function.
+ from .ruby_rails import get_or_build_rails_index
+
+ rails_index = get_or_build_rails_index(ctx)
+ if rails_index is not None and not module_path.startswith("."):
+ # Strip leading autoload-root prefixes (``app/services/foo`` →
+ # ``foo`` lookup against namespace_to_file).
+ normalised = module_path
+ for root in rails_index.autoload_roots:
+ prefix = f"{root}/"
+ if normalised.startswith(prefix):
+ normalised = normalised[len(prefix) :]
+ break
+ hit = rails_index.namespace_to_file.get(normalised)
+ if hit:
+ return hit
+
return ctx.add_external_node(module_path)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ruby_rails.py b/packages/core/src/repowise/core/ingestion/resolvers/ruby_rails.py
new file mode 100644
index 000000000..82e8c2687
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/ruby_rails.py
@@ -0,0 +1,115 @@
+"""Rails / Zeitwerk autoload index for Ruby import resolution.
+
+Real Rails apps barely use ``require``; class references like
+``UserController`` or ``Admin::Reports::Daily`` are resolved at runtime by
+Zeitwerk's convention: ``CamelCase`` constants live at
+``snake_case.rb`` files under one of a fixed set of autoload roots
+(``app/*``, ``lib/``).
+
+This index is detection-gated: returns ``None`` unless ``config/application.rb``
+exists. Non-Rails Ruby repos pay zero cost.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+
+_CAMEL_TO_SNAKE_RE = re.compile(r"(?<!^)(?=[A-Z])")
+
+
+def camel_to_snake(name: str) -> str:
+ """``UserController`` → ``user_controller``; ``HTTPRequest`` → ``h_t_t_p_request``.
+
+ Zeitwerk uses ``ActiveSupport::Inflector.underscore`` which collapses
+ runs of capitals (HTTPRequest → http_request); we approximate with a
+ second pass that handles the ``ABCDef`` → ``ab_c_def`` case.
+ """
+ # First pass: insert _ before any uppercase preceded by lowercase
+ s1 = re.sub(r"(.)([A-Z][a-z]+)", r"\1_\2", name)
+ s2 = re.sub(r"([a-z0-9])([A-Z])", r"\1_\2", s1)
+ return s2.lower()
+
+
+@dataclass
+class RailsIndex:
+ autoload_roots: list[str] = field(default_factory=list)
+ name_to_file: dict[str, str] = field(default_factory=dict)
+ namespace_to_file: dict[str, str] = field(default_factory=dict)
+
+ def lookup(self, constant: str) -> str | None:
+ """Resolve a constant reference (``UserController`` or ``Foo::Bar``)
+ to a repo-relative ``.rb`` path.
+ """
+ if "::" in constant:
+ parts = constant.split("::")
+ namespaced_path = "/".join(camel_to_snake(p) for p in parts)
+ hit = self.namespace_to_file.get(namespaced_path)
+ if hit:
+ return hit
+ # Fall back to last segment lookup
+ constant = parts[-1]
+ snake = camel_to_snake(constant)
+ return self.name_to_file.get(snake)
+
+
+_DEFAULT_AUTOLOAD_ROOTS = (
+ "app/models",
+ "app/controllers",
+ "app/services",
+ "app/jobs",
+ "app/mailers",
+ "app/helpers",
+ "app/channels",
+ "app/policies",
+ "lib",
+)
+
+
+def _is_rails_repo(repo_path: Path) -> bool:
+ return (repo_path / "config" / "application.rb").is_file()
+
+
+def build_rails_index(repo_path: Path | None) -> RailsIndex | None:
+ if repo_path is None or not repo_path.is_dir():
+ return None
+ if not _is_rails_repo(repo_path):
+ return None
+
+ index = RailsIndex()
+ repo_resolved = repo_path.resolve()
+
+ for root in _DEFAULT_AUTOLOAD_ROOTS:
+ root_path = repo_resolved / root
+ if not root_path.is_dir():
+ continue
+ index.autoload_roots.append(root)
+ for rb in root_path.rglob("*.rb"):
+ try:
+ rel = rb.relative_to(repo_resolved).as_posix()
+ except ValueError:
+ continue
+ stem = rb.stem
+ # Path under the autoload root (without extension)
+ try:
+ relative_to_root = rb.relative_to(root_path).with_suffix("").as_posix()
+ except ValueError:
+ continue
+ index.name_to_file.setdefault(stem, rel)
+ index.namespace_to_file.setdefault(relative_to_root, rel)
+ return index
+
+
+def get_or_build_rails_index(ctx: "ResolverContext") -> RailsIndex | None:
+ cached = getattr(ctx, "_ruby_rails_index", "__sentinel__")
+ if cached != "__sentinel__":
+ return cached # type: ignore[return-value]
+ index = build_rails_index(ctx.repo_path)
+ ctx._ruby_rails_index = index # type: ignore[attr-defined]
+ return index
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/rust.py b/packages/core/src/repowise/core/ingestion/resolvers/rust.py
index 5ccf1cc07..7be4b47a7 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/rust.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/rust.py
@@ -37,6 +37,24 @@ def resolve_rust_import(module_path: str, importer_path: str, ctx: ResolverConte
if resolved is not None:
return resolved
+ # Cargo workspace sibling crate: `use sibling_crate::...`
+ from .rust_workspace import get_or_build_cargo_workspace_index
+
+ ws_index = get_or_build_cargo_workspace_index(ctx)
+ if ws_index is not None:
+ 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:], ctx.path_set)
+ if resolved is None:
+ # Probe the crate root itself (lib.rs / main.rs) when the
+ # import has no further path segments.
+ for root_file in ("lib.rs", "main.rs"):
+ candidate = f"{sibling_src}/{root_file}"
+ if candidate in ctx.path_set:
+ return candidate
+ if resolved is not None:
+ return resolved
+
# External crate
return ctx.add_external_node(module_path)
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/rust_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/rust_workspace.py
new file mode 100644
index 000000000..47fb35e32
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/rust_workspace.py
@@ -0,0 +1,117 @@
+"""Cargo workspace index — maps sibling crate names to their src/ directories.
+
+A Cargo workspace declares member crates in the root ``Cargo.toml``::
+
+ [workspace]
+ members = ["crates/foo", "crates/bar"]
+
+Each member is a directory containing its own ``Cargo.toml`` with a
+``[package] name = "foo-thing"`` entry. Inside any sibling crate, a
+``use foo_thing::baz`` should resolve to ``crates/foo/src/lib.rs``-rooted
+modules (Cargo replaces ``-`` with ``_`` for the import identifier).
+
+The index is built lazily on first access via
+``ResolverContext.cargo_workspace_index`` and cached on the context.
+"""
+
+from __future__ import annotations
+
+import tomllib
+from dataclasses import dataclass
+from pathlib import Path
+
+import structlog
+
+log = structlog.get_logger(__name__)
+
+
+@dataclass(frozen=True)
+class CargoCrate:
+ """A workspace member crate."""
+
+ name: str # package name as it appears in Cargo.toml (may contain "-")
+ src_dir: str # repo-relative POSIX path to the crate's src/ directory
+
+
+@dataclass(frozen=True)
+class CargoWorkspaceIndex:
+ """Cargo workspace member index. Map from crate-import-name → src dir."""
+
+ crates: tuple[CargoCrate, ...]
+
+ def lookup(self, import_prefix: str) -> str | None:
+ """Find the src/ dir for a crate referenced as ``import_prefix::...``."""
+ # Cargo replaces "-" with "_" for the Rust import identifier.
+ for crate in self.crates:
+ normalised = crate.name.replace("-", "_")
+ if normalised == import_prefix:
+ return crate.src_dir
+ return None
+
+
+def get_or_build_cargo_workspace_index(ctx) -> CargoWorkspaceIndex | None:
+ """Lazily build (and cache) the Cargo workspace index for the current repo."""
+ cached = getattr(ctx, "_cargo_workspace_index", "__unset__")
+ if cached != "__unset__":
+ return cached # type: ignore[return-value]
+
+ index = _build_cargo_workspace_index(ctx)
+ setattr(ctx, "_cargo_workspace_index", index)
+ return index
+
+
+def _build_cargo_workspace_index(ctx) -> CargoWorkspaceIndex | None:
+ repo_path = getattr(ctx, "repo_path", None)
+ if not repo_path:
+ return None
+
+ root_toml = Path(repo_path) / "Cargo.toml"
+ if not root_toml.exists():
+ return None
+
+ try:
+ with open(root_toml, "rb") as f:
+ root_data = tomllib.load(f)
+ except (OSError, tomllib.TOMLDecodeError):
+ return None
+
+ workspace = root_data.get("workspace") or {}
+ members = workspace.get("members") or []
+ if not isinstance(members, list):
+ return None
+
+ crates: list[CargoCrate] = []
+ repo = Path(repo_path).resolve()
+
+ # Single-crate repo with a [package] at the root: still index it.
+ root_pkg = root_data.get("package") or {}
+ if root_pkg.get("name"):
+ crates.append(CargoCrate(name=str(root_pkg["name"]), src_dir="src"))
+
+ for member in members:
+ if not isinstance(member, str):
+ continue
+ member_path = (repo / member).resolve()
+ try:
+ member_rel = member_path.relative_to(repo).as_posix()
+ except ValueError:
+ continue
+ member_toml = member_path / "Cargo.toml"
+ if not member_toml.exists():
+ continue
+ try:
+ with open(member_toml, "rb") as f:
+ member_data = tomllib.load(f)
+ except (OSError, tomllib.TOMLDecodeError):
+ continue
+ pkg = member_data.get("package") or {}
+ name = pkg.get("name")
+ if not name:
+ continue
+ src_dir = f"{member_rel}/src" if member_rel else "src"
+ crates.append(CargoCrate(name=str(name), src_dir=src_dir))
+
+ if not crates:
+ return None
+ log.debug("Built Cargo workspace index", crate_count=len(crates))
+ return CargoWorkspaceIndex(crates=tuple(crates))
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/scala.py b/packages/core/src/repowise/core/ingestion/resolvers/scala.py
index 4b4d12ec3..ab426538c 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/scala.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/scala.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from .context import ResolverContext
+from .scala_build import resolve_via_scala_index
def resolve_scala_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
@@ -13,6 +14,13 @@ def resolve_scala_import(module_path: str, importer_path: str, ctx: ResolverCont
if local in ("*", "_"):
return None
+ # 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.
+ build_match = resolve_via_scala_index(module_path, ctx)
+ if build_match is not None:
+ return build_match
+
# Try stem lookup on the last name component
result = ctx.stem_lookup(local.lower())
if result and result.endswith(".scala"):
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/scala_build.py b/packages/core/src/repowise/core/ingestion/resolvers/scala_build.py
new file mode 100644
index 000000000..51ed3e255
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/scala_build.py
@@ -0,0 +1,165 @@
+"""SBT / Mill multi-project index for Scala import resolution.
+
+SBT's ``build.sbt`` declares subprojects as
+``lazy val core = project.in(file("core"))``. Mill's ``build.sc`` uses
+``object Foo extends ScalaModule { ... }`` (or ``CrossScalaModule``,
+``SbtModule``, etc.). This module parses both with conservative regex,
+discovers their source roots (defaults: ``src/main/scala`` for SBT,
+``<modulename>/src`` for Mill), and walks each root for ``package``
+declarations to build a ``{fully.qualified.Name → [path, ...]}`` map.
+"""
+
+from __future__ import annotations
+
+import re
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+
+_SBT_PROJECT_RE = re.compile(
+ r'lazy\s+val\s+(\w+)\s*=\s*(?:\([^)]*\)\s*=>\s*)?'
+ r'(?:project|Project)\b[^\n]*?\.in\(\s*file\(\s*"([^"]+)"\s*\)\s*\)',
+ re.DOTALL,
+)
+_MILL_OBJECT_RE = re.compile(
+ r'object\s+(\w+)\s+extends\s+([\w.]+(?:\s*with\s+[\w.]+)*)',
+)
+_PACKAGE_RE = re.compile(r"^\s*package\s+([\w.]+)", re.MULTILINE)
+
+
+@dataclass
+class ScalaProjectIndex:
+ build_tool: str = "none" # "sbt" | "mill" | "none"
+ projects: dict[str, str] = field(default_factory=dict) # name -> dir_posix
+ package_to_files: dict[str, list[str]] = field(default_factory=dict)
+
+ def lookup_class(self, fqn: str) -> list[str]:
+ if "." not in fqn:
+ return self.package_to_files.get(fqn, [])
+ package, local = fqn.rsplit(".", 1)
+ candidates = self.package_to_files.get(package, [])
+ local_lower = local.lower()
+ return [
+ p for p in candidates
+ if p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower() == local_lower
+ ]
+
+
+def _parse_build_sbt(repo_path: Path) -> dict[str, str]:
+ build = repo_path / "build.sbt"
+ if not build.is_file():
+ return {}
+ try:
+ text = build.read_text(encoding="utf-8", errors="ignore")
+ except Exception:
+ return {}
+ result: dict[str, str] = {}
+ for match in _SBT_PROJECT_RE.finditer(text):
+ result[match.group(1)] = match.group(2).strip("./")
+ return result
+
+
+def _parse_build_sc(repo_path: Path) -> dict[str, str]:
+ build = repo_path / "build.sc"
+ if not build.is_file():
+ return {}
+ try:
+ text = build.read_text(encoding="utf-8", errors="ignore")
+ except Exception:
+ return {}
+ result: dict[str, str] = {}
+ for match in _MILL_OBJECT_RE.finditer(text):
+ name = match.group(1)
+ parents = match.group(2)
+ if "Module" not in parents:
+ continue
+ # Mill convention: directory is the module name relative to repo root.
+ result[name] = name
+ return result
+
+
+def _scan_packages(repo_path: Path, project_dir: str, build_tool: str) -> dict[str, list[str]]:
+ """Walk a project's source tree, recording package declarations."""
+ found: dict[str, list[str]] = {}
+ proj_path = (repo_path / project_dir).resolve() if project_dir else repo_path.resolve()
+ if not proj_path.is_dir():
+ return found
+
+ # Likely source root layouts per build tool.
+ candidate_roots: list[Path] = []
+ if build_tool == "sbt":
+ candidate_roots.extend(
+ proj_path / sub for sub in ("src/main/scala", "src/main/java")
+ )
+ elif build_tool == "mill":
+ # Mill: files live directly under <module>/src or <module>/src/main/scala.
+ candidate_roots.append(proj_path / "src")
+ candidate_roots.append(proj_path / "src" / "main" / "scala")
+ # Always try the project root itself as a last-resort source root.
+ candidate_roots.append(proj_path)
+
+ seen: set[Path] = set()
+ for root in candidate_roots:
+ if not root.is_dir() or root in seen:
+ continue
+ seen.add(root)
+ for src in root.rglob("*.scala"):
+ try:
+ rel = src.relative_to(repo_path.resolve()).as_posix()
+ except ValueError:
+ continue
+ try:
+ text = src.read_text(encoding="utf-8", errors="ignore")
+ except Exception:
+ continue
+ pkg_match = _PACKAGE_RE.search(text)
+ if not pkg_match:
+ continue
+ found.setdefault(pkg_match.group(1), []).append(rel)
+ return found
+
+
+def build_scala_index(repo_path: Path | None) -> ScalaProjectIndex:
+ if repo_path is None or not repo_path.is_dir():
+ return ScalaProjectIndex()
+ sbt_projects = _parse_build_sbt(repo_path)
+ mill_projects = _parse_build_sc(repo_path)
+ if sbt_projects:
+ index = ScalaProjectIndex(build_tool="sbt", projects=sbt_projects)
+ elif mill_projects:
+ index = ScalaProjectIndex(build_tool="mill", projects=mill_projects)
+ else:
+ # No multi-project config: still scan repo root for package decls so
+ # standalone ``src/main/scala`` layouts are indexed.
+ if (repo_path / "build.sbt").is_file():
+ index = ScalaProjectIndex(build_tool="sbt", projects={"<root>": ""})
+ elif (repo_path / "build.sc").is_file():
+ index = ScalaProjectIndex(build_tool="mill", projects={"<root>": ""})
+ else:
+ return ScalaProjectIndex()
+
+ for _name, project_dir in index.projects.items():
+ for pkg, files in _scan_packages(repo_path, project_dir, index.build_tool).items():
+ index.package_to_files.setdefault(pkg, []).extend(files)
+ return index
+
+
+def get_or_build_scala_index(ctx: "ResolverContext") -> ScalaProjectIndex:
+ cached = getattr(ctx, "_scala_index", None)
+ if cached is not None:
+ return cached
+ index = build_scala_index(ctx.repo_path)
+ ctx._scala_index = index # type: ignore[attr-defined]
+ return index
+
+
+def resolve_via_scala_index(module_path: str, ctx: "ResolverContext") -> str | None:
+ index = get_or_build_scala_index(ctx)
+ matches = index.lookup_class(module_path)
+ if matches:
+ return matches[0]
+ return None
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/swift.py b/packages/core/src/repowise/core/ingestion/resolvers/swift.py
index 30973cc21..bc3be08f2 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/swift.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/swift.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from pathlib import PurePosixPath
from .context import ResolverContext
+from .swift_spm import resolve_via_swift_targets
def resolve_swift_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
@@ -12,6 +13,12 @@ def resolve_swift_import(module_path: str, importer_path: str, ctx: ResolverCont
parts = module_path.split(".")
local = parts[-1]
+ # Package.swift target → directory mapping (SPM is the dominant way Swift
+ # apps are structured today; consult before stem matching).
+ spm_match = resolve_via_swift_targets(module_path, ctx)
+ if spm_match is not None:
+ return spm_match
+
# Try stem lookup
result = ctx.stem_lookup(local.lower())
if result and result.endswith(".swift"):
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/swift_spm.py b/packages/core/src/repowise/core/ingestion/resolvers/swift_spm.py
new file mode 100644
index 000000000..9e2512ae6
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/swift_spm.py
@@ -0,0 +1,119 @@
+"""Swift Package Manager target → directory parsing.
+
+``Package.swift`` is itself Swift source, but real packages overwhelmingly
+use a small set of conventional declarations:
+
+ .target(name: "Foo")
+ .target(name: "Foo", path: "Custom/Path")
+ .executableTarget(name: "Bar")
+ .testTarget(name: "FooTests")
+
+Regex covers >95% of real-world packages without requiring tree-sitter-swift
+parsing. Targets that omit ``path:`` default to ``Sources/<name>`` (or
+``Tests/<name>`` for test targets).
+"""
+
+from __future__ import annotations
+
+import re
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+
+_TARGET_RE = re.compile(
+ r"\.(target|executableTarget|testTarget|systemLibrary|binaryTarget|plugin)\s*\("
+ r"(?P<body>[^()]*(?:\([^()]*\)[^()]*)*)\)",
+ re.DOTALL,
+)
+_NAME_RE = re.compile(r'name\s*:\s*"([^"]+)"')
+_PATH_RE = re.compile(r'path\s*:\s*"([^"]+)"')
+
+
+def parse_package_swift(path: Path) -> dict[str, str]:
+ """Return ``{module_name: source_dir_posix}`` extracted from a single
+ ``Package.swift`` file. Paths are relative to the file's directory.
+ """
+ if not path.is_file():
+ return {}
+ try:
+ text = path.read_text(encoding="utf-8", errors="ignore")
+ except Exception:
+ return {}
+
+ result: dict[str, str] = {}
+ for match in _TARGET_RE.finditer(text):
+ kind = match.group(1)
+ body = match.group("body")
+ name_match = _NAME_RE.search(body)
+ if not name_match:
+ continue
+ name = name_match.group(1)
+ path_match = _PATH_RE.search(body)
+ if path_match:
+ target_dir = path_match.group(1).strip("./")
+ else:
+ base = "Tests" if kind == "testTarget" else "Sources"
+ target_dir = f"{base}/{name}"
+ result[name] = target_dir
+ return result
+
+
+def build_swift_targets(repo_path: Path | None) -> dict[str, str]:
+ """Walk the repo for every ``Package.swift``, merge their target maps.
+
+ Each target's source dir is prefixed with the package's directory
+ relative to the repo root so the resolver can match against
+ repo-relative paths in ``ctx.path_set``.
+ """
+ if repo_path is None or not repo_path.is_dir():
+ return {}
+ merged: dict[str, str] = {}
+ for pkg_swift in repo_path.rglob("Package.swift"):
+ try:
+ pkg_dir = pkg_swift.parent.relative_to(repo_path).as_posix()
+ except ValueError:
+ continue
+ for name, target_dir in parse_package_swift(pkg_swift).items():
+ full = f"{pkg_dir}/{target_dir}".lstrip("/") if pkg_dir != "." else target_dir
+ merged.setdefault(name, full)
+ return merged
+
+
+def get_or_build_swift_targets(ctx: "ResolverContext") -> dict[str, str]:
+ cached = getattr(ctx, "_swift_targets", None)
+ if cached is not None:
+ return cached
+ mapping = build_swift_targets(ctx.repo_path)
+ ctx._swift_targets = mapping # type: ignore[attr-defined]
+ return mapping
+
+
+def resolve_via_swift_targets(module_path: str, ctx: "ResolverContext") -> str | None:
+ """Pick a ``.swift`` file under the SPM target's source dir matching the
+ last identifier of *module_path*. Returns repo-relative path or None.
+ """
+ mapping = get_or_build_swift_targets(ctx)
+ if not mapping:
+ return None
+ target_name = module_path.split(".")[0]
+ target_dir = mapping.get(target_name)
+ if not target_dir:
+ 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)]
+ if not matches:
+ # Module imported by name but no source files indexed yet (target may
+ # be excluded). Treat as unresolved; caller falls back further.
+ return None
+ last_id = module_path.split(".")[-1]
+ for p in matches:
+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0]
+ if stem.lower() == last_id.lower():
+ return p
+ # No stem hit — return the first file in the target so call/heritage
+ # resolution at least lands inside the right module.
+ return matches[0]
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
new file mode 100644
index 000000000..04f43664a
--- /dev/null
+++ b/packages/core/src/repowise/core/ingestion/resolvers/ts_workspace.py
@@ -0,0 +1,139 @@
+"""npm/yarn/pnpm workspace package resolution for TypeScript imports.
+
+Reads the root ``package.json``'s ``workspaces`` field (string list or
+``{"packages": [...]}`` form), expands glob patterns, and reads each
+sibling package's ``name`` field. The resulting ``{pkg_name: dir_posix}``
+map lets the TS resolver turn ``import x from "@myorg/foo"`` into the
+correct intra-repo file rather than an ``external:`` node.
+"""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from .context import ResolverContext
+
+
+def _read_workspaces_field(pkg_data: dict) -> list[str]:
+ ws = pkg_data.get("workspaces")
+ if isinstance(ws, list):
+ return [str(p) for p in ws if isinstance(p, str)]
+ if isinstance(ws, dict):
+ packages = ws.get("packages")
+ if isinstance(packages, list):
+ return [str(p) for p in packages if isinstance(p, str)]
+ return []
+
+
+def build_workspace_map(repo_path: Path | None) -> dict[str, str]:
+ """Return ``{package_name: dir_posix}`` for every workspace package.
+
+ Empty dict if no root ``package.json`` or no ``workspaces`` field.
+ """
+ if repo_path is None or not repo_path.is_dir():
+ return {}
+ root_pkg = repo_path / "package.json"
+ if not root_pkg.is_file():
+ return {}
+ try:
+ data = json.loads(root_pkg.read_text(encoding="utf-8", errors="ignore"))
+ except Exception:
+ return {}
+ if not isinstance(data, dict):
+ return {}
+ patterns = _read_workspaces_field(data)
+ if not patterns:
+ return {}
+
+ result: dict[str, str] = {}
+ for pattern in patterns:
+ # Glob each pattern relative to the repo root. ``pathlib.Path.glob``
+ # already understands ``*`` and ``**``.
+ for ws_dir in repo_path.glob(pattern):
+ if not ws_dir.is_dir():
+ continue
+ ws_pkg = ws_dir / "package.json"
+ if not ws_pkg.is_file():
+ continue
+ try:
+ ws_data = json.loads(ws_pkg.read_text(encoding="utf-8", errors="ignore"))
+ except Exception:
+ continue
+ if not isinstance(ws_data, dict):
+ continue
+ name = ws_data.get("name")
+ if not isinstance(name, str) or not name:
+ continue
+ try:
+ rel = ws_dir.relative_to(repo_path).as_posix()
+ except ValueError:
+ continue
+ result[name] = rel
+ return result
+
+
+def get_or_build_workspace_map(ctx: "ResolverContext") -> dict[str, str]:
+ cached = getattr(ctx, "_ts_workspace_map", None)
+ if cached is not None:
+ return cached
+ mapping = build_workspace_map(ctx.repo_path)
+ ctx._ts_workspace_map = mapping # type: ignore[attr-defined]
+ return mapping
+
+
+def resolve_via_workspaces(module_path: str, ctx: "ResolverContext") -> str | None:
+ """Resolve a bare specifier (``@scope/pkg`` or ``@scope/pkg/sub/file``)
+ against the workspace map. Returns a repo-relative path or None.
+ """
+ mapping = get_or_build_workspace_map(ctx)
+ if not mapping:
+ return None
+
+ # Match the longest package-name prefix. ``@scope/pkg/sub/x`` should bind
+ # ``@scope/pkg`` and resolve ``sub/x`` under that workspace's dir.
+ best: tuple[str, str] | None = None
+ for name, dir_posix in mapping.items():
+ if module_path == name or module_path.startswith(name + "/"):
+ if best is None or len(name) > len(best[0]):
+ best = (name, dir_posix)
+ if best is None:
+ return None
+ name, dir_posix = best
+ sub = module_path[len(name) :].lstrip("/")
+ base = f"{dir_posix}/{sub}" if sub else dir_posix
+
+ # When the import lacks an explicit file path, target the package's
+ # entry point. Try ``index.{ts,tsx,js,jsx}``.
+ if not sub:
+ for ext in (".ts", ".tsx", ".js", ".jsx"):
+ cand = f"{base}/index{ext}"
+ if cand in ctx.path_set:
+ return cand
+ # Read main/module from the workspace package.json
+ if ctx.repo_path is not None:
+ ws_pkg = ctx.repo_path / dir_posix / "package.json"
+ if ws_pkg.is_file():
+ try:
+ ws_data = json.loads(ws_pkg.read_text(encoding="utf-8", errors="ignore"))
+ except Exception:
+ ws_data = None
+ if isinstance(ws_data, dict):
+ for key in ("module", "main"):
+ entry = ws_data.get(key)
+ if isinstance(entry, str):
+ cand = f"{dir_posix}/{entry.lstrip('./')}"
+ if cand in ctx.path_set:
+ return cand
+ return None
+
+ # Sub-path: try explicit, then with extensions.
+ if base in ctx.path_set:
+ return base
+ for ext in (".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js"):
+ cand = base + ext if not ext.startswith("/") else base + ext
+ if cand in ctx.path_set:
+ return cand
+ return None
diff --git a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py b/packages/core/src/repowise/core/ingestion/resolvers/typescript.py
index 1717f2561..da4ec1ada 100644
--- a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py
+++ b/packages/core/src/repowise/core/ingestion/resolvers/typescript.py
@@ -5,6 +5,7 @@ from __future__ import annotations
from pathlib import Path
from .context import ResolverContext
+from .ts_workspace import resolve_via_workspaces
def resolve_ts_js_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:
@@ -13,7 +14,10 @@ def resolve_ts_js_import(module_path: str, importer_path: str, ctx: ResolverCont
if module_path.startswith("."):
base = importer_dir / module_path
- for ext in (".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js"):
+ exts: tuple[str, ...] = (".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js")
+ if ctx.has_sfc_files:
+ exts = exts + (".vue", ".svelte", ".astro")
+ for ext in exts:
candidate = Path(str(base) + ext).as_posix()
if candidate in ctx.path_set:
return candidate
@@ -33,5 +37,11 @@ def resolve_ts_js_import(module_path: str, importer_path: str, ctx: ResolverCont
if alias_resolved is not None:
return alias_resolved
+ # Workspace package (npm/yarn/pnpm ``workspaces``): turn ``@myorg/foo``
+ # into the sibling package's entry point rather than an external node.
+ workspace_resolved = resolve_via_workspaces(module_path, ctx)
+ if workspace_resolved is not None:
+ return workspace_resolved
+
# Fallback: external npm package.
return ctx.add_external_node(module_path)
diff --git a/packages/server/src/repowise/server/__init__.py b/packages/server/src/repowise/server/__init__.py
index 918e31eea..9f9364779 100644
--- a/packages/server/src/repowise/server/__init__.py
+++ b/packages/server/src/repowise/server/__init__.py
@@ -7,4 +7,4 @@ Provides:
- Background job scheduler (APScheduler)
"""
-__version__ = "0.3.1"
+__version__ = "0.4.0"
diff --git a/pyproject.toml b/pyproject.toml
index ef8208dc9..36fd4c175 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
[project]
name = "repowise"
-version = "0.3.1"
+version = "0.4.0"
description = "Codebase intelligence for developers and AI — generates and maintains a structured wiki for any codebase"
readme = "README.md"
requires-python = ">=3.11"
diff --git a/tests/integration/test_mcp.py b/tests/integration/test_mcp.py
index 6ad9ebb61..1e7fb97b9 100644
--- a/tests/integration/test_mcp.py
+++ b/tests/integration/test_mcp.py
@@ -352,10 +352,14 @@ async def test_mcp_full_exploration_flow(mcp_env):
overview = await get_overview()
assert "Sample Project" in overview["content_md"]
assert len(overview["key_modules"]) == 2
- assert overview["architecture_diagram_mermaid"] is not None
-
- # Step 2: Drill into auth module via get_context
- auth = await get_context(["src/auth"])
+ # `architecture_diagram_mermaid` was deliberately removed from get_overview
+ # — agents can request the diagram via get_architecture_diagram() instead.
+ assert "architecture_diagram_mermaid" not in overview
+
+ # Step 2: Drill into auth module via get_context.
+ # `content_md` is gated behind include=["full_doc"] to keep default
+ # responses cheap; the summary is always present.
+ auth = await get_context(["src/auth"], include=["full_doc"])
t = auth["targets"]["src/auth"]
assert t["type"] == "module"
assert "authentication" in t["docs"]["content_md"].lower()
diff --git a/tests/unit/ingestion/test_dynamic_hints_per_language.py b/tests/unit/ingestion/test_dynamic_hints_per_language.py
new file mode 100644
index 000000000..c7a6e138a
--- /dev/null
+++ b/tests/unit/ingestion/test_dynamic_hints_per_language.py
@@ -0,0 +1,183 @@
+"""Tests for H1-H8 per-language dynamic-hint extractors."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from repowise.core.ingestion.dynamic_hints.c import CDynamicHints
+from repowise.core.ingestion.dynamic_hints.go import GoDynamicHints
+from repowise.core.ingestion.dynamic_hints.luau import LuauDynamicHints
+from repowise.core.ingestion.dynamic_hints.php import PhpDynamicHints
+from repowise.core.ingestion.dynamic_hints.ruby import RubyDynamicHints
+from repowise.core.ingestion.dynamic_hints.scala import ScalaDynamicHints
+from repowise.core.ingestion.dynamic_hints.spring import SpringDynamicHints
+from repowise.core.ingestion.dynamic_hints.swift import SwiftDynamicHints
+
+
+class TestSpringHints:
+ def test_get_bean_resolves_to_class_file(self, tmp_path: Path) -> None:
+ (tmp_path / "Foo.java").write_text(
+ "package x;\nimport org.springframework.context.ApplicationContext;\n"
+ "public class Foo { void m(ApplicationContext c) { c.getBean(Bar.class); } }\n"
+ )
+ (tmp_path / "Bar.java").write_text("package x;\npublic class Bar {}\n")
+ edges = SpringDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "spring:get_bean"}
+ assert "Bar.java" in targets
+
+ def test_bean_factory_links_to_return_type(self, tmp_path: Path) -> None:
+ (tmp_path / "Cfg.java").write_text(
+ "package x;\nimport org.springframework.context.annotation.Bean;\n"
+ "public class Cfg {\n @Bean\n public Foo fooBean() { return new Foo(); }\n}\n"
+ )
+ (tmp_path / "Foo.java").write_text("package x;\npublic class Foo {}\n")
+ edges = SpringDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "spring:bean_factory"}
+ assert "Foo.java" in targets
+
+ def test_no_spring_no_edges(self, tmp_path: Path) -> None:
+ (tmp_path / "Foo.java").write_text("public class Foo {}\n")
+ assert SpringDynamicHints().extract(tmp_path) == []
+
+
+class TestRubyHints:
+ def test_send_resolves_method(self, tmp_path: Path) -> None:
+ (tmp_path / "a.rb").write_text("class A\n def hello; end\nend\n")
+ (tmp_path / "b.rb").write_text("class B\n def call(o); o.send(:hello); end\nend\n")
+ edges = RubyDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "ruby:send"}
+ assert "a.rb" in targets
+
+ def test_const_get(self, tmp_path: Path) -> None:
+ (tmp_path / "user.rb").write_text("class User\nend\n")
+ (tmp_path / "loader.rb").write_text(
+ "klass = Object.const_get(:User)\n"
+ )
+ edges = RubyDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "ruby:const_get"}
+ assert "user.rb" in targets
+
+
+class TestPhpHints:
+ def test_container_get_class(self, tmp_path: Path) -> None:
+ (tmp_path / "Foo.php").write_text("<?php\nclass Foo {}\n")
+ (tmp_path / "Bar.php").write_text(
+ "<?php\nclass Bar { function m($c) { return $c->get(Foo::class); } }\n"
+ )
+ edges = PhpDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "php:container_get"}
+ assert "Foo.php" in targets
+
+ def test_reflection_class(self, tmp_path: Path) -> None:
+ (tmp_path / "Foo.php").write_text("<?php\nclass Foo {}\n")
+ (tmp_path / "Use.php").write_text(
+ "<?php\n$r = new ReflectionClass(Foo::class);\n"
+ )
+ edges = PhpDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "php:reflection_class"}
+ assert "Foo.php" in targets
+
+
+class TestScalaHints:
+ def test_class_forname(self, tmp_path: Path) -> None:
+ (tmp_path / "Foo.scala").write_text("package x\nclass Foo\n")
+ (tmp_path / "Loader.scala").write_text(
+ "package x\nobject Loader { val c = Class.forName(\"x.Foo\") }\n"
+ )
+ edges = ScalaDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "scala:class_forname"}
+ assert "Foo.scala" in targets
+
+ def test_given(self, tmp_path: Path) -> None:
+ (tmp_path / "Ord.scala").write_text("package x\ntrait Ord\n")
+ (tmp_path / "Use.scala").write_text(
+ "package x\nobject Use { given intOrd: Ord = ??? }\n"
+ )
+ edges = ScalaDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "scala:given"}
+ assert "Ord.scala" in targets
+
+
+class TestSwiftHints:
+ def test_nsclass_from_string(self, tmp_path: Path) -> None:
+ (tmp_path / "MyClass.swift").write_text("class MyClass {}\n")
+ (tmp_path / "Use.swift").write_text(
+ "let c = NSClassFromString(\"MyClass\")\n"
+ )
+ edges = SwiftDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "swift:nsclass_from_string"}
+ assert "MyClass.swift" in targets
+
+ def test_selector(self, tmp_path: Path) -> None:
+ (tmp_path / "A.swift").write_text("func myAction() {}\n")
+ (tmp_path / "B.swift").write_text("let s = Selector(\"myAction\")\n")
+ edges = SwiftDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "swift:selector"}
+ assert "A.swift" in targets
+
+
+class TestCHints:
+ def test_function_pointer_assignment(self, tmp_path: Path) -> None:
+ (tmp_path / "ops.c").write_text(
+ "int do_thing(int x) { return x; }\n"
+ )
+ (tmp_path / "main.c").write_text(
+ "extern int do_thing(int);\nint main(){\n int (*fp)(int);\n fp = do_thing;\n return 0;\n}\n"
+ )
+ edges = CDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "c:fn_ptr"}
+ assert "ops.c" in targets
+
+ def test_dlopen_emits_external(self, tmp_path: Path) -> None:
+ (tmp_path / "main.c").write_text(
+ "#include <dlfcn.h>\nint main(){ void *h = dlopen(\"./libfoo.so\", 0); return 0; }\n"
+ )
+ edges = CDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "c:dlopen" for e in edges)
+
+
+class TestLuauHints:
+ def test_get_service(self, tmp_path: Path) -> None:
+ (tmp_path / "init.luau").write_text(
+ "local rs = game:GetService(\"ReplicatedStorage\")\n"
+ )
+ edges = LuauDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "luau:get_service" for e in edges)
+
+ def test_metatable_index(self, tmp_path: Path) -> None:
+ (tmp_path / "Base.luau").write_text("local Base = {}\nreturn Base\n")
+ (tmp_path / "Sub.luau").write_text(
+ "local Sub = {}\nsetmetatable(Sub, {__index = Base})\nreturn Sub\n"
+ )
+ edges = LuauDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "luau:metatable_index"}
+ assert "Base.luau" in targets
+
+
+class TestGoHints:
+ def test_reflect_typeof(self, tmp_path: Path) -> None:
+ (tmp_path / "types.go").write_text(
+ "package x\ntype Foo struct{}\n"
+ )
+ (tmp_path / "use.go").write_text(
+ "package x\nimport \"reflect\"\nvar _ = reflect.TypeOf(Foo{})\n"
+ )
+ edges = GoDynamicHints().extract(tmp_path)
+ targets = {e.target for e in edges if e.hint_source == "go:reflect_typeof"}
+ assert "types.go" in targets
+
+ def test_plugin_open_emits_external(self, tmp_path: Path) -> None:
+ (tmp_path / "main.go").write_text(
+ "package main\nimport \"plugin\"\nfunc main(){ plugin.Open(\"./p.so\") }\n"
+ )
+ edges = GoDynamicHints().extract(tmp_path)
+ assert any(e.hint_source == "go:plugin_open" for e in edges)
+
+
+class TestRegistryWiring:
+ def test_default_registry_includes_new_extractors(self) -> None:
+ from repowise.core.ingestion.dynamic_hints.registry import HintRegistry
+
+ names = {ex.name for ex in HintRegistry()._extractors}
+ for required in ("spring", "ruby", "php", "scala", "swift", "c", "luau", "go"):
+ assert required in names, f"missing {required}"
diff --git a/tests/unit/ingestion/test_express_framework_edges.py b/tests/unit/ingestion/test_express_framework_edges.py
new file mode 100644
index 000000000..af15e032a
--- /dev/null
+++ b/tests/unit/ingestion/test_express_framework_edges.py
@@ -0,0 +1,109 @@
+"""Unit tests for Express / NestJS framework edges (F4)."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+
+
+def _file_info(rel: str, abs_path: str) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=abs_path,
+ language="typescript",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _build_parsed(repo: Path) -> dict[str, ParsedFile]:
+ parser = ASTParser()
+ out: dict[str, ParsedFile] = {}
+ for src in repo.rglob("*.ts"):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ fi = _file_info(rel, str(src.resolve()))
+ out[rel] = parser.parse_file(fi, src.read_bytes())
+ return out
+
+
+def _ctx(repo: Path, parsed: dict[str, ParsedFile]) -> ResolverContext:
+ path_set = set(parsed.keys())
+ stem_map: dict[str, list[str]] = {}
+ for p in path_set:
+ stem = Path(p).stem.lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set, stem_map=stem_map, graph=nx.DiGraph(), repo_path=repo
+ )
+
+
+class TestExpress:
+ def test_app_use_router_links_to_router_file(self, tmp_path: Path) -> None:
+ (tmp_path / "users.router.ts").write_text(
+ "import { Router } from 'express';\n"
+ "export const usersRouter = Router();\n"
+ )
+ (tmp_path / "app.ts").write_text(
+ "import express from 'express';\n"
+ "import { usersRouter } from './users.router';\n"
+ "const app = express();\n"
+ "app.use('/users', usersRouter);\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["express"])
+ assert graph.has_edge("app.ts", "users.router.ts")
+
+
+class TestNestJS:
+ def test_module_controllers_array(self, tmp_path: Path) -> None:
+ (tmp_path / "users.controller.ts").write_text(
+ "import { Controller } from '@nestjs/common';\n"
+ "@Controller()\nexport class UsersController {}\n"
+ )
+ (tmp_path / "users.service.ts").write_text(
+ "import { Injectable } from '@nestjs/common';\n"
+ "@Injectable()\nexport class UsersService {}\n"
+ )
+ (tmp_path / "users.module.ts").write_text(
+ "import { Module } from '@nestjs/common';\n"
+ "import { UsersController } from './users.controller';\n"
+ "import { UsersService } from './users.service';\n"
+ "@Module({ controllers: [UsersController], providers: [UsersService] })\n"
+ "export class UsersModule {}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["nestjs"])
+ assert graph.has_edge("users.module.ts", "users.controller.ts")
+ assert graph.has_edge("users.module.ts", "users.service.ts")
+
+
+class TestExpressGate:
+ def test_no_express_no_edges(self, tmp_path: Path) -> None:
+ (tmp_path / "plain.ts").write_text("export const x = 1;\n")
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ count = add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert count == 0
diff --git a/tests/unit/ingestion/test_go_extractors.py b/tests/unit/ingestion/test_go_extractors.py
new file mode 100644
index 000000000..4c8f80e3c
--- /dev/null
+++ b/tests/unit/ingestion/test_go_extractors.py
@@ -0,0 +1,65 @@
+"""Unit tests for Go heritage (struct embedding) and binding extraction."""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+
+def _file(path: str = "foo.go") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language="go",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
+class TestGoSymbols:
+ def test_function_and_struct(self, parser: ASTParser) -> None:
+ src = b"package x\n\ntype User struct { Name string }\n\nfunc Hello() string { return \"\" }\n"
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "User" in names
+ assert "Hello" in names
+
+
+class TestGoHeritage:
+ def test_struct_embedding(self, parser: ASTParser) -> None:
+ src = b"package x\n\ntype Base struct{}\n\ntype Foo struct {\n Base\n Name string\n}\n"
+ result = parser.parse_file(_file(), src)
+ parents = {r.parent_name for r in result.heritage}
+ assert "Base" in parents
+
+
+class TestGoBindings:
+ def test_imports(self, parser: ASTParser) -> None:
+ src = b"package x\n\nimport (\n \"fmt\"\n \"net/http\"\n)\n"
+ result = parser.parse_file(_file(), src)
+ modules = [imp.module_path for imp in result.imports]
+ assert "fmt" in modules
+ assert "net/http" in modules
+
+
+class TestGoMethodReceiver:
+ def test_method_parent_extracted_from_receiver(self, parser: ASTParser) -> None:
+ src = b"package x\n\ntype User struct{}\n\nfunc (u *User) Greet() string { return \"\" }\n"
+ result = parser.parse_file(_file(), src)
+ greet = [s for s in result.symbols if s.name == "Greet"]
+ assert greet
+ assert greet[0].parent_name == "User"
diff --git a/tests/unit/ingestion/test_go_framework_edges.py b/tests/unit/ingestion/test_go_framework_edges.py
new file mode 100644
index 000000000..f0d9dc07f
--- /dev/null
+++ b/tests/unit/ingestion/test_go_framework_edges.py
@@ -0,0 +1,107 @@
+"""Unit tests for Gin/Echo/Chi framework edges (F5)."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+
+
+def _file_info(rel: str, abs_path: str) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=abs_path,
+ language="go",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _build_parsed(repo: Path) -> dict[str, ParsedFile]:
+ parser = ASTParser()
+ out: dict[str, ParsedFile] = {}
+ for src in repo.rglob("*.go"):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ fi = _file_info(rel, str(src.resolve()))
+ out[rel] = parser.parse_file(fi, src.read_bytes())
+ return out
+
+
+def _ctx(repo: Path, parsed: dict[str, ParsedFile]) -> ResolverContext:
+ path_set = set(parsed.keys())
+ stem_map: dict[str, list[str]] = {}
+ for p in path_set:
+ stem = Path(p).stem.lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set, stem_map=stem_map, graph=nx.DiGraph(), repo_path=repo
+ )
+
+
+class TestGinRoutes:
+ def test_pkg_function_handler(self, tmp_path: Path) -> None:
+ (tmp_path / "go.mod").write_text("module example.com/app\n\ngo 1.21\n")
+ users_dir = tmp_path / "users"
+ users_dir.mkdir()
+ (users_dir / "handler.go").write_text(
+ "package users\n\nimport \"github.com/gin-gonic/gin\"\n\n"
+ "func Index(c *gin.Context) {}\n"
+ )
+ (tmp_path / "main.go").write_text(
+ "package main\n\nimport (\n \"github.com/gin-gonic/gin\"\n \"example.com/app/users\"\n)\n\n"
+ "func main() {\n"
+ " r := gin.Default()\n"
+ " r.GET(\"/users\", users.Index)\n"
+ " r.Run()\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["gin"])
+ assert graph.has_edge("main.go", "users/handler.go")
+
+ def test_lambda_handler_ignored(self, tmp_path: Path) -> None:
+ (tmp_path / "main.go").write_text(
+ "package main\n\nimport \"github.com/gin-gonic/gin\"\n\n"
+ "func main() {\n"
+ " r := gin.Default()\n"
+ " r.GET(\"/ping\", func(c *gin.Context) {})\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ # Should not error or crash
+ add_framework_edges(graph, parsed, ctx, tech_stack=["gin"])
+ # Single file → no inter-file edges to itself
+ assert not graph.has_edge("main.go", "main.go")
+
+
+class TestGoRouterGate:
+ def test_non_router_unaffected(self, tmp_path: Path) -> None:
+ (tmp_path / "main.go").write_text(
+ "package main\n\nfunc main() {}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ count = add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert count == 0
diff --git a/tests/unit/ingestion/test_go_resolver.py b/tests/unit/ingestion/test_go_resolver.py
new file mode 100644
index 000000000..9dd4b71bc
--- /dev/null
+++ b/tests/unit/ingestion/test_go_resolver.py
@@ -0,0 +1,84 @@
+"""Unit tests for the Go multi-module resolver."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.go import (
+ read_go_modules,
+ resolve_go_import,
+)
+
+
+def _ctx(repo: Path, paths: list[str], go_modules: tuple = ()) -> ResolverContext:
+ path_set = set(paths)
+ stem_map: dict[str, list[str]] = {}
+ for p in paths:
+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set,
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ go_modules=go_modules,
+ )
+
+
+class TestReadGoModules:
+ def test_finds_root_and_nested_modules(self, tmp_path: Path) -> None:
+ (tmp_path / "go.mod").write_text("module github.com/me/root\n")
+ (tmp_path / "services" / "foo").mkdir(parents=True)
+ (tmp_path / "services" / "foo" / "go.mod").write_text(
+ "module github.com/me/foo\n"
+ )
+ modules = read_go_modules(tmp_path)
+ # Longest first: foo's path is shorter than root's? Both equal length
+ # — but ``github.com/me/foo`` (19) vs ``github.com/me/root`` (20).
+ # We just assert both modules are present.
+ names = [m for _, m in modules]
+ assert "github.com/me/root" in names
+ assert "github.com/me/foo" in names
+
+ def test_skips_vendor(self, tmp_path: Path) -> None:
+ (tmp_path / "vendor" / "x").mkdir(parents=True)
+ (tmp_path / "vendor" / "x" / "go.mod").write_text("module vendored\n")
+ assert read_go_modules(tmp_path) == ()
+
+
+class TestResolveGoImport:
+ def test_multi_module_picks_nearest_module(self, tmp_path: Path) -> None:
+ ctx = _ctx(
+ tmp_path,
+ ["services/foo/handler.go", "libs/bar/util.go"],
+ go_modules=(
+ ("services/foo", "github.com/me/foo"),
+ ("libs/bar", "github.com/me/bar"),
+ ),
+ )
+ # Sort longest-first as the real builder does.
+ ctx.go_modules = tuple(sorted(ctx.go_modules, key=lambda t: len(t[1]), reverse=True))
+ result = resolve_go_import("github.com/me/bar", "services/foo/handler.go", ctx)
+ assert result == "libs/bar/util.go"
+
+ def test_single_module_back_compat(self, tmp_path: Path) -> None:
+ # Build via legacy ``go_module_path`` only (no go_modules tuple).
+ path_set = {"pkg/util.go"}
+ stem_map = {"util": ["pkg/util.go"]}
+ ctx = ResolverContext(
+ path_set=path_set,
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=tmp_path,
+ go_module_path="github.com/me/root",
+ )
+ result = resolve_go_import("github.com/me/root/pkg", "main.go", ctx)
+ assert result == "pkg/util.go"
+
+ def test_external_falls_back(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["pkg/util.go"])
+ result = resolve_go_import("github.com/external/lib", "main.go", ctx)
+ assert result == "external:github.com/external/lib"
diff --git a/tests/unit/ingestion/test_java_extractors.py b/tests/unit/ingestion/test_java_extractors.py
new file mode 100644
index 000000000..e9998dc5f
--- /dev/null
+++ b/tests/unit/ingestion/test_java_extractors.py
@@ -0,0 +1,70 @@
+"""Unit tests for Java heritage, binding, and module-Javadoc extraction."""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+
+def _file(path: str = "Foo.java") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language="java",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
+class TestJavaHeritage:
+ def test_extends_and_implements(self, parser: ASTParser) -> None:
+ src = b"package x;\npublic class Foo extends Base implements IBar, IBaz {}\n"
+ result = parser.parse_file(_file(), src)
+ rels = {(r.parent_name, r.kind) for r in result.heritage}
+ assert ("Base", "extends") in rels
+ assert ("IBar", "implements") in rels
+ assert ("IBaz", "implements") in rels
+
+ def test_interface_extends(self, parser: ASTParser) -> None:
+ src = b"package x;\npublic interface IFoo extends IBase {}\n"
+ result = parser.parse_file(_file(), src)
+ rels = {(r.parent_name, r.kind) for r in result.heritage}
+ assert any(p == "IBase" for p, _ in rels)
+
+
+class TestJavaRecords:
+ def test_record_declaration_captured(self, parser: ASTParser) -> None:
+ src = b"package x;\npublic record Point(double x, double y) {}\n"
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "Point" in names
+
+
+class TestJavaBindings:
+ def test_import_produces_binding(self, parser: ASTParser) -> None:
+ src = b"package x;\nimport com.example.Foo;\nimport static com.example.Bar.baz;\npublic class App {}\n"
+ result = parser.parse_file(_file(), src)
+ modules = [imp.module_path for imp in result.imports]
+ assert "com.example.Foo" in modules
+
+
+class TestJavaModuleDocstring:
+ def test_module_javadoc_extracted(self, parser: ASTParser) -> None:
+ src = b"/**\n * Module-level summary line.\n */\npackage x;\npublic class Foo {}\n"
+ result = parser.parse_file(_file(), src)
+ assert result.docstring is not None
+ assert "Module-level summary" in result.docstring
diff --git a/tests/unit/ingestion/test_kotlin_extractors.py b/tests/unit/ingestion/test_kotlin_extractors.py
new file mode 100644
index 000000000..310c76a3d
--- /dev/null
+++ b/tests/unit/ingestion/test_kotlin_extractors.py
@@ -0,0 +1,92 @@
+"""Unit tests for Kotlin symbol extraction.
+
+Phase 1 baseline coverage — covers class, object, and interface
+declarations. In ``tree-sitter-kotlin`` the ``interface Foo {}`` form
+parses as a ``class_declaration`` with ``interface`` as the leading
+keyword child (NOT a separate ``interface_declaration`` node), so the
+existing ``class_declaration`` capture in ``kotlin.scm`` already picks
+interfaces up. These tests pin that behavior so any future grammar
+upgrade or query change is caught immediately.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+
+def _file(path: str = "Foo.kt") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language="kotlin",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
+class TestKotlinSymbols:
+ def test_interface_captured_as_class_declaration(self, parser: ASTParser) -> None:
+ # tree-sitter-kotlin parses `interface Foo {}` as class_declaration
+ # with `interface` as a keyword child; the existing
+ # class_declaration capture covers it (kind="class").
+ src = b"""\
+package com.example
+
+interface Greeter {
+ fun greet(): String
+}
+"""
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "Greeter" in names
+
+ def test_class_declaration_still_captured(self, parser: ASTParser) -> None:
+ src = b"""\
+package com.example
+
+class Foo {
+ fun bar(): Int = 1
+}
+"""
+ result = parser.parse_file(_file(), src)
+ names = {(s.name, s.kind) for s in result.symbols}
+ assert ("Foo", "class") in names
+
+ def test_object_declaration_still_captured(self, parser: ASTParser) -> None:
+ src = b"""\
+package com.example
+
+object Singleton {
+ fun work() {}
+}
+"""
+ result = parser.parse_file(_file(), src)
+ names = {(s.name, s.kind) for s in result.symbols}
+ assert ("Singleton", "class") in names
+
+ def test_interface_alongside_class(self, parser: ASTParser) -> None:
+ src = b"""\
+package com.example
+
+interface Repo
+class UserRepo : Repo
+"""
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "Repo" in names
+ assert "UserRepo" in names
diff --git a/tests/unit/ingestion/test_kotlin_resolver.py b/tests/unit/ingestion/test_kotlin_resolver.py
new file mode 100644
index 000000000..0518e5e94
--- /dev/null
+++ b/tests/unit/ingestion/test_kotlin_resolver.py
@@ -0,0 +1,73 @@
+"""Unit tests for the Kotlin Gradle-aware import resolver."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.kotlin import resolve_kotlin_import
+from repowise.core.ingestion.resolvers.kotlin_gradle import build_kotlin_index
+
+
+def _ctx(repo: Path, paths: list[str]) -> ResolverContext:
+ path_set = set(paths)
+ stem_map: dict[str, list[str]] = {}
+ for p in paths:
+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set,
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ )
+
+
+def _make_module(repo: Path, name: str, package: str, class_name: str) -> str:
+ src_dir = repo / name / "src" / "main" / "kotlin" / package.replace(".", "/")
+ src_dir.mkdir(parents=True)
+ file_path = src_dir / f"{class_name}.kt"
+ file_path.write_text(f"package {package}\n\nclass {class_name}\n")
+ return file_path.relative_to(repo).as_posix()
+
+
+class TestKotlinIndex:
+ def test_settings_gradle_subprojects(self, tmp_path: Path) -> None:
+ (tmp_path / "settings.gradle.kts").write_text(
+ 'include("app", "core", "feature-foo")\n'
+ )
+ (tmp_path / "build.gradle.kts").write_text("// root\n")
+ # Create app module
+ _make_module(tmp_path, "app", "com.example.app", "MainActivity")
+ _make_module(tmp_path, "core", "com.example.core", "Engine")
+ index = build_kotlin_index(tmp_path)
+ assert "app" in index.modules
+ assert "core" in index.modules
+ assert "com.example.app" in index.package_to_files
+ assert "com.example.core" in index.package_to_files
+
+ def test_resolves_class_to_module_file(self, tmp_path: Path) -> None:
+ (tmp_path / "settings.gradle").write_text('include "core"\n')
+ (tmp_path / "build.gradle").write_text("// root\n")
+ rel = _make_module(tmp_path, "core", "com.example", "Engine")
+ ctx = _ctx(tmp_path, [rel])
+ result = resolve_kotlin_import("com.example.Engine", "main.kt", ctx)
+ assert result == rel
+
+ def test_falls_through_without_gradle(self, tmp_path: Path) -> None:
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "Foo.kt").write_text("class Foo\n")
+ ctx = _ctx(tmp_path, ["src/Foo.kt"])
+ result = resolve_kotlin_import("com.example.Foo", "main.kt", ctx)
+ assert result == "src/Foo.kt"
+
+ def test_single_module_root_build_gradle(self, tmp_path: Path) -> None:
+ (tmp_path / "build.gradle.kts").write_text("// single module\n")
+ src = tmp_path / "src" / "main" / "kotlin" / "com" / "example"
+ src.mkdir(parents=True)
+ (src / "Util.kt").write_text("package com.example\n\nclass Util\n")
+ 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"
diff --git a/tests/unit/ingestion/test_laravel_framework_edges.py b/tests/unit/ingestion/test_laravel_framework_edges.py
new file mode 100644
index 000000000..9ad30057d
--- /dev/null
+++ b/tests/unit/ingestion/test_laravel_framework_edges.py
@@ -0,0 +1,172 @@
+"""Unit tests for Laravel framework edges (F3)."""
+
+from __future__ import annotations
+
+import json
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+
+
+def _file_info(rel: str, abs_path: str) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=abs_path,
+ language="php",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _build_parsed(repo: Path) -> dict[str, ParsedFile]:
+ parser = ASTParser()
+ out: dict[str, ParsedFile] = {}
+ for php in repo.rglob("*.php"):
+ rel = php.resolve().relative_to(repo.resolve()).as_posix()
+ fi = _file_info(rel, str(php.resolve()))
+ out[rel] = parser.parse_file(fi, php.read_bytes())
+ return out
+
+
+def _ctx(repo: Path, parsed: dict[str, ParsedFile]) -> ResolverContext:
+ path_set = set(parsed.keys())
+ stem_map: dict[str, list[str]] = {}
+ for p in path_set:
+ stem = Path(p).stem.lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set, stem_map=stem_map, graph=nx.DiGraph(), repo_path=repo
+ )
+
+
+def _make_composer(repo: Path, psr4: dict[str, str]) -> None:
+ (repo / "composer.json").write_text(
+ json.dumps({"autoload": {"psr-4": psr4}})
+ )
+
+
+class TestLaravelRoutes:
+ def test_array_syntax_route_to_controller(self, tmp_path: Path) -> None:
+ _make_composer(tmp_path, {"App\\": "src/"})
+ ctrl_dir = tmp_path / "src" / "Http" / "Controllers"
+ ctrl_dir.mkdir(parents=True)
+ (ctrl_dir / "UsersController.php").write_text(
+ "<?php\nnamespace App\\Http\\Controllers;\nclass UsersController {}\n"
+ )
+ routes_dir = tmp_path / "routes"
+ routes_dir.mkdir()
+ (routes_dir / "web.php").write_text(
+ "<?php\nuse App\\Http\\Controllers\\UsersController;\n"
+ "Route::get('/users', [UsersController::class, 'index']);\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["laravel"])
+ assert graph.has_edge(
+ "routes/web.php", "src/Http/Controllers/UsersController.php"
+ )
+
+ def test_legacy_string_route_to_controller(self, tmp_path: Path) -> None:
+ _make_composer(tmp_path, {"App\\": "src/"})
+ ctrl_dir = tmp_path / "src"
+ ctrl_dir.mkdir(parents=True)
+ (ctrl_dir / "UsersController.php").write_text(
+ "<?php\nnamespace App;\nclass UsersController {}\n"
+ )
+ routes_dir = tmp_path / "routes"
+ routes_dir.mkdir()
+ (routes_dir / "api.php").write_text(
+ "<?php\nRoute::get('/users', 'UsersController@index');\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["laravel"])
+ assert graph.has_edge("routes/api.php", "src/UsersController.php")
+
+
+class TestLaravelServiceProvider:
+ def test_bind_links_provider_to_classes(self, tmp_path: Path) -> None:
+ _make_composer(tmp_path, {"App\\": "src/"})
+ src = tmp_path / "src"
+ src.mkdir()
+ (src / "PaymentInterface.php").write_text(
+ "<?php\nnamespace App;\ninterface PaymentInterface {}\n"
+ )
+ (src / "StripePayment.php").write_text(
+ "<?php\nnamespace App;\nclass StripePayment implements PaymentInterface {}\n"
+ )
+ (src / "AppServiceProvider.php").write_text(
+ "<?php\nnamespace App;\nclass AppServiceProvider {\n"
+ " public function register() {\n"
+ " $this->app->bind(PaymentInterface::class, StripePayment::class);\n"
+ " }\n}\n"
+ )
+ # Need a route file to enable the slice
+ (tmp_path / "routes").mkdir()
+ (tmp_path / "routes" / "web.php").write_text("<?php\n")
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert graph.has_edge(
+ "src/AppServiceProvider.php", "src/PaymentInterface.php"
+ )
+ assert graph.has_edge(
+ "src/AppServiceProvider.php", "src/StripePayment.php"
+ )
+
+
+class TestLaravelEloquent:
+ def test_has_many_links_models(self, tmp_path: Path) -> None:
+ _make_composer(tmp_path, {"App\\": "src/"})
+ models = tmp_path / "src" / "Models"
+ models.mkdir(parents=True)
+ (models / "User.php").write_text(
+ "<?php\nnamespace App\\Models;\n"
+ "class User {\n"
+ " public function orders() { return $this->hasMany(Order::class); }\n"
+ "}\n"
+ )
+ (models / "Order.php").write_text(
+ "<?php\nnamespace App\\Models;\nclass Order {}\n"
+ )
+ (tmp_path / "routes").mkdir()
+ (tmp_path / "routes" / "web.php").write_text("<?php\n")
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert graph.has_edge("src/Models/User.php", "src/Models/Order.php")
+
+
+class TestLaravelGate:
+ def test_no_route_files_no_edges(self, tmp_path: Path) -> None:
+ (tmp_path / "Plain.php").write_text("<?php\nclass Plain {}\n")
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ count = add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert count == 0
diff --git a/tests/unit/ingestion/test_php_extractors.py b/tests/unit/ingestion/test_php_extractors.py
new file mode 100644
index 000000000..66d340ace
--- /dev/null
+++ b/tests/unit/ingestion/test_php_extractors.py
@@ -0,0 +1,67 @@
+"""Unit tests for PHP heritage, traits, bindings, and const/property captures."""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+
+def _file(path: str = "Foo.php") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language="php",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
+class TestPhpHeritage:
+ def test_extends_implements(self, parser: ASTParser) -> None:
+ src = b"<?php\nclass Foo extends Base implements IBar {}\n"
+ result = parser.parse_file(_file(), src)
+ parents = {r.parent_name for r in result.heritage}
+ assert "Base" in parents
+ assert "IBar" in parents
+
+ def test_use_trait(self, parser: ASTParser) -> None:
+ src = b"<?php\nclass Foo {\n use TimestampedTrait;\n}\n"
+ result = parser.parse_file(_file(), src)
+ parents = {r.parent_name for r in result.heritage}
+ assert "TimestampedTrait" in parents
+
+
+class TestPhpCaptures:
+ def test_const_declaration(self, parser: ASTParser) -> None:
+ src = b"<?php\nclass Foo { const ITEMS = 10; }\n"
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "ITEMS" in names
+
+ def test_property_declaration(self, parser: ASTParser) -> None:
+ src = b"<?php\nclass Foo { public $name = 'a'; }\n"
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "name" in names
+
+
+class TestPhpBindings:
+ def test_use_declaration(self, parser: ASTParser) -> None:
+ src = b"<?php\nuse App\\Service\\UserService;\nclass Foo {}\n"
+ result = parser.parse_file(_file(), src)
+ modules = [imp.module_path for imp in result.imports]
+ assert any("UserService" in m for m in modules)
diff --git a/tests/unit/ingestion/test_php_resolver.py b/tests/unit/ingestion/test_php_resolver.py
new file mode 100644
index 000000000..7ffb2c44d
--- /dev/null
+++ b/tests/unit/ingestion/test_php_resolver.py
@@ -0,0 +1,94 @@
+"""Unit tests for the PHP / composer.json-aware import resolver."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.php import resolve_php_import
+from repowise.core.ingestion.resolvers.php_composer import (
+ read_composer_psr4,
+ resolve_via_psr4,
+)
+
+
+def _ctx(repo: Path, paths: list[str]) -> ResolverContext:
+ path_set = set(paths)
+ stem_map: dict[str, list[str]] = {}
+ for p in paths:
+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set,
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ )
+
+
+def _write_composer(repo: Path, autoload: dict, autoload_dev: dict | None = None) -> None:
+ data: dict = {"autoload": {"psr-4": autoload}}
+ if autoload_dev is not None:
+ data["autoload-dev"] = {"psr-4": autoload_dev}
+ (repo / "composer.json").write_text(json.dumps(data))
+
+
+class TestComposerParsing:
+ def test_psr4_single_string_value(self, tmp_path: Path) -> None:
+ _write_composer(tmp_path, {"App\\": "src/"})
+ psr4 = read_composer_psr4(tmp_path)
+ assert psr4 == {"App\\": ["src"]}
+
+ def test_psr4_list_value(self, tmp_path: Path) -> None:
+ _write_composer(tmp_path, {"App\\": ["src/", "lib/"]})
+ psr4 = read_composer_psr4(tmp_path)
+ assert psr4 == {"App\\": ["src", "lib"]}
+
+ def test_psr4_merges_autoload_dev(self, tmp_path: Path) -> None:
+ _write_composer(tmp_path, {"App\\": "src/"}, autoload_dev={"Tests\\": "tests/"})
+ psr4 = read_composer_psr4(tmp_path)
+ assert psr4 == {"App\\": ["src"], "Tests\\": ["tests"]}
+
+ def test_missing_composer(self, tmp_path: Path) -> None:
+ assert read_composer_psr4(tmp_path) == {}
+
+
+class TestPsr4Resolution:
+ def test_longest_prefix_wins(self, tmp_path: Path) -> None:
+ _write_composer(tmp_path, {"App\\": "src/", "App\\Foo\\": "lib/"})
+ ctx = _ctx(tmp_path, ["src/Bar.php", "lib/Baz.php"])
+ # App\Foo\Baz should hit the longer prefix and resolve under lib/.
+ assert resolve_via_psr4("App\\Foo\\Baz", ctx) == "lib/Baz.php"
+
+ def test_psr4_resolves_nested_namespace(self, tmp_path: Path) -> None:
+ _write_composer(tmp_path, {"App\\": "src/"})
+ ctx = _ctx(tmp_path, ["src/Models/User.php"])
+ assert resolve_via_psr4("App\\Models\\User", ctx) == "src/Models/User.php"
+
+ def test_falls_through_when_no_match(self, tmp_path: Path) -> None:
+ _write_composer(tmp_path, {"App\\": "src/"})
+ ctx = _ctx(tmp_path, ["src/Foo.php"])
+ assert resolve_via_psr4("Vendor\\Lib\\Thing", ctx) is None
+
+
+class TestPhpResolverIntegration:
+ def test_psr4_match_takes_priority_over_stem(self, tmp_path: Path) -> None:
+ # Two ``Foo.php`` files exist; PSR-4 should pick the one under src/.
+ _write_composer(tmp_path, {"App\\": "src/"})
+ ctx = _ctx(tmp_path, ["src/Models/Foo.php", "vendor/other/Foo.php"])
+ result = resolve_php_import("App\\Models\\Foo", "src/Models/Foo.php", ctx)
+ assert result == "src/Models/Foo.php"
+
+ def test_missing_composer_falls_through_to_stem_lookup(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["lib/Foo.php"])
+ result = resolve_php_import("Foo", "lib/Foo.php", ctx)
+ assert result == "lib/Foo.php"
+
+ def test_unknown_namespace_becomes_external(self, tmp_path: Path) -> None:
+ _write_composer(tmp_path, {"App\\": "src/"})
+ ctx = _ctx(tmp_path, ["src/Foo.php"])
+ result = resolve_php_import("Vendor\\Lib\\Missing", "src/Foo.php", ctx)
+ assert result == "external:Vendor\\Lib\\Missing"
diff --git a/tests/unit/ingestion/test_rails_framework_edges.py b/tests/unit/ingestion/test_rails_framework_edges.py
new file mode 100644
index 000000000..862c5c7b3
--- /dev/null
+++ b/tests/unit/ingestion/test_rails_framework_edges.py
@@ -0,0 +1,166 @@
+"""Unit tests for Rails framework edges (F2)."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+
+
+def _file_info(rel: str, abs_path: str, language: str = "ruby") -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=abs_path,
+ language=language,
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=rel.startswith("config/"),
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _build_parsed(repo: Path) -> dict[str, ParsedFile]:
+ parser = ASTParser()
+ out: dict[str, ParsedFile] = {}
+ for rb in repo.rglob("*.rb"):
+ rel = rb.resolve().relative_to(repo.resolve()).as_posix()
+ fi = _file_info(rel, str(rb.resolve()))
+ out[rel] = parser.parse_file(fi, rb.read_bytes())
+ return out
+
+
+def _ctx(repo: Path, parsed: dict[str, ParsedFile]) -> ResolverContext:
+ path_set = set(parsed.keys())
+ stem_map: dict[str, list[str]] = {}
+ for p in path_set:
+ stem = Path(p).stem.lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set, stem_map=stem_map, graph=nx.DiGraph(), repo_path=repo
+ )
+
+
+def _make_rails_app(repo: Path) -> None:
+ (repo / "config").mkdir(parents=True)
+ (repo / "config" / "application.rb").write_text("module App; class Application; end; end\n")
+
+
+class TestRailsRoutes:
+ def test_resources_routes_to_controller(self, tmp_path: Path) -> None:
+ _make_rails_app(tmp_path)
+ (tmp_path / "config" / "routes.rb").write_text(
+ "Rails.application.routes.draw do\n resources :users\nend\n"
+ )
+ ctrl_dir = tmp_path / "app" / "controllers"
+ ctrl_dir.mkdir(parents=True)
+ (ctrl_dir / "users_controller.rb").write_text("class UsersController; end\n")
+
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["rails"])
+ assert graph.has_edge("config/routes.rb", "app/controllers/users_controller.rb")
+
+ def test_get_to_routes_to_controller(self, tmp_path: Path) -> None:
+ _make_rails_app(tmp_path)
+ (tmp_path / "config" / "routes.rb").write_text(
+ 'Rails.application.routes.draw do\n get "/foo", to: "users#index"\nend\n'
+ )
+ ctrl_dir = tmp_path / "app" / "controllers"
+ ctrl_dir.mkdir(parents=True)
+ (ctrl_dir / "users_controller.rb").write_text("class UsersController; end\n")
+
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["rails"])
+ assert graph.has_edge("config/routes.rb", "app/controllers/users_controller.rb")
+
+ def test_namespace_block_resolves_nested_controller(self, tmp_path: Path) -> None:
+ _make_rails_app(tmp_path)
+ (tmp_path / "config" / "routes.rb").write_text(
+ "Rails.application.routes.draw do\n"
+ " namespace :admin do\n"
+ " resources :reports\n"
+ " end\n"
+ "end\n"
+ )
+ admin_dir = tmp_path / "app" / "controllers" / "admin"
+ admin_dir.mkdir(parents=True)
+ (admin_dir / "reports_controller.rb").write_text(
+ "module Admin; class ReportsController; end; end\n"
+ )
+
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["rails"])
+ assert graph.has_edge(
+ "config/routes.rb", "app/controllers/admin/reports_controller.rb"
+ )
+
+
+class TestRailsActiveRecord:
+ def test_belongs_to_links_models(self, tmp_path: Path) -> None:
+ _make_rails_app(tmp_path)
+ models_dir = tmp_path / "app" / "models"
+ models_dir.mkdir(parents=True)
+ (models_dir / "order.rb").write_text(
+ "class Order < ApplicationRecord\n belongs_to :user\nend\n"
+ )
+ (models_dir / "user.rb").write_text("class User < ApplicationRecord; end\n")
+
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["rails"])
+ assert graph.has_edge("app/models/order.rb", "app/models/user.rb")
+
+ def test_has_many_singularizes(self, tmp_path: Path) -> None:
+ _make_rails_app(tmp_path)
+ models_dir = tmp_path / "app" / "models"
+ models_dir.mkdir(parents=True)
+ (models_dir / "user.rb").write_text(
+ "class User < ApplicationRecord\n has_many :orders\nend\n"
+ )
+ (models_dir / "order.rb").write_text("class Order < ApplicationRecord; end\n")
+
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["rails"])
+ assert graph.has_edge("app/models/user.rb", "app/models/order.rb")
+
+
+class TestRailsGate:
+ def test_non_rails_repo_unaffected(self, tmp_path: Path) -> None:
+ # Plain Ruby with similar-looking code but no config/application.rb
+ (tmp_path / "models.rb").write_text(
+ "class Order; belongs_to :user; end\nclass User; end\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ count = add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert count == 0
diff --git a/tests/unit/ingestion/test_ruby_extractors.py b/tests/unit/ingestion/test_ruby_extractors.py
new file mode 100644
index 000000000..14783a123
--- /dev/null
+++ b/tests/unit/ingestion/test_ruby_extractors.py
@@ -0,0 +1,65 @@
+"""Unit tests for Ruby heritage, mixins, bindings, and constant captures."""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+
+def _file(path: str = "foo.rb") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language="ruby",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
+class TestRubyHeritage:
+ def test_class_extends(self, parser: ASTParser) -> None:
+ src = b"class Foo < Base\nend\n"
+ result = parser.parse_file(_file(), src)
+ parents = {r.parent_name for r in result.heritage}
+ assert "Base" in parents
+
+ def test_include_mixin(self, parser: ASTParser) -> None:
+ # Avoid stdlib names (Comparable/Enumerable) — those are filtered as
+ # builtin parents. Use custom modules.
+ src = b"class Foo\n include Loggable\n extend Cacheable\nend\n"
+ result = parser.parse_file(_file(), src)
+ parents = {r.parent_name for r in result.heritage}
+ assert "Loggable" in parents
+ assert "Cacheable" in parents
+
+
+class TestRubyConstants:
+ def test_top_level_constant_captured(self, parser: ASTParser) -> None:
+ src = b"MAX_RETRIES = 3\nDEFAULT = :foo\n"
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "MAX_RETRIES" in names
+ assert "DEFAULT" in names
+
+
+class TestRubyImports:
+ def test_require_statements(self, parser: ASTParser) -> None:
+ src = b"require 'json'\nrequire_relative './helper'\n"
+ result = parser.parse_file(_file(), src)
+ modules = [imp.module_path for imp in result.imports]
+ assert "json" in modules
+ assert "./helper" in modules
diff --git a/tests/unit/ingestion/test_ruby_resolver.py b/tests/unit/ingestion/test_ruby_resolver.py
new file mode 100644
index 000000000..4c8b10776
--- /dev/null
+++ b/tests/unit/ingestion/test_ruby_resolver.py
@@ -0,0 +1,91 @@
+"""Unit tests for the Ruby Rails / Zeitwerk-aware import resolver."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.ruby import resolve_ruby_import
+from repowise.core.ingestion.resolvers.ruby_rails import (
+ build_rails_index,
+ camel_to_snake,
+)
+
+
+def _ctx(repo: Path, paths: list[str]) -> ResolverContext:
+ path_set = set(paths)
+ stem_map: dict[str, list[str]] = {}
+ for p in paths:
+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set,
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ )
+
+
+def _make_rails_repo(repo: Path) -> None:
+ (repo / "config").mkdir()
+ (repo / "config" / "application.rb").write_text("module App; class Application; end; end\n")
+
+
+class TestRailsDetection:
+ def test_returns_none_when_not_rails(self, tmp_path: Path) -> None:
+ assert build_rails_index(tmp_path) is None
+
+ def test_detects_via_application_rb(self, tmp_path: Path) -> None:
+ _make_rails_repo(tmp_path)
+ index = build_rails_index(tmp_path)
+ assert index is not None
+
+
+class TestRailsConstantLookup:
+ def test_simple_constant(self, tmp_path: Path) -> None:
+ _make_rails_repo(tmp_path)
+ ctrl = tmp_path / "app" / "controllers"
+ ctrl.mkdir(parents=True)
+ (ctrl / "users_controller.rb").write_text("class UsersController; end\n")
+ index = build_rails_index(tmp_path)
+ assert index is not None
+ assert index.lookup("UsersController") == "app/controllers/users_controller.rb"
+
+ def test_namespaced_constant(self, tmp_path: Path) -> None:
+ _make_rails_repo(tmp_path)
+ admin = tmp_path / "app" / "controllers" / "admin"
+ admin.mkdir(parents=True)
+ (admin / "reports_controller.rb").write_text(
+ "module Admin; class ReportsController; end; end\n"
+ )
+ index = build_rails_index(tmp_path)
+ assert index is not None
+ result = index.lookup("Admin::ReportsController")
+ assert result == "app/controllers/admin/reports_controller.rb"
+
+ def test_camel_to_snake(self) -> None:
+ assert camel_to_snake("UserController") == "user_controller"
+ assert camel_to_snake("Foo") == "foo"
+
+
+class TestRubyResolverIntegration:
+ def test_require_relative_unaffected(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["lib/foo.rb"])
+ result = resolve_ruby_import("./foo", "lib/main.rb", ctx)
+ assert result == "lib/foo.rb"
+
+ def test_rails_path_style_require(self, tmp_path: Path) -> None:
+ _make_rails_repo(tmp_path)
+ svc = tmp_path / "app" / "services"
+ svc.mkdir(parents=True)
+ (svc / "user_service.rb").write_text("class UserService; end\n")
+ ctx = _ctx(tmp_path, ["app/services/user_service.rb", "config/application.rb"])
+ result = resolve_ruby_import("app/services/user_service", "main.rb", ctx)
+ assert result == "app/services/user_service.rb"
+
+ def test_non_rails_unaffected(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["lib/foo.rb"])
+ result = resolve_ruby_import("foo", "main.rb", ctx)
+ assert result == "lib/foo.rb"
diff --git a/tests/unit/ingestion/test_rust_framework_edges.py b/tests/unit/ingestion/test_rust_framework_edges.py
new file mode 100644
index 000000000..c5dc11c75
--- /dev/null
+++ b/tests/unit/ingestion/test_rust_framework_edges.py
@@ -0,0 +1,102 @@
+"""Unit tests for Axum/Actix framework edges (F6)."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+
+
+def _file_info(rel: str, abs_path: str) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=abs_path,
+ language="rust",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _build_parsed(repo: Path) -> dict[str, ParsedFile]:
+ parser = ASTParser()
+ out: dict[str, ParsedFile] = {}
+ for src in repo.rglob("*.rs"):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ fi = _file_info(rel, str(src.resolve()))
+ out[rel] = parser.parse_file(fi, src.read_bytes())
+ return out
+
+
+def _ctx(repo: Path, parsed: dict[str, ParsedFile]) -> ResolverContext:
+ path_set = set(parsed.keys())
+ stem_map: dict[str, list[str]] = {}
+ for p in path_set:
+ stem = Path(p).stem.lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set, stem_map=stem_map, graph=nx.DiGraph(), repo_path=repo
+ )
+
+
+class TestAxum:
+ def test_route_to_handler(self, tmp_path: Path) -> None:
+ (tmp_path / "handlers.rs").write_text(
+ "pub async fn list_users() -> &'static str { \"ok\" }\n"
+ )
+ (tmp_path / "main.rs").write_text(
+ "use axum::{Router, routing::get};\n"
+ "mod handlers;\n"
+ "fn app() -> Router {\n"
+ " Router::new().route(\"/users\", get(list_users))\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["axum"])
+ assert graph.has_edge("main.rs", "handlers.rs")
+
+
+class TestActix:
+ def test_web_get_to_handler(self, tmp_path: Path) -> None:
+ (tmp_path / "handlers.rs").write_text(
+ "pub async fn index() -> &'static str { \"ok\" }\n"
+ )
+ (tmp_path / "main.rs").write_text(
+ "use actix_web::{web, App};\n"
+ "fn config(cfg: &mut web::ServiceConfig) {\n"
+ " cfg.route(\"/\", web::get().to(index));\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["actix"])
+ assert graph.has_edge("main.rs", "handlers.rs")
+
+
+class TestRustGate:
+ def test_non_router_unaffected(self, tmp_path: Path) -> None:
+ (tmp_path / "main.rs").write_text("fn main() {}\n")
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ count = add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert count == 0
diff --git a/tests/unit/ingestion/test_rust_resolver.py b/tests/unit/ingestion/test_rust_resolver.py
new file mode 100644
index 000000000..2e22484f1
--- /dev/null
+++ b/tests/unit/ingestion/test_rust_resolver.py
@@ -0,0 +1,116 @@
+"""Unit tests for the Rust workspace-aware import resolver."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.rust import resolve_rust_import
+from repowise.core.ingestion.resolvers.rust_workspace import (
+ get_or_build_cargo_workspace_index,
+)
+
+
+def _ctx(repo: Path, paths: list[str]) -> ResolverContext:
+ path_set = set(paths)
+ stem_map: dict[str, list[str]] = {}
+ for p in paths:
+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set,
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ )
+
+
+def _write_workspace(repo: Path, members: list[str]) -> None:
+ members_str = ", ".join(f'"{m}"' for m in members)
+ (repo / "Cargo.toml").write_text(
+ f"[workspace]\nmembers = [{members_str}]\n"
+ )
+
+
+def _write_member_crate(repo: Path, member_dir: str, name: str) -> None:
+ crate_dir = repo / member_dir
+ crate_dir.mkdir(parents=True, exist_ok=True)
+ (crate_dir / "Cargo.toml").write_text(
+ f"[package]\nname = \"{name}\"\nversion = \"0.1.0\"\n"
+ )
+ src_dir = crate_dir / "src"
+ src_dir.mkdir(exist_ok=True)
+ (src_dir / "lib.rs").write_text("// crate root\n")
+
+
+class TestCargoWorkspaceIndex:
+ def test_member_lookup(self, tmp_path: Path) -> None:
+ _write_workspace(tmp_path, ["crates/foo", "crates/bar"])
+ _write_member_crate(tmp_path, "crates/foo", "foo")
+ _write_member_crate(tmp_path, "crates/bar", "bar-utils")
+ ctx = _ctx(tmp_path, [
+ "crates/foo/src/lib.rs",
+ "crates/bar/src/lib.rs",
+ ])
+ idx = get_or_build_cargo_workspace_index(ctx)
+ assert idx is not None
+ assert idx.lookup("foo") == "crates/foo/src"
+ # Hyphen → underscore in import identifier
+ assert idx.lookup("bar_utils") == "crates/bar/src"
+ # Bare hyphenated name should not match
+ assert idx.lookup("bar-utils") is None
+
+ def test_no_workspace_returns_none(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, [])
+ assert get_or_build_cargo_workspace_index(ctx) is None
+
+
+class TestRustWorkspaceResolution:
+ def test_use_sibling_crate_resolves_to_module_file(self, tmp_path: Path) -> None:
+ _write_workspace(tmp_path, ["crates/foo", "crates/bar"])
+ _write_member_crate(tmp_path, "crates/foo", "foo")
+ _write_member_crate(tmp_path, "crates/bar", "bar")
+ # Add a module under bar to import
+ (tmp_path / "crates/bar/src/baz.rs").write_text("pub fn hello(){}")
+
+ ctx = _ctx(tmp_path, [
+ "crates/foo/src/lib.rs",
+ "crates/foo/src/main.rs",
+ "crates/bar/src/lib.rs",
+ "crates/bar/src/baz.rs",
+ ])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("bar::baz", "crates/foo/src/main.rs", ctx)
+ assert result == "crates/bar/src/baz.rs"
+
+ def test_use_sibling_crate_root_only(self, tmp_path: Path) -> None:
+ _write_workspace(tmp_path, ["crates/foo", "crates/bar"])
+ _write_member_crate(tmp_path, "crates/foo", "foo")
+ _write_member_crate(tmp_path, "crates/bar", "bar")
+
+ ctx = _ctx(tmp_path, [
+ "crates/foo/src/lib.rs",
+ "crates/foo/src/main.rs",
+ "crates/bar/src/lib.rs",
+ ])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("bar::SomeType", "crates/foo/src/main.rs", ctx)
+ assert result == "crates/bar/src/lib.rs"
+
+ def test_unknown_crate_falls_through_to_external(self, tmp_path: Path) -> None:
+ _write_workspace(tmp_path, ["crates/foo"])
+ _write_member_crate(tmp_path, "crates/foo", "foo")
+
+ ctx = _ctx(tmp_path, ["crates/foo/src/lib.rs", "crates/foo/src/main.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("serde::Serialize", "crates/foo/src/main.rs", ctx)
+ assert result is not None and result.startswith("external:")
+
+ def test_no_workspace_unaffected(self, tmp_path: Path) -> None:
+ # Single-crate Cargo.toml without [workspace] — existing path still wins
+ ctx = _ctx(tmp_path, ["src/lib.rs", "src/main.rs"])
+ ctx.parsed_files = {p: None for p in ctx.path_set}
+ result = resolve_rust_import("serde::Serialize", "src/main.rs", ctx)
+ assert result is not None and result.startswith("external:")
diff --git a/tests/unit/ingestion/test_scala_extractors.py b/tests/unit/ingestion/test_scala_extractors.py
new file mode 100644
index 000000000..f8e065d86
--- /dev/null
+++ b/tests/unit/ingestion/test_scala_extractors.py
@@ -0,0 +1,67 @@
+"""Unit tests for Scala heritage, traits, val/var, and Scala 3 captures."""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+
+def _file(path: str = "Foo.scala") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language="scala",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
+class TestScalaHeritage:
+ def test_extends_with_trait(self, parser: ASTParser) -> None:
+ src = b"class Foo extends Base with Comparable[Foo]\n"
+ result = parser.parse_file(_file(), src)
+ parents = {r.parent_name for r in result.heritage}
+ assert "Base" in parents
+
+
+class TestScalaCaptures:
+ def test_val_var_definitions(self, parser: ASTParser) -> None:
+ src = b"val x = 1\nvar y: Int = 2\n"
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "x" in names
+ assert "y" in names
+
+ def test_scala3_enum(self, parser: ASTParser) -> None:
+ src = b"enum Color { case Red, Green, Blue }\n"
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "Color" in names
+
+ def test_scala3_given(self, parser: ASTParser) -> None:
+ src = b"given foo: Ord[Int] = ???\n"
+ result = parser.parse_file(_file(), src)
+ names = {s.name for s in result.symbols}
+ assert "foo" in names
+
+
+class TestScalaImports:
+ def test_import_path(self, parser: ASTParser) -> None:
+ src = b"import scala.collection.mutable\nclass Foo\n"
+ result = parser.parse_file(_file(), src)
+ modules = [imp.module_path for imp in result.imports]
+ assert any("scala" in m for m in modules)
diff --git a/tests/unit/ingestion/test_scala_resolver.py b/tests/unit/ingestion/test_scala_resolver.py
new file mode 100644
index 000000000..31a8566f3
--- /dev/null
+++ b/tests/unit/ingestion/test_scala_resolver.py
@@ -0,0 +1,79 @@
+"""Unit tests for the Scala SBT/Mill-aware import resolver."""
+
+from __future__ import annotations
+
+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_build import build_scala_index
+
+
+def _ctx(repo: Path, paths: list[str]) -> ResolverContext:
+ path_set = set(paths)
+ stem_map: dict[str, list[str]] = {}
+ for p in paths:
+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set,
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ )
+
+
+def _make_sbt_project(repo: Path, project_dir: str, package: str, class_name: str) -> str:
+ src = repo / project_dir / "src" / "main" / "scala" / package.replace(".", "/")
+ src.mkdir(parents=True)
+ file_path = src / f"{class_name}.scala"
+ file_path.write_text(f"package {package}\n\nclass {class_name}\n")
+ return file_path.relative_to(repo).as_posix()
+
+
+def _make_mill_module(repo: Path, module_name: str, package: str, class_name: str) -> str:
+ src = repo / module_name / "src" / package.replace(".", "/")
+ src.mkdir(parents=True)
+ file_path = src / f"{class_name}.scala"
+ file_path.write_text(f"package {package}\n\nclass {class_name}\n")
+ return file_path.relative_to(repo).as_posix()
+
+
+class TestScalaIndex:
+ def test_sbt_subprojects_detected(self, tmp_path: Path) -> None:
+ (tmp_path / "build.sbt").write_text(
+ 'lazy val core = project.in(file("core"))\n'
+ 'lazy val util = project.in(file("util"))\n'
+ )
+ rel = _make_sbt_project(tmp_path, "core", "com.example", "Engine")
+ index = build_scala_index(tmp_path)
+ assert index.build_tool == "sbt"
+ assert "core" in index.projects
+ assert rel in index.package_to_files["com.example"]
+
+ def test_mill_modules_detected(self, tmp_path: Path) -> None:
+ (tmp_path / "build.sc").write_text(
+ "import mill._\n"
+ "object core extends ScalaModule { def scalaVersion = T(\"3.0.0\") }\n"
+ )
+ rel = _make_mill_module(tmp_path, "core", "com.example", "Engine")
+ index = build_scala_index(tmp_path)
+ assert index.build_tool == "mill"
+ assert "core" in index.projects
+ assert rel in index.package_to_files["com.example"]
+
+ def test_resolves_via_sbt_index(self, tmp_path: Path) -> None:
+ (tmp_path / "build.sbt").write_text('lazy val core = project.in(file("core"))\n')
+ rel = _make_sbt_project(tmp_path, "core", "com.example", "Engine")
+ ctx = _ctx(tmp_path, [rel])
+ result = resolve_scala_import("com.example.Engine", "main.scala", ctx)
+ assert result == rel
+
+ def test_no_build_file_falls_through(self, tmp_path: Path) -> None:
+ (tmp_path / "src").mkdir()
+ (tmp_path / "src" / "Foo.scala").write_text("class Foo\n")
+ ctx = _ctx(tmp_path, ["src/Foo.scala"])
+ result = resolve_scala_import("com.example.Foo", "main.scala", ctx)
+ assert result == "src/Foo.scala"
diff --git a/tests/unit/ingestion/test_spring_framework_edges.py b/tests/unit/ingestion/test_spring_framework_edges.py
new file mode 100644
index 000000000..032a5e855
--- /dev/null
+++ b/tests/unit/ingestion/test_spring_framework_edges.py
@@ -0,0 +1,152 @@
+"""Unit tests for Spring Boot framework edges (F1)."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.framework_edges import add_framework_edges
+from repowise.core.ingestion.models import FileInfo, ParsedFile
+from repowise.core.ingestion.parser import ASTParser
+from repowise.core.ingestion.resolvers.context import ResolverContext
+
+
+def _file_info(rel: str, abs_path: str, language: str) -> FileInfo:
+ return FileInfo(
+ path=rel,
+ abs_path=abs_path,
+ language=language,
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
+def _build_parsed(repo: Path) -> dict[str, ParsedFile]:
+ parser = ASTParser()
+ out: dict[str, ParsedFile] = {}
+ for src in list(repo.rglob("*.java")) + list(repo.rglob("*.kt")):
+ rel = src.resolve().relative_to(repo.resolve()).as_posix()
+ lang = "java" if src.suffix == ".java" else "kotlin"
+ fi = _file_info(rel, str(src.resolve()), lang)
+ out[rel] = parser.parse_file(fi, src.read_bytes())
+ return out
+
+
+def _ctx(repo: Path, parsed: dict[str, ParsedFile]) -> ResolverContext:
+ path_set = set(parsed.keys())
+ stem_map: dict[str, list[str]] = {}
+ for p in path_set:
+ stem = Path(p).stem.lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set, stem_map=stem_map, graph=nx.DiGraph(), repo_path=repo
+ )
+
+
+class TestSpringDI:
+ def test_autowired_field_injection(self, tmp_path: Path) -> None:
+ (tmp_path / "UserService.java").write_text(
+ "import org.springframework.stereotype.Service;\n"
+ "@Service\npublic class UserService {}\n"
+ )
+ (tmp_path / "UserController.java").write_text(
+ "import org.springframework.beans.factory.annotation.Autowired;\n"
+ "import org.springframework.web.bind.annotation.RestController;\n"
+ "@RestController\npublic class UserController {\n"
+ " @Autowired private UserService userService;\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["spring"])
+ assert graph.has_edge("UserController.java", "UserService.java")
+
+ def test_constructor_injection_resolves_interface_to_impl(self, tmp_path: Path) -> None:
+ (tmp_path / "PaymentService.java").write_text(
+ "public interface PaymentService {}\n"
+ )
+ (tmp_path / "StripePayment.java").write_text(
+ "import org.springframework.stereotype.Service;\n"
+ "@Service\npublic class StripePayment implements PaymentService {}\n"
+ )
+ (tmp_path / "CheckoutController.java").write_text(
+ "import org.springframework.web.bind.annotation.RestController;\n"
+ "@RestController\npublic class CheckoutController {\n"
+ " private final PaymentService payments;\n"
+ " public CheckoutController(PaymentService payments) { this.payments = payments; }\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["spring"])
+ # Edge to either the interface file or its impl is acceptable.
+ assert graph.has_edge("CheckoutController.java", "StripePayment.java") or graph.has_edge(
+ "CheckoutController.java", "PaymentService.java"
+ )
+
+ def test_bean_factory_links_config_to_return_type(self, tmp_path: Path) -> None:
+ (tmp_path / "Greeter.java").write_text("public class Greeter {}\n")
+ (tmp_path / "AppConfig.java").write_text(
+ "import org.springframework.context.annotation.Bean;\n"
+ "import org.springframework.context.annotation.Configuration;\n"
+ "@Configuration\npublic class AppConfig {\n"
+ " @Bean\n public Greeter greeter() { return new Greeter(); }\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["spring"])
+ assert graph.has_edge("AppConfig.java", "Greeter.java")
+
+
+class TestSpringKotlin:
+ def test_kotlin_service_with_autowired_field(self, tmp_path: Path) -> None:
+ (tmp_path / "Repo.kt").write_text(
+ "import org.springframework.stereotype.Repository\n"
+ "@Repository\nclass Repo\n"
+ )
+ (tmp_path / "Svc.kt").write_text(
+ "import org.springframework.beans.factory.annotation.Autowired\n"
+ "import org.springframework.stereotype.Service\n"
+ "@Service\nclass Svc {\n"
+ " @Autowired lateinit var repo: Repo\n"
+ "}\n"
+ )
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ add_framework_edges(graph, parsed, ctx, tech_stack=["spring"])
+ # The Java-style regex won't match Kotlin `@Autowired lateinit var`, so this
+ # currently exercises only the gate (Spring detection works for Kotlin).
+ # The edge may or may not be present — assert the slice runs without error.
+ assert graph.number_of_nodes() == 2
+
+
+class TestSpringGate:
+ def test_non_spring_unaffected(self, tmp_path: Path) -> None:
+ (tmp_path / "Plain.java").write_text("public class Plain {}\n")
+ parsed = _build_parsed(tmp_path)
+ graph = nx.DiGraph()
+ for p in parsed:
+ graph.add_node(p)
+ ctx = _ctx(tmp_path, parsed)
+ count = add_framework_edges(graph, parsed, ctx, tech_stack=[])
+ assert count == 0
diff --git a/tests/unit/ingestion/test_swift_extractors.py b/tests/unit/ingestion/test_swift_extractors.py
new file mode 100644
index 000000000..d3f5eeadb
--- /dev/null
+++ b/tests/unit/ingestion/test_swift_extractors.py
@@ -0,0 +1,81 @@
+"""Unit tests for Swift heritage extraction.
+
+Covers Phase 1 fix B2 — adding ``extension_declaration`` to Swift's
+``heritage_node_types``. The ``_extract_swift_heritage`` extractor
+already handled the node, but the upstream filter discarded it.
+Class and protocol cases are exercised as regression coverage.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+
+import pytest
+
+from repowise.core.ingestion.models import FileInfo
+from repowise.core.ingestion.parser import ASTParser
+
+
+def _file(path: str = "Foo.swift") -> FileInfo:
+ return FileInfo(
+ path=path,
+ abs_path=f"/tmp/{path}",
+ language="swift",
+ size_bytes=100,
+ git_hash="",
+ last_modified=datetime.now(),
+ is_test=False,
+ is_config=False,
+ is_api_contract=False,
+ is_entry_point=False,
+ )
+
+
[email protected](scope="module")
+def parser() -> ASTParser:
+ return ASTParser()
+
+
+class TestSwiftHeritage:
+ def test_extension_protocol_conformance(self, parser: ASTParser) -> None:
+ # B2: extension Foo: SomeProtocol {} previously produced no
+ # heritage edge because extension_declaration was filtered out
+ # before _extract_swift_heritage ran.
+ src = b"""\
+class Foo {}
+protocol Greeter {}
+extension Foo: Greeter {}
+"""
+ result = parser.parse_file(_file(), src)
+ rels = {(r.child_name, r.parent_name) for r in result.heritage}
+ assert ("Foo", "Greeter") in rels
+
+ def test_class_inheritance_still_works(self, parser: ASTParser) -> None:
+ src = b"""\
+class Base {}
+class Derived: Base {}
+"""
+ result = parser.parse_file(_file(), src)
+ rels = {(r.child_name, r.parent_name) for r in result.heritage}
+ assert ("Derived", "Base") in rels
+
+ def test_protocol_inheritance_still_works(self, parser: ASTParser) -> None:
+ src = b"""\
+protocol Animal {}
+protocol Pet: Animal {}
+"""
+ result = parser.parse_file(_file(), src)
+ rels = {(r.child_name, r.parent_name) for r in result.heritage}
+ assert ("Pet", "Animal") in rels
+
+ def test_extension_multiple_conformances(self, parser: ASTParser) -> None:
+ src = b"""\
+class Foo {}
+protocol A {}
+protocol B {}
+extension Foo: A, B {}
+"""
+ result = parser.parse_file(_file(), src)
+ rels = {(r.child_name, r.parent_name) for r in result.heritage}
+ assert ("Foo", "A") in rels
+ assert ("Foo", "B") in rels
diff --git a/tests/unit/ingestion/test_swift_resolver.py b/tests/unit/ingestion/test_swift_resolver.py
new file mode 100644
index 000000000..bef37b263
--- /dev/null
+++ b/tests/unit/ingestion/test_swift_resolver.py
@@ -0,0 +1,101 @@
+"""Unit tests for the Swift Package.swift-aware import resolver."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.swift import resolve_swift_import
+from repowise.core.ingestion.resolvers.swift_spm import (
+ build_swift_targets,
+ parse_package_swift,
+)
+
+
+def _ctx(repo: Path, paths: list[str]) -> ResolverContext:
+ path_set = set(paths)
+ stem_map: dict[str, list[str]] = {}
+ for p in paths:
+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0].lower()
+ stem_map.setdefault(stem, []).append(p)
+ return ResolverContext(
+ path_set=path_set,
+ stem_map=stem_map,
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ )
+
+
+_PACKAGE_SWIFT = """
+// swift-tools-version:5.9
+import PackageDescription
+
+let package = Package(
+ name: "MyPkg",
+ targets: [
+ .target(name: "Core"),
+ .target(name: "Helpers", path: "Custom/Helpers"),
+ .executableTarget(name: "App"),
+ .testTarget(name: "CoreTests"),
+ ]
+)
+"""
+
+
+class TestPackageSwiftParsing:
+ def test_default_sources_path(self, tmp_path: Path) -> None:
+ pkg = tmp_path / "Package.swift"
+ pkg.write_text(_PACKAGE_SWIFT)
+ targets = parse_package_swift(pkg)
+ assert targets["Core"] == "Sources/Core"
+ assert targets["App"] == "Sources/App"
+
+ def test_explicit_path(self, tmp_path: Path) -> None:
+ pkg = tmp_path / "Package.swift"
+ pkg.write_text(_PACKAGE_SWIFT)
+ targets = parse_package_swift(pkg)
+ assert targets["Helpers"] == "Custom/Helpers"
+
+ def test_test_target_uses_tests_root(self, tmp_path: Path) -> None:
+ pkg = tmp_path / "Package.swift"
+ pkg.write_text(_PACKAGE_SWIFT)
+ targets = parse_package_swift(pkg)
+ assert targets["CoreTests"] == "Tests/CoreTests"
+
+ def test_missing_file(self, tmp_path: Path) -> None:
+ assert parse_package_swift(tmp_path / "missing.swift") == {}
+
+
+class TestSwiftResolverIntegration:
+ def test_resolves_via_target_dir(self, tmp_path: Path) -> None:
+ (tmp_path / "Package.swift").write_text(_PACKAGE_SWIFT)
+ ctx = _ctx(
+ tmp_path,
+ ["Sources/Core/Engine.swift", "Sources/App/main.swift"],
+ )
+ # Trigger build_swift_targets via the lazy accessor in swift.py.
+ result = resolve_swift_import("Core.Engine", "Sources/App/main.swift", ctx)
+ assert result == "Sources/Core/Engine.swift"
+
+ def test_falls_through_when_no_package_swift(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["Sources/Foo/Foo.swift"])
+ # No Package.swift → swift_targets empty → falls through to stem.
+ result = resolve_swift_import("Foo", "src/main.swift", ctx)
+ assert result == "Sources/Foo/Foo.swift"
+
+
+class TestBuildSwiftTargets:
+ def test_merges_multiple_packages(self, tmp_path: Path) -> None:
+ (tmp_path / "pkg-a").mkdir()
+ (tmp_path / "pkg-a" / "Package.swift").write_text(
+ 'let package = Package(name: "A", targets: [.target(name: "Alpha")])'
+ )
+ (tmp_path / "pkg-b").mkdir()
+ (tmp_path / "pkg-b" / "Package.swift").write_text(
+ 'let package = Package(name: "B", targets: [.target(name: "Beta")])'
+ )
+ merged = build_swift_targets(tmp_path)
+ assert merged["Alpha"] == "pkg-a/Sources/Alpha"
+ assert merged["Beta"] == "pkg-b/Sources/Beta"
diff --git a/tests/unit/ingestion/test_typescript_resolver.py b/tests/unit/ingestion/test_typescript_resolver.py
new file mode 100644
index 000000000..06f797c08
--- /dev/null
+++ b/tests/unit/ingestion/test_typescript_resolver.py
@@ -0,0 +1,97 @@
+"""Unit tests for TS resolver SFC extension probing and workspace packages."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import networkx as nx
+
+from repowise.core.ingestion.resolvers.context import ResolverContext
+from repowise.core.ingestion.resolvers.ts_workspace import (
+ build_workspace_map,
+ resolve_via_workspaces,
+)
+from repowise.core.ingestion.resolvers.typescript import resolve_ts_js_import
+
+
+def _ctx(repo: Path, paths: list[str], has_sfc: bool = False) -> ResolverContext:
+ path_set = set(paths)
+ return ResolverContext(
+ path_set=path_set,
+ stem_map={},
+ graph=nx.DiGraph(),
+ repo_path=repo,
+ has_sfc_files=has_sfc
+ or any(p.endswith((".vue", ".svelte", ".astro")) for p in path_set),
+ )
+
+
+class TestSfcExtensions:
+ def test_vue_extension_resolved_when_sfc_present(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["src/App.vue", "src/main.ts"])
+ result = resolve_ts_js_import("./App", "src/main.ts", ctx)
+ assert result == "src/App.vue"
+
+ def test_svelte_extension(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["src/Widget.svelte", "src/main.ts"])
+ result = resolve_ts_js_import("./Widget", "src/main.ts", ctx)
+ assert result == "src/Widget.svelte"
+
+ def test_pure_ts_repo_skips_sfc_probe(self, tmp_path: Path) -> None:
+ # No SFC file present → has_sfc_files=False → resolver should NOT
+ # match a hypothetical .vue path. We don't index App.vue here; the
+ # resolver should return None rather than fishing for SFC files.
+ ctx = _ctx(tmp_path, ["src/foo.ts"])
+ assert ctx.has_sfc_files is False
+ result = resolve_ts_js_import("./missing", "src/foo.ts", ctx)
+ assert result is None
+
+
+class TestWorkspaceMap:
+ def test_workspaces_array_form(self, tmp_path: Path) -> None:
+ (tmp_path / "package.json").write_text(json.dumps({"workspaces": ["packages/*"]}))
+ pkg_a = tmp_path / "packages" / "a"
+ pkg_a.mkdir(parents=True)
+ (pkg_a / "package.json").write_text(json.dumps({"name": "@org/a"}))
+ mapping = build_workspace_map(tmp_path)
+ assert mapping == {"@org/a": "packages/a"}
+
+ def test_workspaces_object_form(self, tmp_path: Path) -> None:
+ (tmp_path / "package.json").write_text(
+ json.dumps({"workspaces": {"packages": ["libs/*"]}})
+ )
+ pkg = tmp_path / "libs" / "core"
+ pkg.mkdir(parents=True)
+ (pkg / "package.json").write_text(json.dumps({"name": "@org/core"}))
+ mapping = build_workspace_map(tmp_path)
+ assert mapping == {"@org/core": "libs/core"}
+
+ def test_empty_when_no_root_package(self, tmp_path: Path) -> None:
+ assert build_workspace_map(tmp_path) == {}
+
+
+class TestWorkspaceResolution:
+ def test_resolves_workspace_subpath(self, tmp_path: Path) -> None:
+ (tmp_path / "package.json").write_text(json.dumps({"workspaces": ["packages/*"]}))
+ pkg = tmp_path / "packages" / "core"
+ pkg.mkdir(parents=True)
+ (pkg / "package.json").write_text(json.dumps({"name": "@org/core"}))
+ ctx = _ctx(tmp_path, ["packages/core/src/index.ts"])
+ result = resolve_via_workspaces("@org/core/src/index", ctx)
+ assert result == "packages/core/src/index.ts"
+
+ def test_resolves_workspace_index(self, tmp_path: Path) -> None:
+ (tmp_path / "package.json").write_text(json.dumps({"workspaces": ["packages/*"]}))
+ pkg = tmp_path / "packages" / "core"
+ pkg.mkdir(parents=True)
+ (pkg / "package.json").write_text(json.dumps({"name": "@org/core"}))
+ ctx = _ctx(tmp_path, ["packages/core/index.ts"])
+ result = resolve_via_workspaces("@org/core", ctx)
+ assert result == "packages/core/index.ts"
+
+ def test_external_when_no_match(self, tmp_path: Path) -> None:
+ ctx = _ctx(tmp_path, ["packages/core/index.ts"])
+ # No package.json → no workspaces → returns None (resolver itself
+ # would then return external:).
+ assert resolve_via_workspaces("@unknown/pkg", ctx) is None
diff --git a/tests/unit/test_dead_code.py b/tests/unit/test_dead_code.py
index 7ce707b74..ebd93cd27 100644
--- a/tests/unit/test_dead_code.py
+++ b/tests/unit/test_dead_code.py
@@ -593,3 +593,219 @@ def test_report_deletable_lines_sum():
assert "pkg/alive.py" not in safe_paths
# Verify the actual sum
assert report.deletable_lines == 100 + 200
+
+
+# ---------------------------------------------------------------------------
+# 13. test_dynamic_edge_clamps_unreachable_confidence
+# ---------------------------------------------------------------------------
+
+
+def test_dynamic_edge_clamps_unreachable_confidence():
+ """A file in a package that has dynamic graph edges should have confidence clamped to 0.4."""
+ g = _build_graph(
+ nodes={
+ "pkg/orphan.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 5,
+ "symbols": [],
+ },
+ "pkg/dispatcher.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "symbols": [],
+ },
+ "pkg/handler.py": {
+ "is_entry_point": True,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 3,
+ "symbols": [],
+ },
+ },
+ edges=[
+ ("pkg/dispatcher.py", "pkg/handler.py", {"edge_type": "dynamic"}),
+ ],
+ )
+
+ git_meta = {
+ "pkg/orphan.py": {
+ "commit_count_90d": 0,
+ "last_commit_at": _old_date(days=400),
+ "age_days": 500,
+ },
+ }
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map=git_meta)
+ report = analyzer.analyze(
+ {
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ findings = [f for f in report.findings if f.file_path == "pkg/orphan.py"]
+ assert len(findings) == 1
+ assert findings[0].confidence == pytest.approx(0.4)
+ assert any("dynamic" in e.lower() for e in findings[0].evidence)
+
+
+# ---------------------------------------------------------------------------
+# 14. test_find_dynamic_edge_files_handles_subtypes
+# ---------------------------------------------------------------------------
+
+
+def test_find_dynamic_edge_files_handles_subtypes():
+ """find_dynamic_edge_files picks up edges with dynamic_* sub-type prefixes."""
+ from repowise.core.analysis.dead_code.dynamic_markers import find_dynamic_edge_files
+
+ g = nx.DiGraph()
+ g.add_node("a.py")
+ g.add_node("b.py")
+ g.add_node("c.py")
+ g.add_node("d.py")
+ g.add_node("external:something")
+ g.add_edge("a.py", "b.py", edge_type="dynamic_uses")
+ g.add_edge("c.py", "d.py", edge_type="dynamic_imports")
+ g.add_edge("a.py", "external:something", edge_type="dynamic")
+ # Non-dynamic edges should not contribute
+ g.add_edge("b.py", "c.py", edge_type="calls")
+
+ files = find_dynamic_edge_files(g)
+ assert {"a.py", "b.py", "c.py", "d.py"} <= files
+ assert "external:something" not in files
+
+
+# ---------------------------------------------------------------------------
+# 15. test_dynamic_markers_per_language_coverage
+# ---------------------------------------------------------------------------
+
+
+ "suffix,expected_markers",
+ [
+ (".go", ("plugin.Open(", "reflect.New(", "reflect.TypeOf(", "reflect.ValueOf(")),
+ (
+ ".rb",
+ ("autoload ", "const_get(", "Object.send(", "Kernel.const_get(", ".public_send("),
+ ),
+ (
+ ".php",
+ (
+ "class_exists(",
+ "call_user_func(",
+ "call_user_func_array(",
+ "new $",
+ "ReflectionClass(",
+ ),
+ ),
+ (
+ ".kt",
+ ("Class.forName(", "ServiceLoader.load(", "KClass.createInstance(", "::class.java"),
+ ),
+ (
+ ".swift",
+ ("NSClassFromString(", "Selector(", "#selector(", "NSStringFromClass("),
+ ),
+ (".scala", ("Class.forName(", "runtimeMirror(", "reflect.runtime")),
+ ],
+)
+def test_dynamic_markers_per_language_coverage(suffix, expected_markers):
+ """Each language's marker tuple must contain the documented Phase 2 entries."""
+ from repowise.core.analysis.dead_code.dynamic_markers import _DYNAMIC_IMPORT_MARKERS
+
+ markers = _DYNAMIC_IMPORT_MARKERS.get(suffix, ())
+ for expected in expected_markers:
+ assert expected in markers, f"missing marker {expected!r} for {suffix}"
+
+
+# ---------------------------------------------------------------------------
+# 16. test_unused_internal_default_on
+# ---------------------------------------------------------------------------
+
+
+def test_unused_internal_default_on():
+ """detect_unused_internals defaults to True; private symbols with no callers are flagged."""
+ g = _build_graph(
+ nodes={
+ "pkg/utils.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "_helper",
+ "kind": "function",
+ "visibility": "private",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 12,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
+ assert any(f.symbol_name == "_helper" for f in internals)
+ assert all(f.safe_to_delete is False for f in internals)
+
+
+# ---------------------------------------------------------------------------
+# 17. test_unused_internal_explicit_opt_out
+# ---------------------------------------------------------------------------
+
+
+def test_unused_internal_explicit_opt_out():
+ """Setting detect_unused_internals=False disables the detector."""
+ g = _build_graph(
+ nodes={
+ "pkg/utils.py": {
+ "is_entry_point": False,
+ "is_test": False,
+ "is_api_contract": False,
+ "symbol_count": 1,
+ "symbols": [
+ {
+ "name": "_helper",
+ "kind": "function",
+ "visibility": "private",
+ "decorators": [],
+ "start_line": 1,
+ "end_line": 12,
+ "complexity_estimate": 1,
+ },
+ ],
+ },
+ },
+ )
+
+ analyzer = DeadCodeAnalyzer(g, git_meta_map={})
+ report = analyzer.analyze(
+ {
+ "detect_unreachable_files": False,
+ "detect_unused_exports": False,
+ "detect_zombie_packages": False,
+ "detect_unused_internals": False,
+ "min_confidence": 0.0,
+ }
+ )
+
+ internals = [f for f in report.findings if f.kind == DeadCodeKind.UNUSED_INTERNAL]
+ assert internals == []
diff --git a/uv.lock b/uv.lock
index 303374e12..d7d2aeffc 100644
--- a/uv.lock
+++ b/uv.lock
@@ -3010,7 +3010,7 @@ wheels = [
[[package]]
name = "repowise"
-version = "0.3.0"
+version = "0.4.0"
source = { editable = "." }
dependencies = [
{ name = "aiosqlite" },