Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat: 14-language AST support with heritage, call resolution, and dead code improvements (#78)
Raghav Chamadiyacb27a7e78d54
diff --git a/README.md b/README.mdindex f339af4ab..fa334ea5e 100644--- a/README.md+++ b/README.md@@ -65,7 +65,7 @@ There's a small genre of "token efficiency" benchmarks going around. It would berepowise runs once, builds everything, then keeps it in sync on every commit.### ◈ Graph Intelligence-tree-sitter parses every file into symbols. NetworkX builds a two-tier dependency graph — file nodes for module-level relationships and symbol nodes (functions, classes, methods) for fine-grained call resolution. A 3-tier resolver links call sites to their targets with confidence scoring. Import aliases, barrel re-exports, and namespace imports all resolve correctly. Inheritance hierarchies are extracted across 11 languages (extends, implements, trait impls, mixins) and resolved to concrete symbol edges. Leiden community detection identifies logical modules at both file and symbol level — with cohesion scoring and heuristic labeling — even when your directory structure doesn't reflect them. Execution flow tracing discovers call paths from entry points through your codebase, classifying them as intra- or cross-community. PageRank, betweenness centrality, and SCC analysis identify your most central and most coupled code.+tree-sitter parses every file across 14 languages into a two-tier dependency graph — file nodes and symbol nodes (functions, classes, methods). A 3-tier call resolver with confidence scoring handles import aliases, barrel re-exports, and namespace imports. Heritage extraction covers extends, implements, trait impls, derive macros, mixins, and extension conformance. Leiden community detection finds logical modules even when your directory structure doesn't reflect them. PageRank, betweenness centrality, SCC analysis, and execution flow tracing from entry points identify your most central, most coupled, and most traversed code.### ◈ Git Intelligence500 commits of history turned into signals: hotspot files (high churn × high complexity), ownership percentages per engineer, co-change pairs (files that change together without an import link — hidden coupling), and significant commit messages that explain *why* code evolved.@@ -543,14 +543,11 @@ repowise reindex # rebuild vector store (no LLM calls)| Tier | Languages | What works ||------|-----------|------------|-| **Full** | Python · TypeScript · JavaScript · Java · Go · Rust | AST parsing, import resolution, named bindings, dependency graph edges, call resolution, heritage extraction |-| **Partial** | C++ | AST parsing, symbol extraction, heritage extraction, `compile_commands.json` import resolution |-| **Partial** | C | AST parsing (structs, functions, macros), `#include` resolution with `compile_commands.json` |-| **Scaffolded** | Kotlin · Ruby | Tree-sitter queries and heritage extractors exist but grammars not yet wired — install `tree-sitter-kotlin` / `tree-sitter-ruby` separately |-| **Traversal** | C# · Swift · Scala · PHP | Files indexed and searchable, but no AST symbol extraction yet |+| **Full** | Python · TypeScript · JavaScript · Java · Go · Rust · C++ | AST parsing, import resolution, named bindings, call resolution, heritage extraction, docstrings |+| **Good** | C · Kotlin · Ruby · C# · Swift · Scala · PHP | AST parsing, import resolution, named bindings, call resolution, heritage (mixins, derive, extensions, traits), docstrings, dedicated resolvers || **Config / data** | OpenAPI · Protobuf · GraphQL · Dockerfile · Makefile · YAML · JSON · TOML · SQL · Terraform | Included in the file tree; special handlers extract endpoints/targets where applicable |-Kotlin, Ruby, C#, Swift, Scala, PHP, Dart, and Elixir are on the [language support roadmap](docs/LANGUAGE_SUPPORT_PLAN.md). Adding a new language requires one `.scm` tree-sitter query file and one config entry. No changes to the parser core. PRs welcome. See [Adding a new language](docs/CONTRIBUTING.md#adding-a-new-language).+14 languages with full AST support. 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/LANGUAGE_SUPPORT.md b/docs/LANGUAGE_SUPPORT.mdnew file mode 100644index 000000000..a3a9ebb68--- /dev/null+++ b/docs/LANGUAGE_SUPPORT.md@@ -0,0 +1,311 @@+# Language Support++repowise analyses codebases written in many languages. Each language goes+through a multi-stage pipeline: file traversal, AST parsing, import+resolution, call graph construction, and heritage (inheritance) extraction.+Not every language has reached full coverage yet --- this page documents+exactly what works today, what is coming next, and how to add a new language.++---++## Support Tiers++Every language falls into one of five tiers. The tier determines which+pipeline stages produce meaningful output.++| Stage | Full | Partial | Scaffolded | Traversal | Config / Data |+|-------|:----:|:-------:|:----------:|:---------:|:-------------:|+| File discovery & git history | Y | Y | Y | Y | Y |+| AST symbol extraction | Y | Y | -- | -- | -- |+| Import resolution | Y | Y | -- | -- | -- |+| Call graph edges | Y | partial | -- | -- | -- |+| Heritage (extends/implements) | Y | partial | -- | -- | -- |+| Named bindings | Y | -- | -- | -- | -- |+| Dead code detection | Y | Y | Y | Y | -- |+| Semantic search & wiki pages | Y | Y | Y | Y | Y |++---++## Language Reference++### Full++Languages with complete pipeline coverage: AST parsing, import resolution,+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()` |+| **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 |+| **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 |++All seven languages support:+- Tree-sitter AST parsing with dedicated `.scm` query files+- Three-tier call resolution (same-file, cross-file, global stem match)+- Named binding extraction (mapping imported names to source symbols)+- Heritage extraction (class/interface/trait inheritance chains)+- Docstring extraction (Python, JSDoc, GoDoc, Rustdoc, Javadoc, Doxygen)+- Framework-aware edges (Django, FastAPI, Flask for Python; tsconfig path aliases for TS/JS; pytest fixture detection)++### Good++AST parsing, symbol extraction, import resolution, call resolution, named+bindings, heritage extraction (including Ruby mixins, Rust derive, Swift+extension conformance, PHP trait use), and docstrings. Dedicated import+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'` |+| **C#** | `.cs` | `Program.cs` `Startup.cs` | `using System.Collections.Generic` |+| **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` |++### Config / Data++Non-code files included in the file tree and wiki. Special handlers extract+endpoints or targets where applicable.++| Language | Extensions / Filenames | Special Handler |+|----------|----------------------|----------------|+| **OpenAPI** | YAML/JSON with `openapi` or `swagger` key | Extracts API paths and schemas |+| **Dockerfile** | `Dockerfile` | Extracts stages and exposed ports |+| **Makefile** | `Makefile` `GNUmakefile` | Extracts targets |+| **Protobuf** | `.proto` | -- |+| **GraphQL** | `.graphql` `.gql` | -- |+| **Terraform** | `.tf` `.hcl` | -- |+| **YAML** | `.yaml` `.yml` | -- |+| **JSON** | `.json` | -- |+| **TOML** | `.toml` | -- |+| **Markdown** | `.md` `.mdx` | -- |+| **SQL** | `.sql` | -- |+| **Shell** | `.sh` `.bash` `.zsh` | -- |++### Git-Blame-Only++These languages are tracked in git history (blame, hotspot analysis,+co-change detection) but have no AST parsing or dedicated support. Files+appear in the wiki as traversal-level entries.++Objective-C, Elixir, Erlang, Lua, R, Dart, Zig, Julia, Clojure, Elm,+Haskell, OCaml, F#, Crystal, Nim, D++---++## How the Pipeline Processes a File++```+File discovered by FileTraverser+ |+ v+Extension/filename -> LanguageTag (via LanguageRegistry)+ |+ +-- Config/data language? -> empty ParsedFile (passthrough)+ +-- Special format? -> special_handlers.py (OpenAPI/Dockerfile/Makefile)+ +-- Has grammar? -> tree-sitter AST parsing+ |+ v+ .scm query extracts:+ @symbol.def / @symbol.name -> Symbol nodes+ @import.statement / @import.module -> Import edges+ @call.target / @call.receiver -> Call edges+ |+ v+ Per-language extractors:+ - Named bindings (import name -> source symbol)+ - Heritage (extends/implements/traits)+ - Docstrings (Python, JSDoc, GoDoc, Rustdoc, Javadoc)+ - Visibility (public/private/protected)+ |+ v+ GraphBuilder resolves imports:+ Python: dotted module paths, __init__.py, src/ layout+ TS/JS: relative paths, tsconfig aliases, node_modules+ Go: go.mod module path stripping+ Rust: crate::/self::/super::, mod.rs probing+ C/C++: compile_commands.json include directories+ Other: stem-map fallback (filename matching)+ |+ v+ Graph analysis:+ PageRank, community detection, dead code, execution flows+```++---++## Adding a New Language++The pipeline is fully modular. Language identity data lives in the+centralised `LanguageRegistry`, per-language extraction logic lives in+`extractors/`, and per-language import resolution lives in `resolvers/`.+Adding a new language touches these places:++### Step 1: Add a `LanguageSpec` to the registry++Edit `packages/core/src/repowise/core/ingestion/languages/registry.py` and+add a new `LanguageSpec(...)` entry to the `_SPECS` tuple:++```python+LanguageSpec(+ tag="mylang",+ display_name="MyLang",+ extensions=frozenset({".ml"}),+ grammar_package="tree_sitter_mylang", # PyPI package name+ scm_file="mylang.scm", # query file name+ heritage_node_types=frozenset({"class_declaration"}),+ entry_point_patterns=("main.ml",),+ manifest_files=("mylang.toml",),+ shebang_tokens=("mylang",),+ builtin_calls=frozenset({"print", "len"}), # filter from call graph+ builtin_parents=frozenset({"Object"}), # filter from heritage+ color_hex="#AB47BC",+)+```++### Step 2: Add the `LanguageTag`++Add `"mylang"` to the `LanguageTag` Literal type in+`packages/core/src/repowise/core/ingestion/models.py`.++### Step 3: Write a tree-sitter query file++Create `packages/core/src/repowise/core/ingestion/queries/mylang.scm` using+tree-sitter S-expression syntax. Follow the capture-name conventions:++| Capture | Purpose | Required? |+|---------|---------|-----------|+| `@symbol.def` | Full definition node (line numbers, kind lookup) | Yes |+| `@symbol.name` | Name identifier | Yes |+| `@symbol.params` | Parameter list | No |+| `@symbol.modifiers` | Decorators / visibility modifiers | No |+| `@symbol.receiver` | Go-style method receiver | No |+| `@import.statement` | Full import node | Yes |+| `@import.module` | Module path being imported | Yes |+| `@call.target` | Function/method being called | No (enables call graph) |+| `@call.receiver` | Object the call is made on | No |+| `@call.arguments` | Call arguments | No |++Look at existing `.scm` files for examples --- `python.scm` and+`typescript.scm` are good starting points.++### Step 4: Add a `LanguageConfig` entry++Add a parser configuration to `LANGUAGE_CONFIGS` in+`packages/core/src/repowise/core/ingestion/parser.py`:++```python+"mylang": LanguageConfig(+ symbol_node_types={+ "function_definition": "function",+ "class_definition": "class",+ },+ import_node_types=["import_statement"],+ export_node_types=[],+ visibility_fn=public_by_default, # from extractors.visibility+ parent_extraction="nesting",+ parent_class_types=frozenset({"class_definition"}),+ entry_point_patterns=["main.ml"],+),+```++### Step 5: Add the tree-sitter grammar dependency++Add the grammar package to `pyproject.toml`:++```toml+[project]+dependencies = [+ # ...+ "tree-sitter-mylang>=0.23,<1",+]+```++### Step 6 (optional): Binding extractor++For full-tier support, add a `extract_mylang_bindings()` function in+`packages/core/src/repowise/core/ingestion/extractors/bindings.py` and+register it in the `extract_import_bindings()` dispatcher. Without this,+imports are still resolved but named-binding-level call resolution won't+work.++### Step 7 (optional): Heritage extractor++Add a `_extract_mylang_heritage()` function in+`packages/core/src/repowise/core/ingestion/extractors/heritage.py` and+register it in the `HERITAGE_EXTRACTORS` dict. Without this, inheritance+chains won't appear in the graph.++### Step 8 (optional): Import resolver++If the language has a non-trivial import system, create a resolver in+`packages/core/src/repowise/core/ingestion/resolvers/mylang.py` and+register it in the `_RESOLVERS` dict in `resolvers/__init__.py`. For simple+languages, the generic stem-map fallback (matching by filename) works out+of the box.++### Verify++```bash+# Run the parser tests+pytest tests/ -k "mylang or sample_repo" -x++# Index a real project+repowise init /path/to/mylang-project+```++No changes are needed to `traverser.py`, `dead_code.py`,+`page_generator.py`, `cost_estimator.py`, or any other consumer file ---+they all derive their language sets from the registry automatically.++---++## Architecture++The language pipeline is fully modular:++```+ingestion/+ languages/ # LanguageRegistry + LanguageSpec (identity data)+ extractors/ # Per-language AST extraction+ 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+ resolvers/ # Per-language import resolution+ python.py # dotted imports, __init__.py, src/ layout+ typescript.py # multi-ext probe, tsconfig aliases+ go.py # go.mod module path stripping+ rust.py # crate::/self::/super::, mod.rs probing+ cpp.py # compile_commands.json include paths+ kotlin.py # package-to-directory mapping+ ruby.py # require/require_relative resolution+ csharp.py # namespace-based resolution+ 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+ parser.py # ASTParser (language-agnostic orchestration)+ graph.py # GraphBuilder (import/call/heritage resolution)+```++Adding a new language requires zero changes to `parser.py`, `graph.py`,+`traverser.py`, `dead_code.py`, or any other core file.++---++## Roadmap++| Language | Target Tier | Status |+|----------|------------|--------|+| Dart | Good | Planned — `tree-sitter-dart` available |+| Elixir | Good | Planned — `tree-sitter-elixir` available |+| F# | Good | Planned — `tree-sitter-f-sharp` available |diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.mdindex 683b86e3b..7ddb56872 100644--- a/docs/architecture/ARCHITECTURE.md+++ b/docs/architecture/ARCHITECTURE.md@@ -163,7 +163,11 @@ repowise/│ │ ├── cpp.scm│ │ ├── c.scm│ │ ├── ruby.scm-│ │ └── kotlin.scm+│ │ ├── kotlin.scm+│ │ ├── csharp.scm+│ │ ├── swift.scm+│ │ ├── scala.scm+│ │ └── php.scm│ ││ ├── server/ # Python: FastAPI REST API + MCP server│ │ └── src/repowise/server/@@ -506,8 +510,8 @@ which runs after the static import graph is built. It operates in three tiers:from the file's import list3. **Global unique match** (confidence 0.50) — target is unique across the whole repo-Call sites are extracted by tree-sitter for all 7 supported languages (Python, TypeScript,-JavaScript, Go, Rust, Java, C++) using per-language `.scm` query files. Results are stored+Call sites are extracted by tree-sitter for all 14 supported languages (Python, TypeScript,+JavaScript, Go, Rust, Java, C++, C, Kotlin, Ruby, C#, Swift, Scala, PHP) using per-language `.scm` query files. Results are storedas `CallSite` dataclasses and become `CALLS` edges in the graph.**Named binding resolution** (`NamedBinding` dataclass in `ingestion/models.py`) ensures@@ -1547,19 +1551,27 @@ Key files:),```-3. **Verify `tree-sitter-languages` includes your language**+3. **Add a `LanguageSpec` to `LanguageRegistry`** in `ingestion/languages/registry.py`- Run `python -c "from tree_sitter_languages import get_parser; get_parser('mylang')"`.- If it raises, the grammar is not bundled. You can add it manually as a tree-sitter- grammar and register it with the Language API.+ This registers the language's identity data (extensions, entry points, manifest files,+ builtin calls, heritage node types, etc.) centrally.-4. **Add test files to `tests/fixtures/sample_repo/`**+4. **Add the grammar dependency to `pyproject.toml`**++ ```toml+ "tree-sitter-mylang>=0.23,<1",+ ```++5. **Add test files to `tests/fixtures/sample_repo/`**At minimum: one file with a function, one with a class, one with imports.-5. **Run `pytest tests/unit/test_parser.py -k mylang`** to verify extraction.+6. **(Optional) Add per-language extractors** for bindings, heritage, visibility, docstrings,+ and a dedicated import resolver in `resolvers/mylang.py`.++7. **Run `pytest tests/unit/test_parser.py -k mylang`** to verify extraction.-6. **Open a PR.** That's it — no other changes needed.+8. **Open a PR.** That's it — no other changes needed.---diff --git a/docs/internals/critical-analysis.md b/docs/internals/critical-analysis.mddeleted file mode 100644index e7b5ff690..000000000--- a/docs/internals/critical-analysis.md+++ /dev/null@@ -1,552 +0,0 @@-# Repowise — Critical Analysis--An honest assessment of what Repowise solves, where it can fail, how likely those failures are, and what would make it better.-------## Table of Contents--1. [What Problem Does Repowise Solve?](#1-what-problem-does-repowise-solve)-2. [How Useful Is It?](#2-how-useful-is-it)-3. [Where the Architecture Can Fail](#3-where-the-architecture-can-fail)-4. [Improvement Suggestions](#4-improvement-suggestions)-------## 1. What Problem Does Repowise Solve?--### The core problem: Code knowledge is invisible and perishable--When a developer joins a team, they face a codebase with thousands of files and no map. They ask:--- "What does this file do?" → Read the code, guess, or interrupt someone.-- "Why is it built this way?" → Nobody remembers. The original author left.-- "If I change this, what breaks?" → No way to know without deep expertise.-- "What's dead code vs critical infrastructure?" → Looks the same in the file tree.--This knowledge exists — scattered across git history, code comments, Slack threads, and people's heads. But it's not **accessible** at the moment of need.--### What Repowise does about it--Repowise automates the creation and maintenance of codebase intelligence:--| Problem | Repowise Solution | How |-|---------|-------------------|-----|-| No documentation | Auto-generated wiki pages | Tree-sitter parsing + LLM generation |-| Don't know what's important | PageRank scoring | Graph algorithms on import dependencies |-| Don't know who owns what | Ownership tracking | Git blame + commit history analysis |-| Don't know what's risky to change | Risk assessment | Churn × centrality × bus factor |-| Don't know what's dead | Dead code detection | Graph reachability + git activity |-| Don't know why decisions were made | Decision archaeology | Inline markers + git commit mining + README extraction |-| Documentation goes stale | Incremental updates | Change detection + cascade propagation |-| AI assistants lack codebase context | MCP tools | 8 specialized tools for Claude Code, Cursor, etc. |--### What makes it non-trivial--Many tools generate documentation. Repowise's differentiators are:--1. **Graph-aware intelligence.** It doesn't just document files — it understands how they connect. PageRank identifies what matters. Betweenness identifies bottlenecks. Communities identify subsystems. This structural understanding drives everything from doc priority to risk assessment.--2. **Temporal intelligence.** Git history adds a time dimension. A file's importance isn't just structural (who imports it) but behavioral (how often it changes, who touches it, what changes alongside it). Co-change detection finds coupling invisible in the import graph.--3. **Decision archaeology.** No other tool automatically discovers *why* code is built the way it is by mining commits, comments, and documentation. This is the hardest kind of knowledge to preserve and the most valuable.--4. **Incremental maintenance with cascade.** The cascade algorithm is genuinely clever — it propagates staleness through the dependency graph with a bounded budget, ensuring the most important docs stay fresh without unbounded cost.-------## 2. How Useful Is It?--### High value scenarios--| Scenario | Value | Why |-|----------|-------|-----|-| New developer onboarding | **Very High** | Replaces weeks of "reading code and asking questions" with searchable documentation, architecture diagrams, and ownership maps |-| Pre-refactor impact analysis | **Very High** | `get_risk` tells you exactly what depends on what you're changing, who owns it, and how volatile it is — before you touch anything |-| AI-assisted development | **High** | MCP tools give Claude Code / Cursor deep codebase context. Instead of the AI guessing, it queries real docs, ownership, and decisions |-| Dead code cleanup | **High** | Automated detection with confidence tiers saves engineering time. The "safe to delete" flag reduces review burden |-| Knowledge preservation | **High** | When senior developers leave, their decision rationale is captured in the wiki and decision records instead of leaving with them |-| Code review context | **Medium** | Reviewer can check the wiki for file context, ownership, and governing decisions before reviewing a PR |-| Compliance and auditing | **Medium** | Decision records with provenance (source, evidence commits, confidence) provide audit trails |--### Moderate value scenarios--| Scenario | Value | Limitation |-|----------|-------|-----------|-| Small repos (< 50 files) | **Low** | You can read 50 files yourself. The overhead of running Repowise isn't justified. |-| Rapidly prototyping repos | **Low** | Code changes so fast that documentation is stale within hours. The incremental system helps but can't keep up with constant rewrites. |-| Non-code-heavy repos | **Low** | Repos that are mostly config, data, or documentation get little value from AST parsing and dependency graphs. |--### Quantitative value estimate--For a **500-file repo with 10 developers**:--```-Without Repowise:- New developer onboarding: ~2 weeks of asking questions- Finding file owners: ~10 min per file (git blame, asking around)- Pre-refactor impact: ~1-2 hours of manual grep + tracing- Dead code discovery: ~1-2 days of manual audit per quarter--With Repowise:- New developer onboarding: ~2 days reading wiki + using search- Finding file owners: instant (ownership data in every page)- Pre-refactor impact: ~30 seconds (get_risk tool call)- Dead code discovery: instant (pre-computed with confidence tiers)--Time saved per developer per quarter: ~15-25 hours-For 10 developers: ~150-250 hours/quarter-```--The ROI depends on the LLM cost of `repowise init` (potentially $5-50 depending on provider and repo size) versus the engineering hours saved.-------## 3. Where the Architecture Can Fail--### Failure Category 1: Data Consistency (Three-Store Split)--**The problem:** Repowise writes to three independent stores — SQL, vector store, and graph — without atomic transactions across them. They can get out of sync.--**Failure scenario:**--```-1. LLM generates page content ✓-2. Embed in vector store ✓-3. Upsert in SQL database ✗ (database connection drops)-4. Index in FTS (never reached)--State: Vector store has the page. SQL doesn't. FTS doesn't.-Result: Semantic search finds the page, but clicking it returns 404.-```--**Reverse scenario:**--```-1. LLM generates page content ✓-2. Embed in vector store ✗ (embedding API timeout)-3. Upsert in SQL database ✓-4. Index in FTS ✓--State: SQL and FTS have the page. Vector store doesn't.-Result: Keyword search works. Semantic search misses the page.-```--**Probability: Medium (5-15% over a large init run).** Vector store embedding involves an external API call (OpenAI/Gemini). Over hundreds of pages, at least one is likely to fail. The failure is silent (logged at debug level), so the user may not notice.--**Impact: Low-Medium.** Individual pages missing from one store doesn't break the system — it degrades search quality. But the user has no way to detect or repair the inconsistency.--**Why it happens:** True distributed transactions across SQLite + LanceDB + an embedding API are impractical. The architecture prioritizes availability (keep going if one store fails) over consistency (all stores agree).-------### Failure Category 2: LLM Output Quality--**The problem:** Generated documentation is only as good as the LLM's understanding. The LLM sees assembled context (symbols, imports, source code snippets), not the running system.--**Failure scenarios:**--| Scenario | Probability | Impact |-|----------|------------|--------|-| LLM hallucinates function behavior that doesn't match the code | **Medium (10-20%)** | Misleading docs. Developer trusts wiki and writes incorrect code. |-| LLM misunderstands complex metaprogramming, decorators, or dynamic dispatch | **High (30%+)** for such files | Missing or wrong symbol documentation |-| LLM generates vague "this module handles X" without specifics | **Medium (15-25%)** for low-context files | Docs exist but aren't useful |-| LLM fails to converge on architecture diagram | **Low (< 5%)** | Falls back to no diagram |--**Why it's hard to fix:** The LLM doesn't execute the code. It infers behavior from static text. For straightforward code (clear function names, type annotations, docstrings), accuracy is high. For metaprogramming-heavy code (Python decorators that transform functions, Ruby method_missing, JavaScript Proxy objects), the LLM may produce plausible but wrong descriptions.--**Compounding problem:** Once an incorrect doc is embedded in the vector store, it becomes RAG context for other pages. If `auth.py`'s docs incorrectly describe its behavior, `service.py`'s docs (which reference `auth.py` via dependency summaries) inherit the error.-------### Failure Category 3: Stale Documentation Drift--**The problem:** Even with incremental updates, documentation can drift from reality.--**How staleness accumulates:**--```-Day 1: repowise init → all docs fresh-Day 3: Developer changes config.py → cascade updates 30 pages- But cascade_budget = 30, and 50 pages actually depend on config.py- 20 pages are marked "decay_only" (stale, not regenerated)-Day 5: Developer changes utils.py → cascade updates 30 different pages- The 20 stale pages from Day 3 are still stale-Day 10: Those 20 pages hit staleness_threshold (7 days)- But nobody runs repowise update again-Day 30: Those pages hit expiry_threshold and would be regenerated- IF someone runs repowise update-```--**Probability: High (almost certain) for repos without automated CI integration.** If `repowise update` only runs when a developer remembers to run it, documentation drift is inevitable.--**Impact: Medium.** Stale docs are worse than no docs — they give a false sense of confidence. The freshness indicator (confidence score) mitigates this, but only if developers check it.-------### Failure Category 4: Graph Accuracy (Import Resolution)--**The problem:** The dependency graph is only as accurate as import resolution. Missed or wrong imports lead to wrong PageRank, wrong cascade propagation, and wrong dead code detection.--**Where import resolution fails:**--| Pattern | Example | What Repowise misses |-|---------|---------|---------------------|-| Dynamic imports | `importlib.import_module(name)` | Entire dependency edge |-| Conditional imports | `if TYPE_CHECKING: import X` | Edge exists but is typing-only, not runtime |-| Re-exports through `__init__.py` | `from .utils import *` | May miss specific names in wildcard |-| Barrel files (TypeScript) | `export * from './module'` | Specific names re-exported |-| Build-time code generation | Protobuf → `_pb2.py` files | Generated files might be gitignored |-| Runtime plugin loading | Django apps, pytest plugins | Framework-mediated imports |-| Monkeypatching | `module.func = my_func` | No import edge at all |--**Probability: Medium-High (20-40% of edges affected in large repos).** Most codebases use some dynamic imports. The more framework-heavy the code (Django, Flask, FastAPI with dependency injection), the more imports are invisible to static analysis.--**Impact cascades:**--```-Missing edge A → B means:- - A's documentation doesn't mention dependency on B- - B's PageRank is too low (missing one vote)- - Changing B doesn't cascade to A's docs (becomes stale silently)- - B might be falsely flagged as dead code (in_degree appears lower)-```--**Partial mitigation:** Co-change edges partially compensate. If A and B always change together (captured from git history), they get a co-change edge even without an import edge. But co-change edges don't affect PageRank (deliberately excluded).-------### Failure Category 5: Scale and Performance--**The problem:** Several components are in-memory and O(n²) or worse.--| Component | Complexity | Breaks at | What happens |-|-----------|-----------|-----------|-------------|-| NetworkX graph in memory | O(N + E) memory | ~100K files with dense edges | OOM crash during `graph.build()` |-| Betweenness centrality (exact) | O(N × E) time | >30K nodes | Falls back to sampling (k=500), approximate results |-| PageRank convergence | O(E × iterations) | Unusual graph topologies | `PowerIterationFailedConvergence` → falls back to uniform scores |-| Symbol rename detection | O(removed × added) per file | Files with 500+ symbols | Slow rename detection, but no hard limit |-| InMemory vector search | O(N × D) per query | >10K pages | Seconds per search, kills UX |-| `git log --name-only` | O(commits) | >500K commits | Parsing huge git log output |-| Co-change pair computation | O(files_per_commit²) per commit | Commits touching 100+ files | Quadratic pair generation |--**Probability:**--- For repos < 10K files: **Very Low** (< 1%). Everything fits comfortably.-- For repos 10K-50K files: **Low** (5-10%). Might see betweenness approximation and slower git indexing.-- For repos 50K-100K files: **Medium** (20-30%). Memory pressure on graph, long git indexing times.-- For repos > 100K files: **High** (50%+). Likely needs architectural changes (streaming graph, approximate algorithms, sharded processing).-------### Failure Category 6: Decision Mining Accuracy--**The problem:** LLM-based decision extraction from git commits and READMEs produces false positives and false negatives.--**False positives (phantom decisions):**--```-Commit: "Migrate test fixtures to new format"-LLM extracts: "Decision: Migrate to new test format"-Reality: This was a routine chore, not an architectural decision-Confidence: 0.70 (git_archaeology)-```--**Probability: Medium (15-25% of git-mined decisions).** The word "migrate" triggers extraction, but not every migration is an architectural decision.--**False negatives (missed decisions):**--```-Commit: "Rewrote the query layer because the ORM couldn't handle- the new partitioning scheme"-→ Might be missed if commit doesn't use signal keywords-```--Decisions expressed in natural language without keywords like "migrate", "switch to", "replace" won't be found.--**Impact: Medium.** False positives clutter the decision list (proposed status helps — developers can dismiss them). False negatives mean some decisions are invisible (the harder problem).-------### Failure Category 7: Job System and Resumability--**The problem:** The checkpoint file (JSON on disk) and the database can get out of sync.--**Failure scenario:**--```-1. Page generated successfully-2. job_system.complete_page(job_id, page_id) → JSON file updated ✓-3. Process crashes before session.commit()-4. Database doesn't have the page--On resume:-5. Job checkpoint says page_id is complete (skip it)-6. But database doesn't have it-7. Page is permanently missing-```--**Probability: Low (1-3% per large init run).** Requires a crash between two specific lines. But over hundreds of pages, the window is hit occasionally.--**Impact: Low.** The missing page is a gap in documentation. It won't be regenerated because the checkpoint says it's done. Manual intervention (clearing the checkpoint) is needed.-------### Failure Category 8: Security and Sensitive Data--**The problem:** Repowise sends source code to external LLM APIs.--| Risk | Probability | Severity |-|------|------------|----------|-| Source code sent to LLM API (Anthropic, OpenAI) includes secrets | **Low** (file size + gitignore filtering helps) | **High** if secrets leak |-| `.env` files parsed and sent as context | **Very Low** (excluded by traverser) | **Critical** |-| API keys in code comments sent to LLM | **Low-Medium** | **High** |-| Generated docs stored in plain text in `.repowise/wiki.db` | **Certain** (by design) | **Medium** (local file, but if shared...) |-| Vector embeddings encode semantic content of code | **Certain** | **Low** (embeddings aren't reversible to code, but contain signal) |--**Mitigation:** Ollama provider supports fully offline operation. For sensitive codebases, this is the only safe option.-------### Summary: Failure probability matrix--| Failure Category | Probability | Impact | Detection | Recovery |-|-----------------|------------|--------|-----------|----------|-| Three-store inconsistency | Medium | Low-Medium | Hard (silent failures) | Manual re-index |-| LLM hallucination in docs | Medium | Medium | Hard (looks plausible) | Re-generate page |-| Documentation staleness | High | Medium | Easy (confidence score) | Run update |-| Import resolution gaps | Medium-High | Medium | Hard (invisible edges) | None (fundamental limit) |-| Scale/performance limits | Low-High (repo dependent) | High | Easy (OOM, timeout) | Architecture changes |-| Decision mining false positives | Medium | Low | Easy (review proposed) | Dismiss via CLI |-| Job checkpoint desync | Low | Low | Hard (silent gap) | Clear checkpoint |-| Sensitive data exposure | Low | High | Medium (audit logs) | Use Ollama |-------## 4. Improvement Suggestions--> **Note:** Five of the improvements below have been implemented. They are marked with **(IMPLEMENTED)** and describe what was built rather than what should be built.--### Priority 1: Data Consistency (High impact, Medium effort) — IMPLEMENTED--**Problem:** Three stores can get out of sync.--**Implemented: `repowise doctor --repair`**--The `doctor` command now checks SQL↔Vector Store and SQL↔FTS consistency by comparing page ID sets across all three stores. With `--repair`, it re-embeds missing vector entries, re-indexes missing FTS entries, and deletes orphans. This is powered by new `list_page_ids()` methods on all vector store implementations and `list_indexed_ids()` on FullTextSearch.--**Original suggestion (not yet implemented): Write-ahead log for multi-store writes**--```-Before:- 1. embed_to_vector_store(page) # may fail- 2. upsert_to_sql(page) # may fail- 3. index_to_fts(page) # may fail--After:- 1. write_to_wal(page_id, content, metadata) # single append- 2. embed_to_vector_store(page) # may fail- 3. upsert_to_sql(page) # may fail- 4. index_to_fts(page) # may fail- 5. mark_wal_entry_complete(page_id)--On startup:- for entry in wal where not complete:- retry all three stores-```--This doesn't give you atomic transactions, but it gives you **eventual consistency** — every page that was generated will eventually land in all three stores, even if the process crashes mid-write.--**Simpler alternative:** Add a `repowise doctor --repair` command that compares SQL pages vs vector store entries vs FTS index and re-syncs any mismatches. Not real-time, but catches drift.--### Priority 2: LLM Output Validation (High impact, Low effort) — IMPLEMENTED--**Problem:** LLM output is trusted without validation.--**Implemented:** `_validate_symbol_references()` in `page_generator.py` extracts all backtick-quoted names from generated markdown via regex, cross-checks them against actual symbols, exports, and imports from the ParsedFile. Warnings are logged via structlog and stored in `page.metadata["hallucination_warnings"]`. Common language keywords and builtins are excluded via `_BACKTICK_SKIP`.--**Additional suggestions (not yet implemented):**--1. **Structural validation:** After LLM generates a page, verify it contains expected sections (e.g., file_page should have at least a title and a symbol table). Reject and retry if malformed.--2. **Factual cross-check:** Compare function names in the generated docs against actual symbol names from AST parsing. If the docs reference a function that doesn't exist in the file, flag as hallucination.-- ```python- actual_symbols = {s.name for s in parsed_file.symbols}- mentioned_symbols = extract_code_references(generated_content)- hallucinated = mentioned_symbols - actual_symbols- if hallucinated:- log.warning("Possible hallucination", symbols=hallucinated)- # Option: re-generate with stronger prompt, or add warning to page- ```--3. **Confidence-weighted display:** Show LLM confidence alongside generated content. Pages generated with "minimal" depth or low-context could display a "low detail" indicator.--### Priority 3: Dynamic Import Detection (High impact, High effort) — PARTIALLY IMPLEMENTED--**Problem:** Static import resolution misses dynamic imports, framework-mediated loading, and plugin systems.--**Implemented:** `add_framework_edges()` on `GraphBuilder` adds synthetic edges with `edge_type="framework"` for four frameworks:-- **pytest**: conftest.py → test files in same/child directories-- **Django**: admin→models, urls→views, forms→models, serializers→models-- **FastAPI**: `include_router()` calls → router modules-- **Flask**: `register_blueprint()` calls → blueprint modules--Framework detection uses regex on source code and the existing `detect_tech_stack()` from manifest files. Called automatically during `repowise init` and `repowise update`.--**Additional suggestions (not yet implemented):**--1. **More framework-aware heuristics:** Additional patterns to detect:-- ```python- # Django: settings.INSTALLED_APPS → app module imports- # Flask: app.register_blueprint(bp) → blueprint module- # FastAPI: app.include_router(router) → router module- # pytest: conftest.py fixtures → test files using them- ```-- Each framework pattern is a known import mechanism that can be statically detected even though it's not a Python `import` statement.--2. **Runtime trace integration (optional):** For Python, run `sys.settrace()` during tests to capture actual imports. Merge runtime edges with static edges. This captures every dynamic import that's exercised by tests. Downside: requires running tests, which may be slow or unavailable.--3. **Heuristic edge recovery from co-change:** If two files always co-change AND are in related directories AND have overlapping symbol names, add a weak synthetic import edge. This is noisy but better than nothing for dynamic-import-heavy codebases.--### Priority 4: Scale Architecture (Medium impact, High effort)--**Problem:** In-memory graph, in-memory vector search, and O(n²) algorithms limit scale.--**Suggestions:**--1. **Streaming graph construction:** Instead of building the full NetworkX graph in memory, use a SQLite-backed graph where nodes and edges are stored in tables. Compute metrics incrementally or with SQL-based algorithms.-- ```- Current: Build graph in memory → compute metrics → persist to SQLite- Improved: Build directly in SQLite → compute metrics with SQL queries- (PageRank via iterative SQL)- ```--2. **Approximate graph metrics at scale:** For repos > 50K files, consider:- - **PageRank:** Use the power iteration directly on the edge list (no need for full graph in memory). Can be done with SQL or sparse matrix operations.- - **Betweenness:** Already approximated with sampling. Could use a more efficient algorithm like Brandes' with better sampling strategies.- - **Communities:** Louvain is already fast. No change needed.--3. **Chunk-based vector search:** Replace InMemoryVectorStore default with LanceDB even for small repos. LanceDB handles scaling internally with IVF-PQ indexes. The in-memory implementation should be test-only.--4. **Parallel git indexing with process pool:** The current ThreadPoolExecutor(20) is limited by Python's GIL for CPU-bound work and GitPython's thread safety for I/O. Consider using `multiprocessing` for git operations, or calling `git log` as a subprocess and parsing output.--### Priority 5: Staleness Prevention (Medium impact, Medium effort) — PARTIALLY IMPLEMENTED--**Problem:** Documentation drifts if nobody runs `repowise update`.--**Suggestions:**--1. **CI/CD integration as first-class:** Provide a GitHub Action and GitLab CI template that runs `repowise update` on every push to main. This makes maintenance automatic rather than opt-in.-- ```yaml- # .github/workflows/repowise.yml- on:- push:- branches: [main]- jobs:- update-docs:- runs-on: ubuntu-latest- steps:- - uses: actions/checkout@v4- with: { fetch-depth: 0 }- - run: pip install repowise-cli- - run: repowise update --cascade-budget 50- - run: repowise serve --export # publish to static site- ```--2. **Staleness alerts in CLAUDE.md:** When generating CLAUDE.md, include a staleness summary:-- ```markdown- ⚠ 15 pages are stale (last updated > 7 days ago)- Run `repowise update` to refresh documentation.- ```-- AI coding assistants reading CLAUDE.md would see this and could suggest running an update.--3. **Smarter cascade budgeting — IMPLEMENTED:** `compute_adaptive_budget()` in `change_detector.py` scales budget by change magnitude: 1 file→10, 2-5→30, 6+→min(n×3, 50). Hard cap at 50. The `--cascade-budget` CLI flag defaults to auto when unset, and users can still override manually.--### Priority 6: Decision System Refinement (Medium impact, Low effort)--**Problem:** False positives in git archaeology; no user feedback loop.--**Suggestions:**--1. **Feedback-weighted confidence:** When a developer dismisses a proposed decision (via `repowise decision dismiss`), record the false positive pattern. Over time, learn which commit message patterns produce false positives and lower their confidence.-- ```- Dismissed: "Migrate test fixtures to new format" (git_archaeology)- Pattern learned: "migrate" + "test" + "fixture" → lower confidence by 0.15- ```--2. **Decision coverage in file pages:** When generating a file_page, include a section on governing decisions. This surfaces decisions where developers actually need them — in the documentation for the file they're about to modify.--3. **Decision expiry:** Auto-deprecate decisions that haven't been confirmed and have high staleness scores for > 90 days. Currently decisions stay "active" forever unless manually changed.--### Priority 7: Observability and Repair (Low impact, Low effort) — IMPLEMENTED--**Problem:** Failures are silent. Users don't know when something is degraded.--**Implemented:**--1. **`repowise doctor --repair`:** Extended with three-store consistency checks (SQL↔Vector, SQL↔FTS) and automated repair (re-embed, re-index, delete orphans). See Priority 1.--2. **Generation report:** `GenerationReport` dataclass in `report.py` with `render_report()` prints a rich table after `repowise update` showing: pages by type, input/output/cached tokens, estimated cost, elapsed time, stale page count, hallucination warning count, and decisions extracted.--**Not yet implemented:**--3. **Structured error log:** `.repowise/errors.json` with timestamped, categorized errors. The `doctor` command would read this to suggest repairs.--### Priority 8: Testing and Validation (Low impact, High effort)--**Suggestions:**--1. **Golden test suite:** For 3-5 well-known open source repos (different sizes, languages, frameworks), generate documentation and manually validate key pages. Store as golden snapshots. Run against each new Repowise version to detect regressions.--2. **Scale benchmark:** Run `repowise init` against repos of increasing size (1K, 5K, 10K, 50K, 100K files) and record: wall time, peak memory, LLM token cost, page quality (manual sample). Publish as a benchmark table.--3. **Import resolution accuracy test:** For a known repo, manually annotate all import relationships. Compare against Repowise's resolved graph. Compute precision (no false edges) and recall (no missing edges). This quantifies the fundamental limitation of static import resolution.-------## Summary--### What Repowise gets right--- **Graph-first architecture** is the right foundation. Import graphs capture real structural dependencies that keyword search and file-listing tools miss entirely.-- **Temporal intelligence** (git history, co-change, staleness) adds a dimension that pure static analysis can't provide.-- **Bounded cascade** is an elegant solution to the exponential propagation problem. PageRank-sorted budgets ensure the most valuable docs stay fresh.-- **Multi-source decision extraction** is genuinely novel. No other open-source tool mines architectural intent from commits, comments, and documentation simultaneously.-- **MCP integration** makes the intelligence immediately useful inside AI coding workflows, which is where developers increasingly spend their time.--### What has been addressed--Five of the top priorities have been implemented:--| Risk | Status | Implementation |-|------|--------|---------------|-| Three-store consistency | **Fixed** | `doctor --repair` checks SQL↔Vector↔FTS and auto-repairs |-| Dynamic import blindness | **Partially fixed** | Framework edges for pytest, Django, FastAPI, Flask |-| LLM output validation | **Fixed** | Symbol cross-check on every file_page generation |-| Cascade budget rigidity | **Fixed** | Adaptive budget scales 10-50 based on change magnitude |-| Silent failures | **Fixed** | Generation report after every update run |--### What still needs work--1. **CI-first staleness prevention** — the biggest adoption risk. A GitHub Action template exists in `docs/` but isn't yet a first-class integration.-2. **Scale architecture** — in-memory graph and O(n²) algorithms still limit repos > 50K files.-3. **Decision auto-expiry** — decisions with high staleness for 90+ days should auto-deprecate (partially designed, not yet in crud.py).-4. **Runtime trace integration** — would capture dynamic imports exercised by tests, complementing the static framework heuristics.--### Overall assessment--Repowise solves a real, painful problem. The architecture is well-designed for its intended scale (repos up to ~50K files). The graph-based approach is fundamentally sound — it captures structural relationships that simpler tools miss. The incremental update system with adaptive cascade budgets is sophisticated and practical.--The recent improvements address the top risks: three-store consistency is now detectable and repairable, LLM hallucinations are flagged via symbol cross-checking, framework-mediated imports are captured for the most common Python frameworks, and generation runs produce clear cost/quality summaries.--Remaining risks are: adoption requiring CI integration for automatic maintenance, scale limits for very large monorepos, and decision system maturity. None of these are fundamental to the architecture — they're engineering hardening, not redesign.--For a team with a 500-10,000 file codebase that wants to reduce onboarding time, improve refactoring safety, and preserve architectural knowledge, Repowise delivers substantial value. For very small repos (< 50 files) or very large monorepos (> 100K files), the value proposition is weaker — the first doesn't need it, the second might outgrow it.diff --git a/packages/cli/src/repowise/cli/cost_estimator.py b/packages/cli/src/repowise/cli/cost_estimator.pyindex 8098da282..38a7f38e3 100644--- a/packages/cli/src/repowise/cli/cost_estimator.py+++ b/packages/cli/src/repowise/cli/cost_estimator.py@@ -6,30 +6,11 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any-# ----------------------------------------------------------------------------# Infra / significance helpers (mirrored from page_generator.py)-# ---------------------------------------------------------------------------+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY-_INFRA_LANGUAGES = frozenset({"dockerfile", "makefile", "terraform", "shell"})+_INFRA_LANGUAGES = _LANG_REGISTRY.infra_languages()_INFRA_FILENAMES = frozenset({"Dockerfile", "Makefile", "GNUmakefile"})-_CODE_LANGUAGES = frozenset(- {- "python",- "typescript",- "javascript",- "go",- "rust",- "java",- "cpp",- "c",- "csharp",- "ruby",- "kotlin",- "scala",- "swift",- "php",- }-)+_CODE_LANGUAGES = _LANG_REGISTRY.code_languages()def _is_infra_file(parsed: Any) -> bool:diff --git a/packages/cli/src/repowise/cli/ui.py b/packages/cli/src/repowise/cli/ui.pyindex 597c99cf2..ae27c3884 100644--- a/packages/cli/src/repowise/cli/ui.py+++ b/packages/cli/src/repowise/cli/ui.py@@ -17,6 +17,8 @@ from rich.rule import Rulefrom rich.table import Tablefrom rich.text import Text+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY+# ---------------------------------------------------------------------------# Brand / theme# ---------------------------------------------------------------------------@@ -71,30 +73,23 @@ class RepoScanInfo:_TEST_PATTERNS = {"test_", "_test.", ".test.", "tests/", "test/", "__tests__/", "spec/"}_INFRA_NAMES = {"dockerfile", "makefile", "jenkinsfile", "terraform", ".tf", ".sh", ".bash"}+# Derived from the centralised LanguageRegistry, supplemented with+# display-only languages (HTML, CSS) not tracked by the pipeline._LANG_MAP: dict[str, list[str]] = {- "Python": [".py"],- "TypeScript": [".ts", ".tsx"],- "JavaScript": [".js", ".jsx", ".mjs", ".cjs"],- "Go": [".go"],- "Rust": [".rs"],- "Java": [".java"],- "C#": [".cs"],- "Ruby": [".rb"],- "PHP": [".php"],- "Swift": [".swift"],- "Kotlin": [".kt", ".kts"],- "C/C++": [".c", ".cpp", ".cc", ".h", ".hpp"],- "Scala": [".scala"],- "Dart": [".dart"],- "Lua": [".lua"],- "Shell": [".sh", ".bash", ".zsh"],- "HTML": [".html", ".htm"],- "CSS": [".css", ".scss", ".sass", ".less"],- "YAML": [".yaml", ".yml"],- "JSON": [".json"],- "Markdown": [".md", ".mdx"],- "SQL": [".sql"],+ spec.display_name: sorted(spec.extensions)+ for spec in _LANG_REGISTRY.all_specs()+ if spec.extensions and spec.tag != "unknown"}+# C and C++ are shown together in the CLI scan+_LANG_MAP["C/C++"] = sorted(+ (_LANG_REGISTRY.get("c") or _LANG_REGISTRY.get("cpp")).extensions # type: ignore[union-attr]+ | (_LANG_REGISTRY.get("cpp") or _LANG_REGISTRY.get("c")).extensions # type: ignore[union-attr]+)+_LANG_MAP.pop("C", None)+_LANG_MAP.pop("C++", None)+# Display-only languages not in the pipeline+_LANG_MAP["HTML"] = [".html", ".htm"]+_LANG_MAP["CSS"] = [".css", ".scss", ".sass", ".less"]_EXT_TO_LANG: dict[str, str] = {}for _lang, _exts in _LANG_MAP.items():for _ext in _exts:diff --git a/packages/core/queries/c.scm b/packages/core/queries/c.scmdeleted file mode 100644index 8bbc2d100..000000000--- a/packages/core/queries/c.scm+++ /dev/null@@ -1,35 +0,0 @@-; =============================================================================-; repowise — C symbol and import queries-; Uses the tree-sitter-cpp grammar (superset of C)-; =============================================================================--; ----------------------------------------------------------------------------; Symbols-; -----------------------------------------------------------------------------(function_definition- declarator: (function_declarator- declarator: (identifier) @symbol.name- parameters: (parameter_list) @symbol.params- )-) @symbol.def--(struct_specifier- name: (type_identifier) @symbol.name-) @symbol.def--(enum_specifier- name: (type_identifier) @symbol.name-) @symbol.def--; ----------------------------------------------------------------------------; Imports (#include directives)-; -----------------------------------------------------------------------------(preproc_include- path: (system_lib_string) @import.module-) @import.statement--(preproc_include- path: (string_literal) @import.module-) @import.statementdiff --git a/packages/core/queries/cpp.scm b/packages/core/queries/cpp.scmdeleted file mode 100644index da57ec9fe..000000000--- a/packages/core/queries/cpp.scm+++ /dev/null@@ -1,62 +0,0 @@-; =============================================================================-; repowise — C++ symbol and import queries-; tree-sitter-cpp >= 0.23-; (Also used for .c files — C is a subset of this grammar for our purposes)-; =============================================================================--; ----------------------------------------------------------------------------; Symbols-; -----------------------------------------------------------------------------; Function definition: ReturnType funcName(params) { body }-; The name is nested inside function_declarator-(function_definition- declarator: (function_declarator- declarator: (identifier) @symbol.name- parameters: (parameter_list) @symbol.params- )-) @symbol.def--; Qualified function definition: ReturnType ClassName::method(params) { }-(function_definition- declarator: (function_declarator- declarator: (qualified_identifier- name: (identifier) @symbol.name- )- parameters: (parameter_list) @symbol.params- )-) @symbol.def--; Class-(class_specifier- name: (type_identifier) @symbol.name-) @symbol.def--; Struct-(struct_specifier- name: (type_identifier) @symbol.name-) @symbol.def--; Enum (type_identifier is a direct child, not a named field in this grammar)-(enum_specifier- (type_identifier) @symbol.name-) @symbol.def--; Namespace-(namespace_definition- name: (namespace_identifier) @symbol.name-) @symbol.def--; ----------------------------------------------------------------------------; Imports (#include directives)-; -----------------------------------------------------------------------------; #include <header>-(preproc_include- path: (system_lib_string) @import.module-) @import.statement--; #include "local_header"-(preproc_include- path: (string_literal) @import.module-) @import.statementdiff --git a/packages/core/queries/go.scm b/packages/core/queries/go.scmdeleted file mode 100644index 432409d04..000000000--- a/packages/core/queries/go.scm+++ /dev/null@@ -1,36 +0,0 @@-; =============================================================================-; repowise — Go symbol and import queries-; tree-sitter-go >= 0.23-; =============================================================================--; ----------------------------------------------------------------------------; Symbols-; -----------------------------------------------------------------------------; Top-level function-(function_declaration- name: (identifier) @symbol.name- parameters: (parameter_list) @symbol.params-) @symbol.def--; Method with receiver — @symbol.receiver is used to determine parent type-(method_declaration- receiver: (parameter_list) @symbol.receiver- name: (field_identifier) @symbol.name- parameters: (parameter_list) @symbol.params-) @symbol.def--; Type declaration (struct, interface, alias)-; type_spec is always inside type_declaration-(type_spec- name: (type_identifier) @symbol.name-) @symbol.def--; ----------------------------------------------------------------------------; Imports-; -----------------------------------------------------------------------------; Single import: import "fmt"-(import_spec- (interpreted_string_literal) @import.module-) @import.statementdiff --git a/packages/core/queries/java.scm b/packages/core/queries/java.scmdeleted file mode 100644index a3d7428e7..000000000--- a/packages/core/queries/java.scm+++ /dev/null@@ -1,44 +0,0 @@-; =============================================================================-; repowise — Java symbol and import queries-; tree-sitter-java >= 0.23-; =============================================================================--; ----------------------------------------------------------------------------; Symbols-; -----------------------------------------------------------------------------(class_declaration- name: (identifier) @symbol.name-) @symbol.def--(interface_declaration- name: (identifier) @symbol.name-) @symbol.def--(enum_declaration- name: (identifier) @symbol.name-) @symbol.def--(method_declaration- name: (identifier) @symbol.name- parameters: (formal_parameters) @symbol.params-) @symbol.def--(constructor_declaration- name: (identifier) @symbol.name- parameters: (formal_parameters) @symbol.params-) @symbol.def--; Public modifier capture-(method_declaration- (modifiers) @symbol.modifiers- name: (identifier) @symbol.name-) @symbol.def--; ----------------------------------------------------------------------------; Imports-; -----------------------------------------------------------------------------(import_declaration- (scoped_identifier) @import.module-) @import.statementdiff --git a/packages/core/queries/javascript.scm b/packages/core/queries/javascript.scmdeleted file mode 100644index 503866a29..000000000--- a/packages/core/queries/javascript.scm+++ /dev/null@@ -1,45 +0,0 @@-; =============================================================================-; repowise — JavaScript symbol and import queries-; tree-sitter-javascript >= 0.23-; =============================================================================--; ----------------------------------------------------------------------------; Symbols-; -----------------------------------------------------------------------------(function_declaration- name: (identifier) @symbol.name- parameters: (formal_parameters) @symbol.params-) @symbol.def--(generator_function_declaration- name: (identifier) @symbol.name- parameters: (formal_parameters) @symbol.params-) @symbol.def--(class_declaration- name: (identifier) @symbol.name-) @symbol.def--(method_definition- name: (property_identifier) @symbol.name- parameters: (formal_parameters) @symbol.params-) @symbol.def--; Arrow function assigned to const/let-(lexical_declaration- (variable_declarator- name: (identifier) @symbol.name- value: (arrow_function- parameters: (formal_parameters) @symbol.params- )- )-) @symbol.def--; ----------------------------------------------------------------------------; Imports-; -----------------------------------------------------------------------------(import_statement- source: (string) @import.module-) @import.statementdiff --git a/packages/core/queries/kotlin.scm b/packages/core/queries/kotlin.scmdeleted file mode 100644index 6190b04ab..000000000--- a/packages/core/queries/kotlin.scm+++ /dev/null@@ -1,25 +0,0 @@-; =============================================================================-; repowise — Kotlin symbol and import queries-; tree-sitter-kotlin (install separately if needed)-; =============================================================================--(function_declaration- (simple_identifier) @symbol.name- (function_value_parameters) @symbol.params-) @symbol.def--(class_declaration- (type_identifier) @symbol.name-) @symbol.def--(object_declaration- (type_identifier) @symbol.name-) @symbol.def--(interface_declaration- (type_identifier) @symbol.name-) @symbol.def--(import_header- (identifier) @import.module-) @import.statementdiff --git a/packages/core/queries/python.scm b/packages/core/queries/python.scmdeleted file mode 100644index 6558b115b..000000000--- a/packages/core/queries/python.scm+++ /dev/null@@ -1,59 +0,0 @@-; =============================================================================-; repowise — Python symbol and import queries-; tree-sitter-python >= 0.23-;-; Capture name conventions (shared across ALL language query files):-; @symbol.def — the full definition node (used for line numbers, kind)-; @symbol.name — the name identifier node-; @symbol.params — parameter list node (optional)-; @symbol.modifiers — decorator / visibility modifier nodes (optional)-; @import.statement — the full import node-; @import.module — the module path being imported from-; =============================================================================--; ----------------------------------------------------------------------------; Symbols-; -----------------------------------------------------------------------------; Function (covers both regular and async — in tree-sitter-python >= 0.23-; async functions share the function_definition node type)-(function_definition- name: (identifier) @symbol.name- parameters: (parameters) @symbol.params-) @symbol.def--; Class-(class_definition- name: (identifier) @symbol.name-) @symbol.def--; Decorated function or class — captures the decorator as a modifier-(decorated_definition- (decorator) @symbol.modifiers- (function_definition- name: (identifier) @symbol.name- parameters: (parameters) @symbol.params- ) @symbol.def-)--(decorated_definition- (decorator) @symbol.modifiers- (class_definition- name: (identifier) @symbol.name- ) @symbol.def-)--; ----------------------------------------------------------------------------; Imports-; -----------------------------------------------------------------------------; from x.y import a, b-; from . import x-(import_from_statement- module_name: (_) @import.module-) @import.statement--; import x.y.z-(import_statement- name: (_) @import.module-) @import.statementdiff --git a/packages/core/queries/ruby.scm b/packages/core/queries/ruby.scmdeleted file mode 100644index 05de0efcd..000000000--- a/packages/core/queries/ruby.scm+++ /dev/null@@ -1,30 +0,0 @@-; =============================================================================-; repowise — Ruby symbol and import queries-; tree-sitter-ruby (install separately if needed)-; =============================================================================--(method- name: (identifier) @symbol.name- parameters: (method_parameters)? @symbol.params-) @symbol.def--(singleton_method- name: (identifier) @symbol.name-) @symbol.def--(class- name: (constant) @symbol.name-) @symbol.def--(module- name: (constant) @symbol.name-) @symbol.def--; require 'module' / require_relative './sibling'-(call- method: (identifier) @_require_method- arguments: (argument_list- (string (string_content) @import.module)- )- (#match? @_require_method "^require")-) @import.statementdiff --git a/packages/core/queries/rust.scm b/packages/core/queries/rust.scmdeleted file mode 100644index f0367a84d..000000000--- a/packages/core/queries/rust.scm+++ /dev/null@@ -1,56 +0,0 @@-; =============================================================================-; repowise — Rust symbol and import queries-; tree-sitter-rust >= 0.23-; =============================================================================--; ----------------------------------------------------------------------------; Symbols-; -----------------------------------------------------------------------------(function_item- name: (identifier) @symbol.name- parameters: (parameters) @symbol.params-) @symbol.def--(struct_item- name: (type_identifier) @symbol.name-) @symbol.def--(enum_item- name: (type_identifier) @symbol.name-) @symbol.def--(trait_item- name: (type_identifier) @symbol.name-) @symbol.def--; impl block — the "type" field identifies what is being implemented-(impl_item- type: (type_identifier) @symbol.name-) @symbol.def--(const_item- name: (identifier) @symbol.name-) @symbol.def--(type_item- name: (type_identifier) @symbol.name-) @symbol.def--(mod_item- name: (identifier) @symbol.name-) @symbol.def--; pub visibility modifier-(function_item- (visibility_modifier) @symbol.modifiers- name: (identifier) @symbol.name-) @symbol.def--; ----------------------------------------------------------------------------; Imports-; -----------------------------------------------------------------------------(use_declaration- argument: (_) @import.module-) @import.statementdiff --git a/packages/core/queries/typescript.scm b/packages/core/queries/typescript.scmdeleted file mode 100644index a02f871b1..000000000--- a/packages/core/queries/typescript.scm+++ /dev/null@@ -1,78 +0,0 @@-; =============================================================================-; repowise — TypeScript symbol and import queries-; tree-sitter-typescript >= 0.23-; =============================================================================--; ----------------------------------------------------------------------------; Symbols-; -----------------------------------------------------------------------------; Top-level function declaration-(function_declaration- name: (identifier) @symbol.name- parameters: (formal_parameters) @symbol.params-) @symbol.def--; Generator function-(generator_function_declaration- name: (identifier) @symbol.name- parameters: (formal_parameters) @symbol.params-) @symbol.def--; Class declaration-(class_declaration- name: (type_identifier) @symbol.name-) @symbol.def--; Abstract class-(abstract_class_declaration- name: (type_identifier) @symbol.name-) @symbol.def--; Interface-(interface_declaration- name: (type_identifier) @symbol.name-) @symbol.def--; Type alias-(type_alias_declaration- name: (type_identifier) @symbol.name-) @symbol.def--; Enum-(enum_declaration- name: (identifier) @symbol.name-) @symbol.def--; Method inside class body-(method_definition- name: (property_identifier) @symbol.name- parameters: (formal_parameters) @symbol.params-) @symbol.def--; Arrow function assigned to const/let: const foo = (...) => { }-(lexical_declaration- (variable_declarator- name: (identifier) @symbol.name- value: (arrow_function- parameters: (formal_parameters) @symbol.params- )- )-) @symbol.def--; Public method accessor modifier capture-(method_definition- (accessibility_modifier) @symbol.modifiers- name: (property_identifier) @symbol.name-) @symbol.def--; ----------------------------------------------------------------------------; Imports-; -----------------------------------------------------------------------------; import { A, B } from "./module"-; import type { T } from "./types"-; import DefaultExport from "module"-(import_statement- source: (string) @import.module-) @import.statementdiff --git a/packages/core/src/repowise/core/analysis/dead_code.py b/packages/core/src/repowise/core/analysis/dead_code.pyindex dc623ac7f..778323bb5 100644--- a/packages/core/src/repowise/core/analysis/dead_code.py+++ b/packages/core/src/repowise/core/analysis/dead_code.py@@ -17,6 +17,8 @@ from typing import Anyimport structlog+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY+logger = structlog.get_logger(__name__)@@ -56,24 +58,13 @@ class DeadCodeReport:# Non-code languages that should never be flagged as dead code.-# These files have no import/export semantics — in_degree=0 is expected and-# meaningless for them. Matches the skip lists in git_indexer and page_generator.+# Derived from the centralised LanguageRegistry — passthrough config/infra+# languages plus "unknown"._NON_CODE_LANGUAGES: frozenset[str] = frozenset(- {- "json",- "yaml",- "toml",- "markdown",- "sql",- "shell",- "terraform",- "proto",- "graphql",- "dockerfile",- "makefile",- "unknown",- }-)+ 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 = (@@ -185,13 +176,25 @@ class DeadCodeAnalyzer:All analysis is graph traversal + SQL. No LLM calls."""- # Patterns in source that indicate dynamic/runtime imports.- _DYNAMIC_IMPORT_MARKERS = (- "importlib.import_module",- "__import__(",- "importlib.reload",- "pkgutil.iter_modules",- )+ # 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("),+ }def __init__(self,@@ -207,9 +210,10 @@ class DeadCodeAnalyzer: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`` or ``__import__``,- unreachable modules in the same package may be loaded at runtime.- We use this to lower confidence on those findings.+ 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():@@ -218,10 +222,11 @@ class DeadCodeAnalyzer:if abs_path is None:continuesrc_path = Path(abs_path.abs_path)- if src_path.suffix != ".py":+ markers = cls._DYNAMIC_IMPORT_MARKERS.get(src_path.suffix)+ if not markers:continuesource = src_path.read_text(errors="ignore")- if any(marker in source for marker in cls._DYNAMIC_IMPORT_MARKERS):+ if any(marker in source for marker in markers):result.add(path)except Exception:continue@@ -444,21 +449,24 @@ class DeadCodeAnalyzer:if self._should_never_flag(str(node), whitelist):continue- # Get symbols for this file from graph node data- symbols = node_data.get("symbols", [])+ # Get symbols defined in this file via DEFINES edges to symbol nodes+ symbols = [+ self.graph.nodes[succ]+ for succ in self.graph.successors(node)+ if self.graph.nodes[succ].get("node_type") == "symbol"+ and self.graph.get_edge_data(node, succ, {}).get("edge_type") == "defines"+ ]if not symbols:continuefile_has_importers = self.graph.in_degree(node) > 0for sym in symbols:- if not isinstance(sym, dict):- continueif sym.get("visibility") != "public":continuesym_name = sym.get("name", "")- # Skip framework decorators+ # 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@@ -494,8 +502,7 @@ class DeadCodeAnalyzer:else:confidence = 0.7- complexity = sym.get("complexity_estimate", 0)- safe = confidence >= 0.7 and complexity < 5+ safe = confidence >= 0.7git_meta = self.git_meta_map.get(str(node), {})@@ -527,9 +534,68 @@ class DeadCodeAnalyzer:dynamic_patterns: tuple[str, ...],whitelist: set[str],) -> list[DeadCodeFindingData]:- """Detect private symbols with no calls edges from same file."""- # Higher false positive rate — off by default- return []+ """Detect private/internal symbols with zero incoming call edges.++ Off by default (higher false-positive rate). Enable with+ ``detect_unused_internals=True`` in the config dict.+ """+ findings: list[DeadCodeFindingData] = []++ for node, node_data in self.graph.nodes(data=True):+ if node_data.get("node_type") != "symbol":+ 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+ file_data = self.graph.nodes.get(file_path, {})+ if file_data.get("is_test", False):+ continue+ if _is_fixture_path(file_path):+ continue+ if self._should_never_flag(file_path, whitelist):+ 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)+ )+ if has_callers:+ continue++ git_meta = self.git_meta_map.get(file_path, {})+ findings.append(+ DeadCodeFindingData(+ kind=DeadCodeKind.UNUSED_INTERNAL,+ file_path=file_path,+ symbol_name=sym_name,+ symbol_kind=node_data.get("kind"),+ confidence=0.65,+ reason=f"Private symbol '{sym_name}' has no callers",+ last_commit_at=git_meta.get("last_commit_at")+ if isinstance(git_meta.get("last_commit_at"), datetime)+ else None,+ commit_count_90d=git_meta.get("commit_count_90d", 0),+ lines=node_data.get("end_line", 0) - node_data.get("start_line", 0),+ package=self._get_package(file_path),+ evidence=[f"No CALL edges to '{sym_name}'"],+ safe_to_delete=False,+ primary_owner=git_meta.get("primary_owner_name"),+ age_days=git_meta.get("age_days"),+ )+ )++ return findingsdef _detect_zombie_packages(self, whitelist: set[str]) -> list[DeadCodeFindingData]:"""Detect monorepo packages with no incoming inter_package edges."""diff --git a/packages/core/src/repowise/core/generation/page_generator.py b/packages/core/src/repowise/core/generation/page_generator.pyindex 24150a355..40bf35258 100644--- a/packages/core/src/repowise/core/generation/page_generator.py+++ b/packages/core/src/repowise/core/generation/page_generator.py@@ -25,6 +25,7 @@ from typing import Anyimport jinja2import structlog+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRYfrom repowise.core.ingestion.models import ParsedFile, RepoStructurefrom repowise.core.providers.llm.base import BaseProvider, GeneratedResponse@@ -107,29 +108,9 @@ SYSTEM_PROMPTS: dict[str, str] = {),}-# Infra file languages-_INFRA_LANGUAGES = frozenset({"dockerfile", "makefile", "terraform", "shell"})+_INFRA_LANGUAGES = _LANG_REGISTRY.infra_languages()_INFRA_FILENAMES = frozenset({"Dockerfile", "Makefile", "GNUmakefile"})--# Languages worth generating file pages for — data/config/doc files excluded-_CODE_LANGUAGES = frozenset(- {- "python",- "typescript",- "javascript",- "go",- "rust",- "java",- "cpp",- "c",- "csharp",- "ruby",- "kotlin",- "scala",- "swift",- "php",- }-)+_CODE_LANGUAGES = _LANG_REGISTRY.code_languages()def _now_iso() -> str:@@ -235,7 +216,10 @@ class PageGenerator:page_summaries: dict[str, str] | None = None,) -> GeneratedPage:ctx = self._assembler.assemble_module_page(- module_path, language, file_contexts, graph,+ module_path,+ language,+ file_contexts,+ graph,page_summaries=page_summaries,)module_git_summary = None@@ -295,7 +279,10 @@ class PageGenerator:graph_builder: Any | None = None,) -> GeneratedPage:ctx = self._assembler.assemble_repo_overview(- repo_structure, pagerank, sccs, community,+ repo_structure,+ pagerank,+ sccs,+ community,graph_builder=graph_builder,)repo_git_summary = None@@ -463,7 +450,11 @@ class PageGenerator:completed_ids: set[str] = set()job_id: str | None = Noneif job_system is not None:- repo_path_str = str(Path(repo_path).resolve()) if repo_path else str(getattr(repo_structure, "root_path", "."))+ repo_path_str = (+ str(Path(repo_path).resolve())+ if repo_path+ else str(getattr(repo_structure, "root_path", "."))+ )# On resume, query the vector store directly — it is the ground truthif resume and self._vector_store is not None:completed_ids = await self._vector_store.list_page_ids()@@ -709,9 +700,7 @@ class PageGenerator:scc_members: dict[int, list[str]] = {n: list(condensation.nodes[n]["members"]) for n in condensation.nodes}- topo_order = [- node for scc_id in topo_order_scc for node in scc_members[scc_id]- ]+ topo_order = [node for scc_id in topo_order_scc for node in scc_members[scc_id]]# Preserve priority ordering within the topo-sort by mapping paths to# their original priority index.@@ -843,7 +832,10 @@ class PageGenerator:(compute_page_id("repo_overview", repo_name),self.generate_repo_overview(- repo_structure, pagerank, sccs, community,+ repo_structure,+ pagerank,+ sccs,+ community,git_meta_map=git_meta_map,graph_builder=graph_builder,),@@ -1101,29 +1093,134 @@ def _is_significant_file(_BACKTICK_SKIP = frozenset({# Python builtins & keywords- "True", "False", "None", "self", "cls", "super",- "str", "int", "float", "bool", "list", "dict", "set", "tuple",- "bytes", "object", "type", "Any", "Optional", "Union",- "async", "await", "return", "yield", "import", "from",- "class", "def", "if", "else", "for", "while", "try", "except",- "raise", "with", "pass", "break", "continue", "lambda",- "in", "not", "and", "or", "is", "del", "assert", "finally",- "elif", "as", "global", "nonlocal",+ "True",+ "False",+ "None",+ "self",+ "cls",+ "super",+ "str",+ "int",+ "float",+ "bool",+ "list",+ "dict",+ "set",+ "tuple",+ "bytes",+ "object",+ "type",+ "Any",+ "Optional",+ "Union",+ "async",+ "await",+ "return",+ "yield",+ "import",+ "from",+ "class",+ "def",+ "if",+ "else",+ "for",+ "while",+ "try",+ "except",+ "raise",+ "with",+ "pass",+ "break",+ "continue",+ "lambda",+ "in",+ "not",+ "and",+ "or",+ "is",+ "del",+ "assert",+ "finally",+ "elif",+ "as",+ "global",+ "nonlocal",# JS/TS keywords- "null", "undefined", "this", "const", "let", "var", "function",- "export", "default", "extends", "implements", "interface",- "enum", "new", "typeof", "instanceof", "void", "never",- "string", "number", "boolean", "symbol", "bigint", "unknown",- "readonly", "abstract", "static", "private", "protected", "public",- "require", "module", "exports", "Promise", "Map", "Set", "Array",- "Object", "Error", "Date", "RegExp", "JSON", "Math", "console",+ "null",+ "undefined",+ "this",+ "const",+ "let",+ "var",+ "function",+ "export",+ "default",+ "extends",+ "implements",+ "interface",+ "enum",+ "new",+ "typeof",+ "instanceof",+ "void",+ "never",+ "string",+ "number",+ "boolean",+ "symbol",+ "bigint",+ "unknown",+ "readonly",+ "abstract",+ "static",+ "private",+ "protected",+ "public",+ "require",+ "module",+ "exports",+ "Promise",+ "Map",+ "Set",+ "Array",+ "Object",+ "Error",+ "Date",+ "RegExp",+ "JSON",+ "Math",+ "console",# Common tool/ecosystem names- "pip", "npm", "npx", "yarn", "pnpm", "go", "rust", "python",- "node", "cargo", "uv", "git", "docker", "make",+ "pip",+ "npm",+ "npx",+ "yarn",+ "pnpm",+ "go",+ "rust",+ "python",+ "node",+ "cargo",+ "uv",+ "git",+ "docker",+ "make",# Common framework/lib names the LLM mentions in prose- "FastAPI", "React", "Next", "Express", "Django", "Flask",- "SQLAlchemy", "Pydantic", "Click", "Typer", "pytest",- "asyncio", "pathlib", "dataclass", "dataclasses",+ "FastAPI",+ "React",+ "Next",+ "Express",+ "Django",+ "Flask",+ "SQLAlchemy",+ "Pydantic",+ "Click",+ "Typer",+ "pytest",+ "asyncio",+ "pathlib",+ "dataclass",+ "dataclasses",})@@ -1133,9 +1230,9 @@ _BACKTICK_REF_RE = re.compile(r"(?<!`)` *([A-Za-z_]\w*(?:\.\w+)*) *`(?!`)")# Patterns that indicate the backtick content is a path, command, or# value rather than a symbol reference — these should never be flagged._PATH_OR_CMD_RE = re.compile(- r"[/\\]" # contains path separator+ r"[/\\]" # contains path separatorr"|\.(?:py|ts|js|json|yaml|yml|toml|md|sh|sql|css|html)$" # file extension- r"|^[a-z][\w-]*$" # all-lowercase with hyphens = CLI command/flag+ r"|^[a-z][\w-]*$" # all-lowercase with hyphens = CLI command/flag)diff --git a/packages/core/src/repowise/core/ingestion/call_resolver.py b/packages/core/src/repowise/core/ingestion/call_resolver.pyindex 32d9a9388..7417168f8 100644--- a/packages/core/src/repowise/core/ingestion/call_resolver.py+++ b/packages/core/src/repowise/core/ingestion/call_resolver.py@@ -32,9 +32,7 @@ from .models import CallSite, NamedBinding, ParsedFilelog = structlog.get_logger(__name__)-def _file_language(- parsed_files: dict[str, ParsedFile], symbol_id: str-) -> str | None:+def _file_language(parsed_files: dict[str, ParsedFile], symbol_id: str) -> str | None:"""Extract language from a symbol ID's file via the parsed files map."""file_path = symbol_id.split("::")[0] if "::" in symbol_id else symbol_idparsed = parsed_files.get(file_path)@@ -159,9 +157,14 @@ class CallResolver:for call in calls:if not call.caller_symbol_id:- # Calls at module level (outside any function) — skip for now- # as they don't have a clear caller node- continue+ # Module-level call — assign to synthetic __module__ symbol+ call = CallSite(+ target_name=call.target_name,+ receiver_name=call.receiver_name,+ caller_symbol_id=f"{file_path}::__module__",+ line=call.line,+ argument_count=call.argument_count,+ )resolved = self._resolve_one(file_path, call)if resolved:diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/base.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/base.pyindex 25f2541d4..53efa9c5f 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/base.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/base.py@@ -7,9 +7,9 @@ from pathlib import Path@dataclassclass DynamicEdge:- source: str # repo-relative path- target: str # repo-relative path- edge_type: str # "dynamic_uses" | "dynamic_imports" | "url_route"+ source: str # repo-relative path+ target: str # repo-relative path+ edge_type: str # "dynamic_uses" | "dynamic_imports" | "url_route"hint_source: str # extractor nameweight: float = 1.0diff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/django.pyindex 6d1e4a4be..0bce49da0 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/django.py@@ -95,35 +95,41 @@ class DjangoDynamicHints(DynamicHintExtractor):for app in _extract_string_list(node.value):resolved = _app_to_path(app, repo_root)if resolved:- edges.append(DynamicEdge(- source=rel_settings,- target=resolved,- edge_type="dynamic_imports",- hint_source=self.name,- ))+ edges.append(+ DynamicEdge(+ source=rel_settings,+ target=resolved,+ edge_type="dynamic_imports",+ hint_source=self.name,+ )+ )elif name == "ROOT_URLCONF":module = _extract_string_value(node.value)if module:resolved = _module_to_path(module, repo_root)if resolved:- edges.append(DynamicEdge(- source=rel_settings,- target=resolved,- edge_type="dynamic_imports",- hint_source=self.name,- ))+ edges.append(+ DynamicEdge(+ source=rel_settings,+ target=resolved,+ edge_type="dynamic_imports",+ hint_source=self.name,+ )+ )elif name == "MIDDLEWARE":for middleware in _extract_string_list(node.value):resolved = _module_to_path(middleware, repo_root)if resolved:- edges.append(DynamicEdge(- source=rel_settings,- target=resolved,- edge_type="dynamic_imports",- hint_source=self.name,- ))+ edges.append(+ DynamicEdge(+ source=rel_settings,+ target=resolved,+ edge_type="dynamic_imports",+ hint_source=self.name,+ )+ )return edges@@ -142,11 +148,13 @@ class DjangoDynamicHints(DynamicHintExtractor):module = match.group(1)resolved = _module_to_path(module, repo_root)if resolved:- edges.append(DynamicEdge(- source=rel_urls,- target=resolved,- edge_type="url_route",- hint_source=self.name,- ))+ edges.append(+ DynamicEdge(+ source=rel_urls,+ target=resolved,+ edge_type="url_route",+ hint_source=self.name,+ )+ )return edgesdiff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/node.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/node.pyindex 62e6e1103..1895d1b16 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/node.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/node.py@@ -76,12 +76,14 @@ class NodeDynamicHints(DynamicHintExtractor):except ValueError:continueif resolved.exists():- edges.append(DynamicEdge(- source=rel_pkg,- target=rel_resolved,- edge_type="dynamic_imports",- hint_source=self.name,- ))+ edges.append(+ DynamicEdge(+ source=rel_pkg,+ target=rel_resolved,+ edge_type="dynamic_imports",+ hint_source=self.name,+ )+ )return edges@@ -126,11 +128,13 @@ class NodeDynamicHints(DynamicHintExtractor):except ValueError:continueif resolved.exists():- edges.append(DynamicEdge(- source=rel_tsconfig,- target=rel_resolved,- edge_type="dynamic_imports",- hint_source=self.name,- ))+ edges.append(+ DynamicEdge(+ source=rel_tsconfig,+ target=rel_resolved,+ edge_type="dynamic_imports",+ hint_source=self.name,+ )+ )return edgesdiff --git a/packages/core/src/repowise/core/ingestion/dynamic_hints/pytest_hints.py b/packages/core/src/repowise/core/ingestion/dynamic_hints/pytest_hints.pyindex 4585fcd5b..d13da185a 100644--- a/packages/core/src/repowise/core/ingestion/dynamic_hints/pytest_hints.py+++ b/packages/core/src/repowise/core/ingestion/dynamic_hints/pytest_hints.py@@ -93,11 +93,13 @@ class PytestDynamicHints(DynamicHintExtractor):test_params = _get_test_function_params(test_tree)if test_params & fixture_names:seen_targets.add(rel_test)- edges.append(DynamicEdge(- source=rel_conftest,- target=rel_test,- edge_type="dynamic_uses",- hint_source=self.name,- ))+ edges.append(+ DynamicEdge(+ source=rel_conftest,+ target=rel_test,+ edge_type="dynamic_uses",+ hint_source=self.name,+ )+ )return edgesdiff --git a/packages/core/src/repowise/core/ingestion/extractors/__init__.py b/packages/core/src/repowise/core/ingestion/extractors/__init__.pynew file mode 100644index 000000000..17cfd2166--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/__init__.py@@ -0,0 +1,22 @@+"""Per-language extractor modules — bindings, heritage, docstrings, signatures, visibility."""++from .bindings import extract_import_bindings+from .docstrings import extract_module_docstring, extract_symbol_docstring+from .helpers import extract_go_receiver_type, node_text, refine_go_type_kind, refine_kotlin_class_kind+from .heritage import HERITAGE_EXTRACTORS, extract_heritage+from .signatures import build_signature+from .visibility import VISIBILITY_FNS++__all__ = [+ "HERITAGE_EXTRACTORS",+ "VISIBILITY_FNS",+ "build_signature",+ "extract_go_receiver_type",+ "extract_heritage",+ "extract_import_bindings",+ "extract_module_docstring",+ "extract_symbol_docstring",+ "node_text",+ "refine_go_type_kind",+ "refine_kotlin_class_kind",+]diff --git a/packages/core/src/repowise/core/ingestion/extractors/bindings.py b/packages/core/src/repowise/core/ingestion/extractors/bindings.pynew file mode 100644index 000000000..eb879f025--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/bindings.py@@ -0,0 +1,467 @@+"""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."""+ alias = None+ namespace = ""+ for child in stmt_node.children:+ if child.type == "name_equals":+ # using Alias = Full.Namespace;+ for sub in child.children:+ if sub.type == "identifier":+ alias = node_text(sub, src)+ elif child.type in ("qualified_name", "identifier"):+ namespace = node_text(child, src)+ 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)]+++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/docstrings.py b/packages/core/src/repowise/core/ingestion/extractors/docstrings.pynew file mode 100644index 000000000..7ebd74f25--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/docstrings.py@@ -0,0 +1,254 @@+"""Module-level and symbol-level docstring extraction."""++from __future__ import annotations++from tree_sitter import Node++from .helpers import (+ clean_jsdoc,+ clean_string_literal,+ find_preceding_block_comment,+ find_preceding_jsdoc,+ node_text,+)+++def extract_module_docstring(root: Node, src: str, lang: str) -> str | None:+ """Extract a module/file-level docstring or leading comment."""+ if lang == "python":+ for child in root.children:+ if child.type == "expression_statement":+ for sub in child.children:+ if sub.type == "string":+ return clean_string_literal(node_text(sub, src))+ break+ elif child.type not in (+ "comment",+ "newline",+ "import_statement",+ "import_from_statement",+ "future_import_statement",+ ):+ break+ elif lang in ("typescript", "javascript"):+ # Look for leading /** ... */ comment+ for child in root.children:+ if child.type == "comment":+ text = node_text(child, src).strip()+ if text.startswith("/**"):+ return clean_jsdoc(text)+ elif child.type not in ("comment",):+ break+ elif lang == "go":+ # Package comment is a series of // lines before package_clause+ lines: list[str] = []+ for child in root.children:+ if child.type == "comment":+ lines.append(node_text(child, src).lstrip("/ ").strip())+ elif child.type == "package_clause":+ break+ return "\n".join(lines) if lines else None+ elif lang == "rust":+ # //! inner doc comments or /// outer doc comments at top+ for child in root.children:+ if child.type in ("line_comment", "block_comment"):+ text = node_text(child, src).strip()+ if text.startswith("//!") or text.startswith("/*!"):+ return text.lstrip("/!* ").strip()+ else:+ break+ elif lang in ("cpp", "c"):+ # Doxygen: first /** ... */ block comment before any declaration+ for child in root.children:+ if child.type in ("comment", "block_comment"):+ text = node_text(child, src).strip()+ if text.startswith("/**"):+ return clean_jsdoc(text)+ elif child.type not in (+ "comment",+ "preproc_include",+ "preproc_ifdef",+ "preproc_ifndef",+ ):+ break+ elif lang == "kotlin":+ for child in root.children:+ if child.type in ("comment", "multiline_comment"):+ text = node_text(child, src).strip()+ if text.startswith("/**"):+ return clean_jsdoc(text)+ elif child.type not in ("comment", "package_header", "import"):+ break+ elif lang == "ruby":+ lines: list[str] = []+ for child in root.children:+ if child.type == "comment":+ lines.append(node_text(child, src).lstrip("# ").strip())+ else:+ break+ return "\n".join(lines) if lines else None++ elif lang == "csharp":+ for child in root.children:+ if child.type == "comment":+ text = node_text(child, src).strip()+ if text.startswith("/**"):+ return clean_jsdoc(text)+ elif child.type not in ("comment", "using_directive"):+ break++ elif lang == "swift":+ for child in root.children:+ if child.type == "comment":+ text = node_text(child, src).strip()+ if text.startswith("/**"):+ return clean_jsdoc(text)+ elif text.startswith("///"):+ return text.lstrip("/ ").strip()+ elif child.type not in ("comment", "import_declaration"):+ break++ elif lang == "scala":+ for child in root.children:+ if child.type == "comment":+ text = node_text(child, src).strip()+ if text.startswith("/**"):+ return clean_jsdoc(text)+ elif child.type not in ("comment", "import_declaration"):+ break++ elif lang == "php":+ for child in root.children:+ if child.type == "comment":+ text = node_text(child, src).strip()+ if text.startswith("/**"):+ return clean_jsdoc(text)+ elif child.type not in (+ "comment",+ "php_tag",+ "namespace_definition",+ "namespace_use_declaration",+ ):+ break++ return None+++def extract_symbol_docstring(def_node: Node, src: str, lang: str) -> str | None:+ """Extract the docstring from a symbol's body node."""+ if lang == "python":+ body = def_node.child_by_field_name("body")+ if body is None:+ return None+ for child in body.children:+ if child.type == "expression_statement":+ for sub in child.children:+ if sub.type == "string":+ return clean_string_literal(node_text(sub, src))+ return None+ elif child.type not in ("comment", "newline"):+ return None+ return None++ elif lang in ("typescript", "javascript"):+ return find_preceding_jsdoc(def_node, src)++ elif lang == "go":+ # Leading // comment lines before the function+ 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":+ lines.insert(0, node_text(siblings[i], src).lstrip("/ ").strip())+ i -= 1+ return "\n".join(lines) if lines else None++ elif lang == "rust":+ # /// doc comments before the item+ 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 in ("line_comment", "block_comment"):+ text = node_text(siblings[i], src).strip()+ if text.startswith("///"):+ lines.insert(0, text.lstrip("/ ").strip())+ i -= 1+ else:+ break+ return "\n".join(lines) if lines else None++ elif lang == "java":+ # /** Javadoc */ comment before the method/class+ return find_preceding_block_comment(def_node, src, "/**")++ elif lang in ("cpp", "c"):+ # Doxygen: /** ... */ block comment or /// line comments+ result = find_preceding_block_comment(def_node, src, "/**")+ if result:+ return result+ return _find_preceding_line_doc_comments(def_node, src, "///")++ elif lang == "kotlin":+ # KDoc: /** ... */ block comment before declaration+ return find_preceding_block_comment(def_node, src, "/**")++ elif lang == "ruby":+ # RDoc/YARD: # comment lines before method/class+ return _find_preceding_line_doc_comments(def_node, src, "#")++ elif lang == "csharp":+ # XML doc comments: /// lines or /** block+ result = find_preceding_block_comment(def_node, src, "/**")+ if result:+ return result+ return _find_preceding_line_doc_comments(def_node, src, "///")++ elif lang == "swift":+ # Swift doc: /** block or /// lines+ result = find_preceding_block_comment(def_node, src, "/**")+ if result:+ return result+ return _find_preceding_line_doc_comments(def_node, src, "///")++ elif lang == "scala":+ # ScalaDoc: /** ... */+ return find_preceding_block_comment(def_node, src, "/**")++ elif lang == "php":+ # PHPDoc: /** ... */+ return find_preceding_block_comment(def_node, src, "/**")++ return None+++def _find_preceding_line_doc_comments(node: Node, src: str, prefix: str) -> str | None:+ """Collect consecutive line comments with *prefix* (e.g. ``///``) before *node*."""+ parent = node.parent+ if parent is None:+ return None+ siblings = list(parent.children)+ idx = next((i for i, s in enumerate(siblings) if s.id == node.id), -1)+ if idx <= 0:+ return None+ lines: list[str] = []+ i = idx - 1+ while i >= 0 and siblings[i].type in ("comment", "line_comment"):+ text = node_text(siblings[i], src).strip()+ if text.startswith(prefix):+ lines.insert(0, text[len(prefix) :].strip())+ i -= 1+ else:+ break+ return "\n".join(lines) if lines else Nonediff --git a/packages/core/src/repowise/core/ingestion/extractors/helpers.py b/packages/core/src/repowise/core/ingestion/extractors/helpers.pynew file mode 100644index 000000000..e59b3edcd--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/helpers.py@@ -0,0 +1,110 @@+"""Shared AST helpers used by extractor modules."""++from __future__ import annotations++from tree_sitter import Node+++def node_text(node: Node | None, src: str) -> str:+ """Return the text of a tree-sitter *node*, or ``""`` if *node* is None."""+ if node is None:+ return ""+ if node.text is not None:+ return node.text.decode("utf-8", errors="replace")+ return src[node.start_byte : node.end_byte]+++def extract_go_receiver_type(receiver_text: str) -> str | None:+ """Extract 'Calculator' from '(c *Calculator)' or '(c Calculator)'."""+ text = receiver_text.strip("() ")+ parts = text.split()+ for part in reversed(parts):+ clean = part.lstrip("*")+ if clean and clean[0].isupper():+ return clean+ return None+++def refine_go_type_kind(type_spec_node: Node, src: str) -> str:+ """Refine the generic 'struct' kind for Go type_spec nodes."""+ type_node = type_spec_node.child_by_field_name("type")+ if type_node is None:+ return "struct"+ type_text = node_text(type_node, src).strip()+ if type_text.startswith("struct"):+ return "struct"+ if type_text.startswith("interface"):+ return "interface"+ return "type_alias"+++def refine_kotlin_class_kind(class_node: Node) -> str:+ """Refine 'class' kind for Kotlin class_declaration nodes.++ In tree-sitter-kotlin v1.x, interfaces and enum classes all use+ ``class_declaration`` — the keyword child (``class``, ``interface``,+ ``enum``) distinguishes them.+ """+ for child in class_node.children:+ if child.type == "interface":+ return "interface"+ if child.type == "enum":+ return "enum"+ return "class"+++def clean_string_literal(text: str) -> str:+ """Strip quote characters from a Python string literal."""+ text = text.strip()+ for triple in ('"""', "'''"):+ if text.startswith(triple) and text.endswith(triple) and len(text) >= 6:+ return text[3:-3].strip()+ for q in ('"', "'"):+ if text.startswith(q) and text.endswith(q) and len(text) >= 2:+ return text[1:-1].strip()+ return text+++def find_preceding_jsdoc(node: Node, src: str) -> str | None:+ """Return the JSDoc comment immediately before *node*, if any."""+ parent = node.parent+ if parent is None:+ return None+ siblings = list(parent.children)+ idx = next((i for i, s in enumerate(siblings) if s.id == node.id), -1)+ if idx <= 0:+ return None+ prev = siblings[idx - 1]+ if prev.type == "comment":+ text = node_text(prev, src).strip()+ if text.startswith("/**"):+ return clean_jsdoc(text)+ return None+++def find_preceding_block_comment(node: Node, src: str, prefix: str) -> str | None:+ """Return the block comment immediately before *node* that starts with *prefix*."""+ parent = node.parent+ if parent is None:+ return None+ siblings = list(parent.children)+ idx = next((i for i, s in enumerate(siblings) if s.id == node.id), -1)+ if idx <= 0:+ return None+ prev = siblings[idx - 1]+ if prev.type in ("block_comment", "comment"):+ text = node_text(prev, src).strip()+ if text.startswith(prefix):+ return clean_jsdoc(text)+ return None+++def clean_jsdoc(text: str) -> str:+ """Strip JSDoc / block-comment delimiters and leading asterisks."""+ lines = text.splitlines()+ cleaned: list[str] = []+ for line in lines:+ line = line.strip().lstrip("/*").lstrip()+ if line:+ cleaned.append(line)+ return "\n".join(cleaned).strip()diff --git a/packages/core/src/repowise/core/ingestion/extractors/heritage.py b/packages/core/src/repowise/core/ingestion/extractors/heritage.pynew file mode 100644index 000000000..a18fca152--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/heritage.py@@ -0,0 +1,588 @@+"""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."""+ for child in def_node.children:+ if child.type == "base_list":+ for base in child.children:+ if base.type in (":", ","):+ continue+ text = node_text(base, src).strip()+ bare = text.split(".")[-1].split("<")[0].strip()+ if bare and bare != name:+ kind = (+ "implements"+ if bare.startswith("I") and len(bare) > 1 and bare[1].isupper()+ else "extends"+ )+ 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/signatures.py b/packages/core/src/repowise/core/ingestion/extractors/signatures.pynew file mode 100644index 000000000..6f2c542af--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/signatures.py@@ -0,0 +1,62 @@+"""Signature building for parsed symbols."""++from __future__ import annotations++from tree_sitter import Node++from .helpers import node_text+++def build_signature(node_type: str, name: str, params_text: str, def_node: Node, src: str) -> str:+ """Build a human-readable signature string."""++ # Helper: try multiple field names for "return type", fall back gracefully.+ def _ret(fields: tuple[str, ...]) -> str:+ for f in fields:+ n = def_node.child_by_field_name(f)+ if n is not None:+ return f" -> {node_text(n, src)}"+ return ""++ if node_type == "function_definition":+ # Detect async via child "async" keyword (tree-sitter-python >= 0.23)+ prefix = "async " if any(c.type == "async" for c in def_node.children) else ""+ return f"{prefix}def {name}{params_text}{_ret(('return_type',))}"+ if node_type == "function_item":+ # Rust: return_type field+ return f"fn {name}{params_text}{_ret(('return_type',))}"+ if node_type in ("function_declaration", "generator_function_declaration"):+ # TS/JS use return_type; Go uses result+ return f"function {name}{params_text}{_ret(('return_type', 'result'))}"+ if node_type in ("class_definition", "class_declaration", "abstract_class_declaration"):+ base = f"class {name}"+ if params_text:+ base += params_text+ return base+ if node_type == "interface_declaration":+ return f"interface {name}"+ if node_type == "type_alias_declaration":+ return f"type {name}"+ if node_type == "enum_declaration":+ return f"enum {name}"+ if node_type == "method_definition":+ # TypeScript/JavaScript class method+ return f"{name}{params_text}{_ret(('return_type',))}"+ if node_type == "method_declaration":+ # Go method: include receiver text and result type+ recv_node = def_node.child_by_field_name("receiver")+ recv_text = node_text(recv_node, src) if recv_node else ""+ recv_prefix = f"{recv_text} " if recv_text else ""+ return f"func {recv_prefix}{name}{params_text}{_ret(('result',))}"+ if node_type in ("struct_item", "struct_specifier"):+ return f"struct {name}"+ if node_type in ("enum_item", "enum_specifier"):+ return f"enum {name}"+ if node_type == "trait_item":+ return f"trait {name}"+ if node_type == "impl_item":+ return f"impl {name}"+ if node_type in ("class_specifier",):+ return f"class {name}"+ # Fallback+ return f"{name}{params_text}"diff --git a/packages/core/src/repowise/core/ingestion/extractors/visibility.py b/packages/core/src/repowise/core/ingestion/extractors/visibility.pynew file mode 100644index 000000000..661835af6--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/extractors/visibility.py@@ -0,0 +1,116 @@+"""Per-language visibility determination functions."""++from __future__ import annotations++from collections.abc import Callable+++def py_visibility(name: str, _mods: list[str]) -> str:+ if name.startswith("__") and name.endswith("__"):+ return "public" # dunder+ if name.startswith("_"):+ return "private"+ return "public"+++def ts_visibility(_name: str, mods: list[str]) -> str:+ mods_lower = [m.lower() for m in mods]+ if "private" in mods_lower:+ return "private"+ if "protected" in mods_lower:+ return "protected"+ return "public"+++def go_visibility(name: str, _mods: list[str]) -> str:+ return "public" if name and name[0].isupper() else "private"+++def rust_visibility(_name: str, mods: list[str]) -> str:+ return "public" if any("pub" in m for m in mods) else "private"+++def java_visibility(_name: str, mods: list[str]) -> str:+ combined = " ".join(mods).lower()+ if "private" in combined:+ return "private"+ if "protected" in combined:+ return "protected"+ return "public"+++def public_by_default(_name: str, _mods: list[str]) -> str:+ return "public"+++def kotlin_visibility(_name: str, modifier_texts: list[str]) -> str:+ combined = " ".join(modifier_texts).lower()+ if "private" in combined:+ return "private"+ if "protected" in combined:+ return "protected"+ if "internal" in combined:+ return "internal"+ return "public"+++def csharp_visibility(_name: str, modifier_texts: list[str]) -> str:+ """C# visibility — public/private/protected/internal, default internal."""+ combined = " ".join(modifier_texts).lower()+ if "private" in combined:+ return "private"+ if "protected" in combined:+ return "protected"+ if "internal" in combined:+ return "internal"+ if "public" in combined:+ return "public"+ return "internal" # C# default is internal+++def swift_visibility(_name: str, modifier_texts: list[str]) -> str:+ """Swift visibility — public/private/fileprivate/internal/open."""+ combined = " ".join(modifier_texts).lower()+ if "private" in combined or "fileprivate" in combined:+ return "private"+ if "public" in combined or "open" in combined:+ return "public"+ return "internal" # Swift default is internal+++def scala_visibility(_name: str, modifier_texts: list[str]) -> str:+ """Scala visibility — public/private/protected, default public."""+ combined = " ".join(modifier_texts).lower()+ if "private" in combined:+ return "private"+ if "protected" in combined:+ return "protected"+ return "public"+++def php_visibility(_name: str, modifier_texts: list[str]) -> str:+ """PHP visibility — public/private/protected, default public."""+ combined = " ".join(modifier_texts).lower()+ if "private" in combined:+ return "private"+ if "protected" in combined:+ return "protected"+ return "public"+++VISIBILITY_FNS: dict[str, Callable[[str, list[str]], str]] = {+ "python": py_visibility,+ "typescript": ts_visibility,+ "javascript": public_by_default,+ "go": go_visibility,+ "rust": rust_visibility,+ "java": java_visibility,+ "cpp": public_by_default,+ "c": public_by_default,+ "kotlin": kotlin_visibility,+ "ruby": public_by_default,+ "csharp": csharp_visibility,+ "swift": swift_visibility,+ "scala": scala_visibility,+ "php": php_visibility,+}diff --git a/packages/core/src/repowise/core/ingestion/framework_edges.py b/packages/core/src/repowise/core/ingestion/framework_edges.pynew file mode 100644index 000000000..65894a97d--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/framework_edges.py@@ -0,0 +1,192 @@+"""Framework-aware synthetic edge detection.++Extracted from ``graph.py`` — detects Django, FastAPI, Flask, and pytest+convention-based relationships and adds ``edge_type="framework"`` edges.+"""++from __future__ import annotations++import re+from pathlib import Path+from typing import TYPE_CHECKING, Any++from .resolvers import ResolverContext, resolve_import++if TYPE_CHECKING:+ import networkx as nx++ from .models import ParsedFile+++def add_framework_edges(+ graph: nx.DiGraph,+ parsed_files: dict[str, ParsedFile],+ ctx: ResolverContext,+ tech_stack: list[str] | None = None,+) -> int:+ """Add synthetic edges for framework-mediated relationships.++ Returns the number of edges added.+ """+ count = 0+ path_set = set(parsed_files.keys())++ # Always run: pytest conftest detection+ count += _add_conftest_edges(graph, path_set)++ stack_lower = {s.lower() for s in (tech_stack or [])}++ if "django" in stack_lower:+ count += _add_django_edges(graph, path_set)+ if "fastapi" in stack_lower or "starlette" in stack_lower:+ count += _add_fastapi_edges(graph, parsed_files, ctx, path_set)+ if "flask" in stack_lower:+ count += _add_flask_edges(graph, parsed_files, ctx, path_set)++ return count+++def _add_edge_if_new(graph: nx.DiGraph, source: str, target: str) -> bool:+ """Add a framework edge if no edge already exists. Returns True if added."""+ if source == target:+ return False+ if graph.has_edge(source, target):+ return False+ graph.add_edge(source, target, edge_type="framework", imported_names=[])+ return True+++def _add_conftest_edges(graph: nx.DiGraph, path_set: set[str]) -> int:+ """conftest.py -> test files in the same or child directories."""+ count = 0+ conftest_paths = [p for p in path_set if Path(p).name == "conftest.py"]++ for conf in conftest_paths:+ conf_dir = Path(conf).parent.as_posix()+ prefix = f"{conf_dir}/" if conf_dir != "." else ""+ for p in path_set:+ if p == conf:+ continue+ node = graph.nodes.get(p, {})+ if not node.get("is_test", False):+ continue+ if (p.startswith(prefix) or (prefix == "" and "/" not in p)) and _add_edge_if_new(+ graph, p, conf+ ):+ count += 1+ return count+++def _add_django_edges(graph: nx.DiGraph, path_set: set[str]) -> int:+ """Django conventions: admin->models, urls->views in the same directory."""+ count = 0+ by_dir: dict[str, dict[str, str]] = {}+ for p in path_set:+ pp = Path(p)+ d = pp.parent.as_posix()+ by_dir.setdefault(d, {})[pp.stem] = p++ for _d, stems in by_dir.items():+ if (+ "admin" in stems+ and "models" in stems+ and _add_edge_if_new(graph, stems["admin"], stems["models"])+ ):+ count += 1+ if (+ "urls" in stems+ and "views" in stems+ and _add_edge_if_new(graph, stems["urls"], stems["views"])+ ):+ count += 1+ if (+ "forms" in stems+ and "models" in stems+ and _add_edge_if_new(graph, stems["forms"], stems["models"])+ ):+ count += 1+ if (+ "serializers" in stems+ and "models" in stems+ and _add_edge_if_new(graph, stems["serializers"], stems["models"])+ ):+ count += 1+ return count+++def _add_fastapi_edges(+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+) -> int:+ """Detect include_router() calls and link app files to router modules."""+ count = 0+ var_to_file: dict[str, str] = {}++ for path, parsed in parsed_files.items():+ for imp in parsed.imports:+ for name in imp.imported_names:+ if name.lower().endswith("router") or name.lower().endswith("app"):+ resolved = resolve_import(+ imp.module_path,+ path,+ parsed.file_info.language,+ ctx,+ )+ if resolved and resolved in path_set:+ var_to_file[name] = resolved++ router_re = re.compile(r"(?:include_router|add_api_route)\s*\(\s*(\w+)")+ for path, parsed in parsed_files.items():+ if parsed.file_info.language != "python":+ continue+ try:+ source = Path(parsed.file_info.abs_path).read_text(errors="ignore")+ except Exception:+ continue+ for match in router_re.finditer(source):+ var_name = match.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+ return count+++def _add_flask_edges(+ graph: nx.DiGraph,+ parsed_files: dict[str, Any],+ ctx: ResolverContext,+ path_set: set[str],+) -> int:+ """Detect register_blueprint() calls and link app files to blueprint modules."""+ count = 0+ var_to_file: dict[str, str] = {}++ for path, parsed in parsed_files.items():+ for imp in parsed.imports:+ for name in imp.imported_names:+ if "blueprint" in name.lower() or name.lower().endswith("bp"):+ resolved = resolve_import(+ imp.module_path,+ path,+ parsed.file_info.language,+ ctx,+ )+ if resolved and resolved in path_set:+ var_to_file[name] = resolved++ bp_re = re.compile(r"register_blueprint\s*\(\s*(\w+)")+ for path, parsed in parsed_files.items():+ if parsed.file_info.language != "python":+ continue+ try:+ source = Path(parsed.file_info.abs_path).read_text(errors="ignore")+ except Exception:+ continue+ for match in bp_re.finditer(source):+ var_name = match.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+ return countdiff --git a/packages/core/src/repowise/core/ingestion/git_indexer.py b/packages/core/src/repowise/core/ingestion/git_indexer.pyindex b1875cb52..3c02a7b44 100644--- a/packages/core/src/repowise/core/ingestion/git_indexer.py+++ b/packages/core/src/repowise/core/ingestion/git_indexer.py@@ -24,6 +24,8 @@ from typing import Anyimport structlog+from .languages.registry import REGISTRY as _LANG_REGISTRY+logger = structlog.get_logger(__name__)# Silence GitPython's _CatFileContentStream.__del__ ValueError spam.@@ -112,85 +114,8 @@ _PR_NUMBER_RE = re.compile(r"(?:pull request |)\#(\d+)|\(#(\d+)\)|!(\d+)")# this set is skipped — data, config, markup, dotfiles, and binaries add no# documentation value, and git blame on large JSON/YAML files is very slow.# Co-change detection still runs across ALL tracked files regardless.-_CODE_EXTENSIONS: frozenset[str] = frozenset(- {- # Python- ".py",- ".pyi",- # JavaScript / TypeScript- ".ts",- ".tsx",- ".js",- ".jsx",- ".mjs",- ".cjs",- # Go- ".go",- # Rust- ".rs",- # JVM- ".java",- ".kt",- ".kts",- ".scala",- # C / C++- ".c",- ".h",- ".cpp",- ".cc",- ".cxx",- ".hpp",- ".hxx",- # C#- ".cs",- # Ruby- ".rb",- # PHP- ".php",- # Swift- ".swift",- # Objective-C- ".m",- ".mm",- # Elixir / Erlang- ".ex",- ".exs",- ".erl",- ".hrl",- # Lua- ".lua",- # R- ".r",- # Dart- ".dart",- # Zig- ".zig",- # Julia- ".jl",- # Clojure- ".clj",- ".cljs",- ".cljc",- # Elm- ".elm",- # Haskell- ".hs",- ".lhs",- # OCaml- ".ml",- ".mli",- # F#- ".fs",- ".fsi",- ".fsx",- # Crystal- ".cr",- # Nim- ".nim",- # D- ".d",- }-)+# Derived from the centralised LanguageRegistry — all code language extensions.+_CODE_EXTENSIONS: frozenset[str] = _LANG_REGISTRY.all_code_extensions()# Files larger than this skip git blame. blame is O(lines) and blocks the# executor thread — for large files the commit-based ownership estimate is@@ -603,7 +528,14 @@ class GitIndexer:if line.startswith("\x00"):parts = line.lstrip("\x00").split("\x1f")if len(parts) >= 6:- sha, an, ae, ct, parents, subj = parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]+ sha, an, ae, ct, parents, subj = (+ parts[0],+ parts[1],+ parts[2],+ parts[3],+ parts[4],+ parts[5],+ )try:ts = int(ct)except ValueError:@@ -634,7 +566,9 @@ class GitIndexer:if match_path in known_paths or match_path == file_path:try:current.added += int(numstat_parts[0]) if numstat_parts[0] != "-" else 0- current.deleted += int(numstat_parts[1]) if numstat_parts[1] != "-" else 0+ current.deleted += (+ int(numstat_parts[1]) if numstat_parts[1] != "-" else 0+ )except ValueError:passdiff --git a/packages/core/src/repowise/core/ingestion/graph.py b/packages/core/src/repowise/core/ingestion/graph.pyindex 5fd39bf46..0ae32526c 100644--- a/packages/core/src/repowise/core/ingestion/graph.py+++ b/packages/core/src/repowise/core/ingestion/graph.py@@ -26,7 +26,6 @@ After calling build(), graph metrics are available:from __future__ import annotationsimport json-import shlexfrom pathlib import Pathfrom typing import Any@@ -34,17 +33,14 @@ import networkx as nximport structlogfrom .models import ParsedFile+from .resolvers import ResolverContext, resolve_import+from .resolvers.go import read_go_module_pathlog = structlog.get_logger(__name__)_LARGE_REPO_THRESHOLD = 30_000 # nodes — above this, algorithms are expensive# Path segments that mark a file as low-value for stem-based import resolution.-# Files under these directories lose stem-collision tiebreaks against equivalents-# in the canonical source tree (e.g. a `flask.py` test fixture will never beat-# `src/flask/__init__.py` for the import-stem "flask"). The list is intentionally-# language-agnostic — it captures the universal convention that fixture, example,-# and script trees shadow rather than replace library code._LOW_VALUE_PATH_SEGMENTS = frozenset({"tests",@@ -73,32 +69,10 @@ def _stem_priority(path: str, stem: str) -> tuple[int, int, int, str]:"""Sort key for choosing among files that share an import stem.Lower tuples sort first; callers take ``candidates[0]`` as the resolution.- The ordering is deliberately language-agnostic so the same logic governs- Python, Go, C/C++, and the generic fallback in :meth:`_resolve_import`.-- Fields, in priority order:-- 1. **Parent-directory match.** A file whose parent directory equals the- stem is almost always the canonical home for that name across every- package layout we care about — ``src/flask/__init__.py`` for stem- ``flask``, ``pkg/foo/foo.go`` for stem ``foo``, ``include/json/json.h``- for stem ``json``. Strongest single signal we have.- 2. **Low-value path.** Files under fixture/example/script/doc trees lose- to equivalents in the source tree. This catches the failure mode- where a test fixture named identically to the package (e.g.- ``tests/.../<pkg>.py``) would otherwise win the stem-collision- tiebreak and inflate its PageRank by absorbing the entire library's- in-edges.- 3. **Path depth.** Canonical package roots live shallow; deep nesting- usually means a vendored copy or a sub-fixture.- 4. **Lexicographic path.** Deterministic tiebreak so resolution is- independent of dict iteration order — critical for reproducible- graphs across re-indexes and platforms."""path_obj = Path(path)parts = path_obj.partsif path_obj.name == "__init__.py":- # Registered under parent dir name — parent-matching by construction.parent_match = 0else:parent_dir = parts[-2].lower() if len(parts) >= 2 else ""@@ -124,9 +98,7 @@ class GraphBuilder:self._parsed_files: dict[str, ParsedFile] = {} # path → ParsedFileself._built = Falseself._repo_path: Path | None = Path(repo_path) if repo_path else None- self._compile_commands_cache: dict[str, dict] | None = Noneself._tsconfig_resolver: Any | None = None # TsconfigResolver (lazy import)- self._go_module_path: str | None = self._read_go_module_path()# Community / flow caches (invalidated on build)self._community_cache: dict[str, int] | None = None@@ -194,13 +166,23 @@ class GraphBuilder:edge_type="has_method",)- def build(self) -> nx.DiGraph:- """Resolve imports and calls, add edges. Returns the finalized graph.+ # --- Synthetic module-level symbol for top-level calls ---+ module_sym_id = f"{path}::__module__"+ self._graph.add_node(+ module_sym_id,+ node_type="symbol",+ kind="module",+ name="__module__",+ file_path=path,+ start_line=0,+ end_line=0,+ visibility="private",+ language=parsed.file_info.language,+ )+ self._graph.add_edge(path, module_sym_id, edge_type="defines")- Idempotent: can be called multiple times; re-resolves edges each time.- Preserves symbol nodes and structural edges (defines, has_method)- while rebuilding import and call edges.- """+ def build(self) -> nx.DiGraph:+ """Resolve imports and calls, add edges. Returns the finalized graph."""# Invalidate cached metricsself._community_cache = Noneself._symbol_community_cache = None@@ -219,15 +201,24 @@ class GraphBuilder:path_set = set(self._parsed_files.keys())stem_map = self._build_stem_map(path_set)+ # Construct resolver context+ 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),+ parsed_files=self._parsed_files,+ )+# --- Phase 1: Resolve file-level imports ---import_targets: dict[str, set[str]] = {} # file → set of imported filesfor path, parsed in self._parsed_files.items():file_imports: set[str] = set()for imp in parsed.imports:- target = self._resolve_import(- imp.module_path, path, path_set, stem_map, parsed.file_info.language- )+ target = resolve_import(imp.module_path, path, parsed.file_info.language, ctx)if target:imp.resolved_file = targetfile_imports.add(target)@@ -317,9 +308,7 @@ class GraphBuilder:resolved = resolver.resolve_file(path, parsed.calls)for rc in resolved:- # Only add edge if both nodes exist in graphif rc.caller_id in self._graph and rc.callee_id in self._graph:- # Avoid duplicate call edges between same pairif not self._graph.has_edge(rc.caller_id, rc.callee_id):self._graph.add_edge(rc.caller_id,@@ -329,7 +318,6 @@ class GraphBuilder:)total_resolved += 1else:- # Update confidence if this resolution is higherexisting = self._graph[rc.caller_id][rc.callee_id]if rc.confidence > existing.get("confidence", 0):existing["confidence"] = rc.confidence@@ -347,18 +335,11 @@ class GraphBuilder:# ------------------------------------------------------------------def strongly_connected_components(self) -> list[frozenset[str]]:- """Return SCCs as a list of frozensets. SCCs of size > 1 are circular deps.-- Operates on the file-level subgraph only.- """+ """Return SCCs as a list of frozensets."""return [frozenset(scc) for scc in nx.strongly_connected_components(self.file_subgraph())]def betweenness_centrality(self) -> dict[str, float]:- """Return betweenness centrality for file nodes. High value → bridge file.-- Approximated with k=min(500, n) samples for large graphs.- Operates on the file-level subgraph only.- """+ """Return betweenness centrality for file nodes."""g = self.file_subgraph()n = g.number_of_nodes()if n == 0:@@ -369,12 +350,7 @@ class GraphBuilder:return nx.betweenness_centrality(g, normalized=True)def community_detection(self) -> dict[str, int]:- """Assign a community ID to each file node.-- Uses Leiden (graspologic) when available, falls back to Louvain.- Results are cached until the next ``build()`` call.- Returns dict[path, community_id].- """+ """Assign a community ID to each file node."""if self._community_cache is not None:return self._community_cache@@ -388,8 +364,7 @@ class GraphBuilder:except Exception as exc:log.warning("community_detection_failed", error=str(exc))file_nodes = [- n for n, d in self._graph.nodes(data=True)- if d.get("node_type", "file") == "file"+ n for n, d in self._graph.nodes(data=True) if d.get("node_type", "file") == "file"]self._community_cache = {n: 0 for n in file_nodes}self._community_info_cache = {}@@ -397,10 +372,7 @@ class GraphBuilder:return self._community_cachedef symbol_communities(self) -> dict[str, int]:- """Assign a community ID to each symbol node using call/heritage edges.-- Returns dict[symbol_id, community_id]. Cached until next ``build()``.- """+ """Assign a community ID to each symbol node using call/heritage edges."""if self._symbol_community_cache is not None:return self._symbol_community_cache@@ -414,38 +386,24 @@ class GraphBuilder:return self._symbol_community_cachedef community_info(self) -> dict[int, Any]:- """Return metadata for each file-level community.-- Returns dict[community_id, CommunityInfo]. Populates cache via- ``community_detection()`` if not yet computed.- """+ """Return metadata for each file-level community."""if self._community_info_cache is None:self.community_detection()return self._community_info_cache or {}def execution_flows(self, config: Any | None = None) -> Any:- """Trace execution flows from entry-point symbols.-- Returns an ``ExecutionFlowReport``. Requires symbol nodes and call- edges to be present in the graph.- """+ """Trace execution flows from entry-point symbols."""from repowise.core.analysis.execution_flows import (ExecutionFlowReport,trace_execution_flows,)- # Build a merged community map that covers both file paths and- # symbol IDs, so crosses_community detection works correctly.- # community_detection() returns {file_path: cid} but traces- # contain symbol IDs like "path::Name".file_cd = self.community_detection()merged_cd: dict[str, int] = dict(file_cd)- # Add symbol-level communitiessym_cd = self.symbol_communities()merged_cd.update(sym_cd)- # For symbols missing from both maps, inherit from their filefor node_id in self._graph.nodes():if node_id not in merged_cd and "::" in node_id:file_path = node_id.split("::")[0]@@ -457,7 +415,9 @@ class GraphBuilder:except Exception as exc:log.warning("execution_flow_tracing_failed", error=str(exc))return ExecutionFlowReport(- total_entry_points_scored=0, total_flows=0, flows=[],+ total_entry_points_scored=0,+ total_flows=0,+ flows=[],)# ------------------------------------------------------------------@@ -469,10 +429,7 @@ class GraphBuilder:return nx.node_link_data(self.graph())async def persist(self, db_path: Path, repo_id: str) -> None:- """Persist the graph to an SQLite database (lightweight Phase-2 schema).-- Phase 4 will replace this with the full SQLAlchemy/Alembic schema.- """+ """Persist the graph to an SQLite database."""import aiosqlitepr = self.pagerank()@@ -502,7 +459,6 @@ class GraphBuilder:);""")- # Nodesnode_rows = [(repo_id,@@ -521,7 +477,6 @@ class GraphBuilder:node_rows,)- # Edgesedge_rows = [(repo_id,@@ -549,121 +504,14 @@ class GraphBuilder:# Internal helpers# ------------------------------------------------------------------- def _load_compile_commands(self) -> dict[str, dict] | None:- """Load and cache compile_commands.json if present in the repo.-- Returns dict[source_file_relpath] → command entry, or None if not found.- """- if self._compile_commands_cache is not None:- return self._compile_commands_cache- if not self._repo_path:- return None- for candidate in [- self._repo_path / "compile_commands.json",- self._repo_path / "build" / "compile_commands.json",- ]:- if candidate.exists():- try:- with open(candidate) as f:- commands = json.load(f)- result: dict[str, dict] = {}- for entry in commands:- file_path = Path(entry.get("file", ""))- if file_path.is_absolute():- try:- file_rel = file_path.relative_to(self._repo_path)- except ValueError:- continue- else:- file_rel = file_path- result[file_rel.as_posix()] = entry- if result:- self._compile_commands_cache = result- log.info(- "Loaded compile_commands.json",- path=str(candidate),- entries=len(self._compile_commands_cache),- )- return self._compile_commands_cache- # No valid entries — try next candidate- log.debug(- "compile_commands.json had no resolvable entries", path=str(candidate)- )- except Exception as exc:- log.debug("Failed to load compile_commands.json", error=str(exc))- return None-- def _extract_include_dirs(self, source_file: str) -> list[str]:- """Return absolute include directories for source_file from compile_commands.json."""- commands = self._load_compile_commands()- if not commands or source_file not in commands:- return []- entry = commands[source_file]- cmd_dir = Path(entry.get("directory", str(self._repo_path or "")))- # compile_commands.json entries use either "arguments" (pre-split array)- # or "command" (shell-quoted string) — check arguments first- if "arguments" in entry:- tokens = list(entry["arguments"])- else:- command = entry.get("command", "")- try:- tokens = shlex.split(command)- except ValueError:- return []- include_dirs: list[str] = []- i = 0- while i < len(tokens):- tok = tokens[i]- if tok in ("-I", "-isystem", "-iquote"):- if i + 1 < len(tokens):- include_dirs.append(tokens[i + 1])- i += 2- else:- i += 1- elif tok.startswith("-I") and len(tok) > 2:- include_dirs.append(tok[2:])- i += 1- elif tok.startswith("-isystem") and len(tok) > 8:- include_dirs.append(tok[8:])- i += 1- else:- i += 1- result: list[str] = []- for d in include_dirs:- p = Path(d)- if not p.is_absolute():- p = cmd_dir / p- result.append(str(p.resolve()))- return result-def _build_stem_map(self, path_set: set[str]) -> dict[str, list[str]]:- """Map import-stems to candidate file paths, sorted best-first.-- For Python ``__init__.py`` files the stem is the *parent directory- name*, since ``import flask`` resolves to ``src/flask/__init__.py``- and not to a file with literal stem ``__init__``. For every other- file the stem is the filename without extension. The same map is- consulted by Python, Go, C/C++, and the generic fallback in- :meth:`_resolve_import` — keeping all collision logic in one place- is what makes the resolver deterministic across languages.-- On stem collisions (test fixtures, vendored copies, deep examples)- candidates are sorted by :func:`_stem_priority` so callers can take- ``candidates[0]`` and get the canonical resolution. The fix that- prevents test-fixture-named-like-the-package PageRank inflation- lives here, not in any per-directory exclusion list.-- Complexity: O(N) build, plus O(k log k) per bucket of size k. Total- worst case O(N log N) when one stem dominates; in practice O(N).- """+ """Map import-stems to candidate file paths, sorted best-first."""buckets: dict[str, list[str]] = {}for p in path_set:path_obj = Path(p)if path_obj.name == "__init__.py":parent = path_obj.parent.nameif not parent:- # Repo-root __init__.py — no meaningful key. Skip rather- # than register under the empty stem.continuestem = parent.lower()else:@@ -674,321 +522,12 @@ class GraphBuilder:paths.sort(key=lambda candidate: _stem_priority(candidate, stem))return buckets- @staticmethod- def _stem_lookup(stem_map: dict[str, list[str]], stem: str) -> str | None:- """Return the highest-priority path for ``stem``, or None."""- candidates = stem_map.get(stem)- return candidates[0] if candidates else None-- def _resolve_import(- self,- module_path: str,- importer_path: str,- path_set: set[str],- stem_map: dict[str, list[str]],- language: str,- ) -> str | None:- """Best-effort resolve of an import to a known file path."""- if not module_path:- return None-- importer_dir = Path(importer_path).parent-- # --- Python ---- if language == "python":- # Relative import: ".sibling" or "..parent.module"- if module_path.startswith("."):- dots = len(module_path) - len(module_path.lstrip("."))- rest = module_path[dots:].replace(".", "/")- base = importer_dir- for _ in range(dots - 1):- base = base.parent- candidates = [- (base / rest).with_suffix(".py").as_posix() if rest else None,- (base / rest / "__init__.py").as_posix() if rest else None,- ]- for c in candidates:- if c and c in path_set:- return c- return None- # Absolute import: "python_pkg.calculator" → "python_pkg/calculator.py"- # Try the obvious filesystem layouts in order. Modern Python- # packaging conventions place the package under "src/", so we- # check that prefix too — non-existent candidates are filtered- # by the path_set membership check, so adding more candidates- # is free of regressions.- dotted = module_path.replace(".", "/")- candidates = [- f"{dotted}.py",- f"{dotted}/__init__.py",- f"src/{dotted}.py",- f"src/{dotted}/__init__.py",- ]- for c in candidates:- if c in path_set:- return c- # Stem-only fallback — uses the deterministic priority from- # _build_stem_map so test fixtures named like the package- # cannot win against the canonical source file.- stem = module_path.split(".")[-1].lower()- return self._stem_lookup(stem_map, stem)-- # --- TypeScript / JavaScript ---- if language in ("typescript", "javascript"):- if module_path.startswith("."):- base = importer_dir / module_path- for ext in (".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js"):- candidate = Path(str(base) + ext).as_posix()- if candidate in path_set:- return candidate- candidate = (- base.with_suffix(ext).as_posix()- if not ext.startswith("/")- else (base / "index.ts").as_posix()- )- if candidate in path_set:- return candidate- return None-- # Non-relative: try tsconfig path-alias resolution first.- if self._tsconfig_resolver is not None:- importer_abs = (- str(self._repo_path / importer_path) if self._repo_path else importer_path- )- alias_resolved = self._tsconfig_resolver.resolve(module_path, importer_abs)- if alias_resolved is not None:- return alias_resolved-- # Fallback: external npm package.- external_key = f"external:{module_path}"- if external_key not in self._graph.nodes:- self._graph.add_node(- external_key, language="external", symbol_count=0, has_error=False- )- return external_key-- # --- Go ---- if language == "go":- return self._resolve_go_import(module_path, path_set, stem_map)-- # --- C / C++ ---- if language in ("cpp", "c"):- repo_root = self._repo_path.resolve() if self._repo_path else None- # 1. Try compile_commands.json include paths- for inc_dir in self._extract_include_dirs(importer_path):- candidate = (Path(inc_dir) / module_path).resolve()- if repo_root:- try:- rel = candidate.relative_to(repo_root).as_posix()- if rel in path_set:- return rel- except ValueError:- pass- # 2. Try relative to the importer's directory- if repo_root:- try:- rel = (importer_dir / module_path).resolve().relative_to(repo_root).as_posix()- if rel in path_set:- return rel- except ValueError:- pass- # 3. Stem-matching fallback- stem = Path(module_path).stem.lower()- return self._stem_lookup(stem_map, stem)-- # --- Rust ---- if language == "rust":- return self._resolve_rust_import(module_path, importer_path, path_set, stem_map)-- # --- Generic fallback: stem matching ---- stem = Path(module_path).stem.lower()- return self._stem_lookup(stem_map, stem)-- # ------------------------------------------------------------------- # Go module resolution- # -------------------------------------------------------------------- def _read_go_module_path(self) -> str | None:- """Read the ``module`` directive from ``go.mod``, if present."""- if self._repo_path is None:- return None- go_mod = self._repo_path / "go.mod"- if not go_mod.is_file():- return None- try:- for line in go_mod.read_text(encoding="utf-8", errors="ignore").splitlines():- line = line.strip()- if line.startswith("module "):- return line.split(None, 1)[1].strip()- except Exception:- pass- return None-- def _resolve_go_import(- self,- module_path: str,- path_set: set[str],- stem_map: dict[str, str],- ) -> str | None:- """Resolve a Go import path.-- If ``go.mod`` declares ``module github.com/org/repo``, then an- import ``github.com/org/repo/pkg/util`` maps to ``pkg/util/*.go``- in the repository. Unmatched imports are classified as external.- """- # If we know the module path and the import starts with it,- # strip the prefix to get the repo-relative package dir.- if self._go_module_path and module_path.startswith(self._go_module_path):- suffix = module_path[len(self._go_module_path) :]- rel_dir = suffix.lstrip("/")- # Find any Go file in that directory- for p in 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}"):- return p- # Try stem matching as fallback for the package name- pkg_name = rel_dir.rsplit("/", 1)[-1].lower() if rel_dir else ""- if pkg_name:- result = self._stem_lookup(stem_map, pkg_name)- if result:- return result-- # No go.mod match — fall back to stem matching on the last segment- stem = module_path.rsplit("/", 1)[-1].lower()- result = self._stem_lookup(stem_map, stem)- if result:- return result-- # External package- external_key = f"external:{module_path}"- if external_key not in self._graph.nodes:- self._graph.add_node(- external_key, language="external", symbol_count=0, has_error=False- )- return external_key-- # ------------------------------------------------------------------- # Rust import resolution- # -------------------------------------------------------------------- def _resolve_rust_import(- self,- module_path: str,- importer_path: str,- path_set: set[str],- stem_map: dict[str, str],- ) -> str | None:- """Resolve a Rust ``use`` path to a repo-relative file.-- Handles ``crate::``, ``self::``, ``super::`` prefixes by mapping- them to filesystem paths, then probing for ``<name>.rs`` or- ``<name>/mod.rs``. External crates are classified as ``external:``- nodes.- """- parts = module_path.split("::")- if not parts:- return None-- prefix = parts[0]-- # --- crate:: — resolve from the crate root ---- if prefix == "crate":- crate_root = self._find_rust_crate_root(importer_path)- return self._probe_rust_path(crate_root, parts[1:], path_set)-- # --- self:: — resolve from the current module's directory ---- if prefix == "self":- importer_dir = str(Path(importer_path).parent.as_posix())- return self._probe_rust_path(importer_dir, parts[1:], path_set)-- # --- super:: — resolve from the parent directory ---- if prefix == "super":- parent_dir = str(Path(importer_path).parent.parent.as_posix())- return self._probe_rust_path(parent_dir, parts[1:], path_set)-- # --- External crate (no prefix or unknown crate name) ---- # Check if it might be a local module at the crate root first- crate_root = self._find_rust_crate_root(importer_path)- resolved = self._probe_rust_path(crate_root, parts, path_set)- if resolved is not None:- return resolved-- # External crate- external_key = f"external:{module_path}"- if external_key not in self._graph.nodes:- self._graph.add_node(- external_key, language="external", symbol_count=0, has_error=False- )- return external_key-- def _find_rust_crate_root(self, importer_path: str) -> str:- """Find the ``src/`` directory containing the importer (Rust crate root).-- Walks up from the importer looking for ``lib.rs`` or ``main.rs``- siblings, returning the directory containing them. Falls back- to the nearest ``src/`` directory.- """- parts = Path(importer_path).parts- for i in range(len(parts) - 1, -1, -1):- candidate_dir = Path(*parts[:i]) if i > 0 else Path(".")- for root_file in ("lib.rs", "main.rs"):- root_path = (candidate_dir / root_file).as_posix()- if root_path in self._parsed_files:- return candidate_dir.as_posix()- if parts[i] == "src" and i > 0:- return candidate_dir.as_posix()- return Path(importer_path).parent.as_posix()-- @staticmethod- def _probe_rust_path(- base_dir: str,- path_parts: list[str],- path_set: set[str],- ) -> str | None:- """Probe the file system for a Rust module path.-- For ``[\"models\", \"Calculator\"]`` from base ``src/``, tries:- - ``src/models.rs`` (module file)- - ``src/models/mod.rs`` (directory module)- Then recurses into deeper segments. The last segment is often- a symbol name (struct/fn), so we try without it too.- """- if not path_parts:- return None-- base = Path(base_dir)-- # Try progressively deeper path segments — the last N segments- # may be symbol names rather than module names.- for depth in range(len(path_parts), 0, -1):- module_parts = path_parts[:depth]- # Build the path: base / part1 / part2 / ... / partN-1- module_dir = base- for p in module_parts[:-1]:- module_dir = module_dir / p-- last = module_parts[-1]- # Try <dir>/<last>.rs- candidate = (module_dir / f"{last}.rs").as_posix()- if candidate in path_set:- return candidate- # Try <dir>/<last>/mod.rs- candidate = (module_dir / last / "mod.rs").as_posix()- if candidate in path_set:- return candidate-- return None-# ------------------------------------------------------------------- # Co-change edges (Phase 5.5)+ # Co-change edges# ------------------------------------------------------------------def add_co_change_edges(self, git_meta_map: dict, min_count: int = 3) -> int:- """Add co_changes edges from git metadata. Returns count of edges added.-- These DO NOT affect PageRank — filter them out before computing.- """+ """Add co_changes edges from git metadata. Returns count of edges added."""count = 0seen: set[tuple[str, str]] = set()@@ -1015,7 +554,6 @@ class GraphBuilder:continueseen.add(pair)- # Don't add if an import edge already existsif not self._graph.has_edge(file_path, partner_path) and not self._graph.has_edge(partner_path, file_path):@@ -1033,14 +571,11 @@ class GraphBuilder:def update_co_change_edges(self, updated_meta: dict, min_count: int = 3) -> None:"""Remove old co_changes edges for updated files, add new ones."""- # Remove existing co_changes edges involving updated filesedges_to_remove = []for u, v, data in self._graph.edges(data=True):if data.get("edge_type") == "co_changes" and (u in updated_meta or v in updated_meta):edges_to_remove.append((u, v))self._graph.remove_edges_from(edges_to_remove)-- # Re-add co_changes edgesself.add_co_change_edges(updated_meta, min_count)# ------------------------------------------------------------------@@ -1053,7 +588,6 @@ class GraphBuilder:if e.source not in self._graph:continueif e.target not in self._graph:- # add a stub node so dead-code analysis sees it as reachableself._graph.add_node(e.target)self._graph.add_edge(e.source,@@ -1070,189 +604,35 @@ class GraphBuilder:def add_framework_edges(self, tech_stack: list[str] | None = None) -> int:"""Add synthetic edges for framework-mediated relationships.- Detects common patterns (conftest fixtures, Django settings/admin/urls,- FastAPI include_router, Flask register_blueprint) and creates directed- edges with ``edge_type="framework"``. These edges participate in- PageRank (they represent real runtime dependencies).-Returns the number of edges added."""- count = 0- path_set = set(self._parsed_files.keys())+ from .framework_edges import add_framework_edges- # Always run: pytest conftest detection- count += self._add_conftest_edges(path_set)-- stack_lower = {s.lower() for s in (tech_stack or [])}+ path_set = set(self._parsed_files.keys())+ stem_map = self._build_stem_map(path_set)- if "django" in stack_lower:- count += self._add_django_edges(path_set)- if "fastapi" in stack_lower or "starlette" in stack_lower:- count += self._add_fastapi_edges(path_set)- if "flask" in stack_lower:- count += self._add_flask_edges(path_set)+ 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),+ parsed_files=self._parsed_files,+ )+ count = add_framework_edges(self._graph, self._parsed_files, ctx, tech_stack)if count:log.info("Framework edges added", count=count)return count- def _add_edge_if_new(self, source: str, target: str) -> bool:- """Add a framework edge if no edge already exists. Returns True if added."""- if source == target:- return False- if self._graph.has_edge(source, target):- return False- self._graph.add_edge(source, target, edge_type="framework", imported_names=[])- return True-- def _add_conftest_edges(self, path_set: set[str]) -> int:- """conftest.py → test files in the same or child directories."""- count = 0- conftest_paths = [p for p in path_set if Path(p).name == "conftest.py"]-- for conf in conftest_paths:- conf_dir = Path(conf).parent.as_posix()- prefix = f"{conf_dir}/" if conf_dir != "." else ""- for p in path_set:- if p == conf:- continue- node = self._graph.nodes.get(p, {})- if not node.get("is_test", False):- continue- # Test file must be in the same or a child directory- if (- p.startswith(prefix) or (prefix == "" and "/" not in p)- ) and self._add_edge_if_new(p, conf):- count += 1- return count-- def _add_django_edges(self, path_set: set[str]) -> int:- """Django conventions: admin→models, urls→views in the same directory."""- count = 0- by_dir: dict[str, dict[str, str]] = {} # dir → {stem: path}- for p in path_set:- pp = Path(p)- d = pp.parent.as_posix()- by_dir.setdefault(d, {})[pp.stem] = p-- for _d, stems in by_dir.items():- # admin.py → models.py- if (- "admin" in stems- and "models" in stems- and self._add_edge_if_new(stems["admin"], stems["models"])- ):- count += 1- # urls.py → views.py- if (- "urls" in stems- and "views" in stems- and self._add_edge_if_new(stems["urls"], stems["views"])- ):- count += 1- # forms.py → models.py- if (- "forms" in stems- and "models" in stems- and self._add_edge_if_new(stems["forms"], stems["models"])- ):- count += 1- # serializers.py → models.py- if (- "serializers" in stems- and "models" in stems- and self._add_edge_if_new(stems["serializers"], stems["models"])- ):- count += 1- return count-- def _add_fastapi_edges(self, path_set: set[str]) -> int:- """Detect include_router() calls and link app files to router modules."""- import re-- count = 0- # Build a map from imported variable names to source file paths- var_to_file: dict[str, str] = {}- stem_map = {Path(p).stem.lower(): p for p in path_set}- for path, parsed in self._parsed_files.items():- for imp in parsed.imports:- for name in imp.imported_names:- if name.lower().endswith("router") or name.lower().endswith("app"):- resolved = self._resolve_import(- imp.module_path,- path,- path_set,- stem_map,- parsed.file_info.language,- )- if resolved and resolved in path_set:- var_to_file[name] = resolved-- router_re = re.compile(r"(?:include_router|add_api_route)\s*\(\s*(\w+)")- for path, parsed in self._parsed_files.items():- if parsed.file_info.language != "python":- continue- try:- source = Path(parsed.file_info.abs_path).read_text(errors="ignore")- except Exception:- continue- for match in router_re.finditer(source):- var_name = match.group(1)- target = var_to_file.get(var_name)- if target and target in path_set and self._add_edge_if_new(path, target):- count += 1- return count-- def _add_flask_edges(self, path_set: set[str]) -> int:- """Detect register_blueprint() calls and link app files to blueprint modules."""- import re-- count = 0- var_to_file: dict[str, str] = {}- stem_map = {Path(p).stem.lower(): p for p in path_set}- for path, parsed in self._parsed_files.items():- for imp in parsed.imports:- for name in imp.imported_names:- if "blueprint" in name.lower() or name.lower().endswith("bp"):- resolved = self._resolve_import(- imp.module_path,- path,- path_set,- stem_map,- parsed.file_info.language,- )- if resolved and resolved in path_set:- var_to_file[name] = resolved-- bp_re = re.compile(r"register_blueprint\s*\(\s*(\w+)")- for path, parsed in self._parsed_files.items():- if parsed.file_info.language != "python":- continue- try:- source = Path(parsed.file_info.abs_path).read_text(errors="ignore")- except Exception:- continue- for match in bp_re.finditer(source):- var_name = match.group(1)- target = var_to_file.get(var_name)- if target and target in path_set and self._add_edge_if_new(path, target):- count += 1- return count-def file_subgraph(self) -> nx.DiGraph:- """Return a subgraph containing only file-level nodes and import edges.-- Used for PageRank, betweenness, and other file-level metrics that- should not be affected by symbol-level nodes.- """+ """Return a subgraph containing only file-level nodes and import edges."""g = self.graph()file_nodes = [- n- for n, d in g.nodes(data=True)- if d.get("node_type", "file") in ("file", "external")+ n for n, d in g.nodes(data=True) if d.get("node_type", "file") in ("file", "external")]sub = g.subgraph(file_nodes).copy()- # Remove non-import edges (co_changes, framework, dynamic)edges_to_remove = [(u, v) for u, v, d in sub.edges(data=True) if d.get("edge_type") in ("co_changes",)]@@ -1260,11 +640,7 @@ class GraphBuilder:return subdef pagerank(self, alpha: float = 0.85) -> dict[str, float]:- """Return PageRank scores for file nodes only.-- High PageRank → file is imported by many others → high documentation priority.- Operates on the file-level subgraph (excludes symbol nodes and co-change edges).- """+ """Return PageRank scores for file nodes only."""filtered = self.file_subgraph()if filtered.number_of_nodes() == 0:return {}diff --git a/packages/core/src/repowise/core/ingestion/heritage_resolver.py b/packages/core/src/repowise/core/ingestion/heritage_resolver.pyindex bfe12820c..6b08f17d9 100644--- a/packages/core/src/repowise/core/ingestion/heritage_resolver.py+++ b/packages/core/src/repowise/core/ingestion/heritage_resolver.py@@ -31,18 +31,25 @@ from .models import HeritageRelation, ParsedFilelog = structlog.get_logger(__name__)-def _file_language(- parsed_files: dict[str, ParsedFile], symbol_id: str-) -> str | None:+def _file_language(parsed_files: dict[str, ParsedFile], symbol_id: str) -> str | None:"""Extract language from a symbol ID's file via the parsed files map."""file_path = symbol_id.split("::")[0] if "::" in symbol_id else symbol_idparsed = parsed_files.get(file_path)return parsed.file_info.language if parsed else None+# Symbol kinds that can be parents in heritage relationships-_PARENT_KINDS = frozenset({- "class", "interface", "trait", "struct", "enum", "type_alias", "impl",-})+_PARENT_KINDS = frozenset(+ {+ "class",+ "interface",+ "trait",+ "struct",+ "enum",+ "type_alias",+ "impl",+ }+)@dataclass(frozen=True, slots=True)@@ -124,9 +131,7 @@ class HeritageResolver:return results- def _resolve_one(- self, file_path: str, rel: HeritageRelation- ) -> ResolvedHeritage | None:+ def _resolve_one(self, file_path: str, rel: HeritageRelation) -> ResolvedHeritage | None:"""Resolve a single HeritageRelation through three-tier fallback."""child_id = f"{file_path}::{rel.child_name}"parent_name = rel.parent_namediff --git a/packages/core/src/repowise/core/ingestion/language_data.py b/packages/core/src/repowise/core/ingestion/language_data.pyindex 8ab84c036..986994412 100644--- a/packages/core/src/repowise/core/ingestion/language_data.py+++ b/packages/core/src/repowise/core/ingestion/language_data.py@@ -1,206 +1,29 @@"""Per-language constants for call/heritage resolution filtering.-Centralises all language-specific data tables (builtin functions, builtin-parent types, test path patterns) in one place so they can be adjusted-without touching resolution or extraction logic.--Adding a new language:- 1. Add its builtins to ``BUILTIN_CALLS`` (functions the language provides- globally that should NOT create graph edges).- 2. Add its builtin parent types to ``BUILTIN_PARENTS`` (base classes /- traits / interfaces provided by the language runtime that should NOT- create heritage edges).- 3. That's it — the resolver and parser import these dicts automatically.+Delegates to the centralised ``LanguageRegistry`` for actual data.+Public API (``get_builtin_calls``, ``get_builtin_parents``) is preserved+so existing consumers need no changes."""from __future__ import annotations+from .languages.registry import REGISTRY+# ----------------------------------------------------------------------------# Builtin function calls — filtered during call extraction (parser.py)-#-# These are names that appear as function calls in source code but refer to-# language-provided builtins, not user-defined symbols. Extracting them-# pollutes the call graph because Tier 3 global resolution can match them-# to unrelated user symbols with the same name in other files/languages.+# Backward-compatible dict views — used by any code that reads the dicts+# directly instead of calling the helper functions.# ----------------------------------------------------------------------------BUILTIN_CALLS: dict[str, frozenset[str]] = {- "python": frozenset({- # builtins module — https://docs.python.org/3/library/functions.html- "abs", "aiter", "all", "anext", "any", "ascii",- "bin", "bool", "breakpoint", "bytearray", "bytes",- "callable", "chr", "classmethod", "compile", "complex",- "delattr", "dict", "dir", "divmod",- "enumerate", "eval", "exec",- "filter", "float", "format", "frozenset",- "getattr", "globals",- "hasattr", "hash", "help", "hex",- "id", "input", "int", "isinstance", "issubclass", "iter",- "len", "list", "locals",- "map", "max", "memoryview", "min",- "next",- "object", "oct", "open", "ord",- "pow", "print", "property",- "range", "repr", "reversed", "round",- "set", "setattr", "slice", "sorted", "staticmethod", "str", "sum", "super",- "tuple", "type",- "vars",- "zip",- "__import__",- }),- "typescript": frozenset({- # Global functions & constructors- "parseInt", "parseFloat", "isNaN", "isFinite",- "decodeURI", "decodeURIComponent", "encodeURI", "encodeURIComponent",- "setTimeout", "setInterval", "clearTimeout", "clearInterval",- "fetch", "require", "eval", "atob", "btoa",- # Global object namespaces (not user-callable symbols)- "JSON", "Math", "console", "Reflect", "Proxy",- # Builtin constructors — user code rarely shadows these- "Object", "Array", "String", "Number", "Boolean",- "Date", "RegExp", "Promise", "Set", "Map", "WeakMap", "WeakSet",- "Symbol", "ArrayBuffer", "DataView", "Uint8Array",- "Error", "TypeError", "RangeError", "SyntaxError", "ReferenceError",- "Int8Array", "Int16Array", "Int32Array", "Float32Array", "Float64Array",- }),- # JavaScript shares the TypeScript set- "javascript": None,- "java": frozenset({- # java.lang auto-imported types used as static calls- "System", "Objects", "Arrays", "Collections", "Math",- "Integer", "Long", "Double", "Float", "Boolean", "Character",- "Byte", "Short",- "String", "Object", "Class", "Thread",- "Throwable", "Exception", "RuntimeException", "Error",- "StringBuilder", "StringBuffer",- }),- "go": frozenset({- # Go builtins — https://pkg.go.dev/builtin- "make", "len", "cap", "new", "append", "copy", "close",- "delete", "complex", "real", "imag",- "panic", "recover",- "print", "println",- }),- "rust": frozenset({- # Macros and builtins that tree-sitter extracts as calls- "println", "eprintln", "print", "eprint",- "format", "format_args",- "vec", "panic", "todo", "unimplemented", "unreachable",- "assert", "assert_eq", "assert_ne",- "debug_assert", "debug_assert_eq", "debug_assert_ne",- "cfg", "include", "include_str", "include_bytes",- "env", "option_env", "concat", "stringify", "line", "column", "file",- "write", "writeln",- }),- "kotlin": frozenset({- "println", "print", "readLine",- "arrayOf", "listOf", "mutableListOf", "setOf", "mutableSetOf",- "mapOf", "mutableMapOf", "hashMapOf",- "lazy", "require", "check", "error",- "TODO", "run", "let", "also", "apply", "with",- }),- "ruby": frozenset({- "puts", "print", "p", "pp", "raise", "fail",- "require", "require_relative", "include", "extend", "prepend",- "attr_reader", "attr_writer", "attr_accessor",- "lambda", "proc",- }),- "cpp": frozenset({- # C++ stdlib commonly-extracted calls- "printf", "scanf", "fprintf", "sprintf", "snprintf",- "malloc", "calloc", "realloc", "free",- "sizeof", "alignof", "typeid", "decltype",- "static_cast", "dynamic_cast", "const_cast", "reinterpret_cast",- "move", "forward", "make_shared", "make_unique", "make_pair",- "cout", "cerr", "endl",- }),- "csharp": frozenset({- "Console", "Math", "Convert",- "String", "Object", "Array",- "GC", "Environment", "Activator",- "Task", "Interlocked",- "nameof", "typeof", "sizeof", "default",- }),- "c": frozenset({- "printf", "scanf", "fprintf", "sprintf", "snprintf",- "malloc", "calloc", "realloc", "free",- "memcpy", "memset", "memmove", "memcmp",- "strlen", "strcpy", "strncpy", "strcat", "strcmp", "strncmp",- "sizeof", "offsetof",- "assert", "abort", "exit",- }),+BUILTIN_CALLS: dict[str, frozenset[str] | None] = {+ spec.tag: spec.builtin_calls if spec.builtin_calls else None+ for spec in REGISTRY.all_specs()+ if spec.builtin_calls}---# ----------------------------------------------------------------------------# Builtin parent types — filtered during heritage extraction (parser.py)-#-# Base classes, interfaces, and traits provided by the language runtime.-# Creating heritage edges to these pollutes the graph because they are-# universally inherited and carry no architectural signal.-# ---------------------------------------------------------------------------+# JavaScript explicitly shares TypeScript's set via None sentinel+BUILTIN_CALLS["javascript"] = NoneBUILTIN_PARENTS: dict[str, frozenset[str]] = {- "python": frozenset({- "object", "Exception", "BaseException",- "type", "ABC", "ABCMeta",- "Protocol", # typing.Protocol- "NamedTuple", "TypedDict",- "Enum", "IntEnum", "Flag", "IntFlag", # enum base classes- }),- "typescript": frozenset({- "Error", "Object",- }),- "javascript": frozenset({- "Error", "Object",- }),- "java": frozenset({- "Object", "Throwable", "Exception", "RuntimeException", "Error",- "Enum",- "Serializable", "Cloneable", "Comparable", "Iterable",- "AutoCloseable", "Closeable",- }),- "go": frozenset({- "error", # Go's error interface- }),- "rust": frozenset({- # std::fmt, std::cmp, std::ops, std::marker traits- "Error", "Display", "Debug",- "Clone", "Copy", "Default",- "PartialEq", "Eq", "PartialOrd", "Ord", "Hash",- "Send", "Sync", "Sized", "Unpin",- "Iterator", "IntoIterator",- "From", "Into", "TryFrom", "TryInto",- "AsRef", "AsMut", "Borrow", "BorrowMut",- "Drop", "Deref", "DerefMut",- "Add", "Sub", "Mul", "Div", "Rem", "Neg",- "Fn", "FnMut", "FnOnce",- }),- "kotlin": frozenset({- "Any", "Throwable", "Exception", "RuntimeException", "Error",- "Enum",- "Comparable", "Iterable", "Serializable",- }),- "cpp": frozenset({- "exception", "runtime_error", "logic_error",- "invalid_argument", "out_of_range", "overflow_error",- # STL containers (not architectural parents)- "string", "vector", "map", "set", "list", "deque",- "unordered_map", "unordered_set",- "shared_ptr", "unique_ptr", "weak_ptr",- }),- "csharp": frozenset({- "Object", "ValueType", "Enum",- "Exception", "SystemException", "ApplicationException",- "IDisposable", "IEnumerable", "IEnumerator",- "IComparable", "ICloneable", "IEquatable",- }),- "ruby": frozenset({- "Object", "BasicObject",- "Exception", "StandardError", "RuntimeError",- "ScriptError", "LoadError", "SyntaxError",- "Comparable", "Enumerable", "Kernel",- }),+ spec.tag: spec.builtin_parents for spec in REGISTRY.all_specs() if spec.builtin_parents}@@ -210,15 +33,17 @@ def get_builtin_calls(language: str) -> frozenset[str]:Falls back to the ``typescript`` set for ``javascript`` when thejavascript key is ``None``."""- result = BUILTIN_CALLS.get(language)- if result is not None:- return result+ spec = REGISTRY.get(language)+ if spec and spec.builtin_calls:+ return spec.builtin_calls# javascript → typescript fallbackif language == "javascript":- return BUILTIN_CALLS.get("typescript", frozenset())+ ts = REGISTRY.get("typescript")+ return ts.builtin_calls if ts else frozenset()return frozenset()def get_builtin_parents(language: str) -> frozenset[str]:"""Return the builtin parent type names for a language."""- return BUILTIN_PARENTS.get(language, frozenset())+ spec = REGISTRY.get(language)+ return spec.builtin_parents if spec else frozenset()diff --git a/packages/core/src/repowise/core/ingestion/languages/__init__.py b/packages/core/src/repowise/core/ingestion/languages/__init__.pynew file mode 100644index 000000000..bfb277984--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/__init__.py@@ -0,0 +1,15 @@+"""Centralised language configuration for repowise.++Public API::++ from repowise.core.ingestion.languages import REGISTRY++ spec = REGISTRY.get("python")+ ext_map = REGISTRY.all_extensions()+ code = REGISTRY.code_languages()+"""++from .registry import REGISTRY+from .spec import LanguageSpec++__all__ = ["REGISTRY", "LanguageSpec"]diff --git a/packages/core/src/repowise/core/ingestion/languages/registry.py b/packages/core/src/repowise/core/ingestion/languages/registry.pynew file mode 100644index 000000000..56db45e3b--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/registry.py@@ -0,0 +1,1170 @@+"""Central language registry — single source of truth.++Every language-specific constant previously scattered across models.py,+parser.py, language_data.py, traverser.py, page_generator.py, cli/ui.py,+git_indexer.py, and others is consolidated here.++This module is a **leaf dependency** — it imports nothing from the+ingestion pipeline (no parser, graph, traverser, etc.) to avoid circular+imports.++Frontend language colours are maintained in parallel in+``packages/web/src/lib/utils/confidence.ts`` and+``packages/web/src/components/``. A Phase 2 build task will generate+the TypeScript file from this registry.+"""++from __future__ import annotations++from collections.abc import Iterable++from .spec import LanguageSpec++# =========================================================================+# Language specifications — one per LanguageTag value+# =========================================================================++_SPECS: tuple[LanguageSpec, ...] = (+ # -----------------------------------------------------------------+ # Full-tier languages (AST + imports + calls + heritage + bindings)+ # -----------------------------------------------------------------+ LanguageSpec(+ tag="python",+ display_name="Python",+ extensions=frozenset({".py", ".pyi"}),+ grammar_package="tree_sitter_python",+ scm_file="python.scm",+ heritage_node_types=frozenset({"class_definition"}),+ entry_point_patterns=(+ "main.py",+ "app.py",+ "__main__.py",+ "manage.py",+ "wsgi.py",+ "asgi.py",+ ),+ manifest_files=("pyproject.toml", "setup.py", "setup.cfg"),+ lock_files=("poetry.lock", "uv.lock"),+ generated_suffixes=("_pb2.py", "_pb2_grpc.py"),+ shebang_tokens=("python",),+ blocked_dirs=(+ "__pycache__",+ ".pytest_cache",+ ".mypy_cache",+ ".ruff_cache",+ ".tox",+ ".eggs",+ "site-packages",+ ),+ blocked_extensions=(".pyc", ".pyo", ".pyd"),+ builtin_calls=frozenset(+ {+ "abs",+ "aiter",+ "all",+ "anext",+ "any",+ "ascii",+ "bin",+ "bool",+ "breakpoint",+ "bytearray",+ "bytes",+ "callable",+ "chr",+ "classmethod",+ "compile",+ "complex",+ "delattr",+ "dict",+ "dir",+ "divmod",+ "enumerate",+ "eval",+ "exec",+ "filter",+ "float",+ "format",+ "frozenset",+ "getattr",+ "globals",+ "hasattr",+ "hash",+ "help",+ "hex",+ "id",+ "input",+ "int",+ "isinstance",+ "issubclass",+ "iter",+ "len",+ "list",+ "locals",+ "map",+ "max",+ "memoryview",+ "min",+ "next",+ "object",+ "oct",+ "open",+ "ord",+ "pow",+ "print",+ "property",+ "range",+ "repr",+ "reversed",+ "round",+ "set",+ "setattr",+ "slice",+ "sorted",+ "staticmethod",+ "str",+ "sum",+ "super",+ "tuple",+ "type",+ "vars",+ "zip",+ "__import__",+ }+ ),+ builtin_parents=frozenset(+ {+ "object",+ "Exception",+ "BaseException",+ "type",+ "ABC",+ "ABCMeta",+ "Protocol",+ "NamedTuple",+ "TypedDict",+ "Enum",+ "IntEnum",+ "Flag",+ "IntFlag",+ }+ ),+ color_hex="#3572A5",+ ),+ LanguageSpec(+ tag="typescript",+ display_name="TypeScript",+ extensions=frozenset({".ts", ".tsx"}),+ grammar_package="tree_sitter_typescript",+ grammar_loader="language_typescript",+ scm_file="typescript.scm",+ heritage_node_types=frozenset(+ {"class_declaration", "abstract_class_declaration", "interface_declaration"}+ ),+ entry_point_patterns=("index.ts", "main.ts", "app.ts", "server.ts"),+ manifest_files=("package.json",),+ lock_files=("package-lock.json", "yarn.lock", "pnpm-lock.yaml"),+ generated_suffixes=("_pb.ts",),+ shebang_tokens=(),+ blocked_dirs=("node_modules", ".next", "dist", "build"),+ builtin_calls=frozenset(+ {+ "parseInt",+ "parseFloat",+ "isNaN",+ "isFinite",+ "decodeURI",+ "decodeURIComponent",+ "encodeURI",+ "encodeURIComponent",+ "setTimeout",+ "setInterval",+ "clearTimeout",+ "clearInterval",+ "fetch",+ "require",+ "eval",+ "atob",+ "btoa",+ "JSON",+ "Math",+ "console",+ "Reflect",+ "Proxy",+ "Object",+ "Array",+ "String",+ "Number",+ "Boolean",+ "Date",+ "RegExp",+ "Promise",+ "Set",+ "Map",+ "WeakMap",+ "WeakSet",+ "Symbol",+ "ArrayBuffer",+ "DataView",+ "Uint8Array",+ "Error",+ "TypeError",+ "RangeError",+ "SyntaxError",+ "ReferenceError",+ "Int8Array",+ "Int16Array",+ "Int32Array",+ "Float32Array",+ "Float64Array",+ }+ ),+ builtin_parents=frozenset({"Error", "Object"}),+ color_hex="#3178C6",+ ),+ LanguageSpec(+ tag="javascript",+ display_name="JavaScript",+ extensions=frozenset({".js", ".jsx", ".mjs", ".cjs"}),+ grammar_package="tree_sitter_javascript",+ scm_file="javascript.scm",+ heritage_node_types=frozenset({"class_declaration"}),+ entry_point_patterns=("index.js", "main.js", "app.js", "server.js"),+ manifest_files=("package.json",),+ lock_files=("package-lock.json", "yarn.lock", "pnpm-lock.yaml"),+ generated_suffixes=("_pb.js",),+ shebang_tokens=("node",),+ blocked_dirs=("node_modules", "dist", "build"),+ # JavaScript shares TypeScript's builtin calls+ builtin_calls=frozenset(+ {+ "parseInt",+ "parseFloat",+ "isNaN",+ "isFinite",+ "decodeURI",+ "decodeURIComponent",+ "encodeURI",+ "encodeURIComponent",+ "setTimeout",+ "setInterval",+ "clearTimeout",+ "clearInterval",+ "fetch",+ "require",+ "eval",+ "atob",+ "btoa",+ "JSON",+ "Math",+ "console",+ "Reflect",+ "Proxy",+ "Object",+ "Array",+ "String",+ "Number",+ "Boolean",+ "Date",+ "RegExp",+ "Promise",+ "Set",+ "Map",+ "WeakMap",+ "WeakSet",+ "Symbol",+ "ArrayBuffer",+ "DataView",+ "Uint8Array",+ "Error",+ "TypeError",+ "RangeError",+ "SyntaxError",+ "ReferenceError",+ "Int8Array",+ "Int16Array",+ "Int32Array",+ "Float32Array",+ "Float64Array",+ }+ ),+ builtin_parents=frozenset({"Error", "Object"}),+ color_hex="#F1E05A",+ ),+ LanguageSpec(+ tag="go",+ display_name="Go",+ extensions=frozenset({".go"}),+ grammar_package="tree_sitter_go",+ scm_file="go.scm",+ heritage_node_types=frozenset({"type_spec"}),+ entry_point_patterns=("main.go", "cmd/main.go"),+ manifest_files=("go.mod",),+ lock_files=("go.sum",),+ generated_suffixes=("_grpc.pb.go",),+ blocked_dirs=("vendor",),+ builtin_calls=frozenset(+ {+ "make",+ "len",+ "cap",+ "new",+ "append",+ "copy",+ "close",+ "delete",+ "complex",+ "real",+ "imag",+ "panic",+ "recover",+ "print",+ "println",+ }+ ),+ builtin_parents=frozenset({"error"}),+ color_hex="#00ADD8",+ ),+ LanguageSpec(+ tag="rust",+ display_name="Rust",+ extensions=frozenset({".rs"}),+ grammar_package="tree_sitter_rust",+ scm_file="rust.scm",+ heritage_node_types=frozenset({"impl_item", "trait_item", "struct_item", "enum_item"}),+ entry_point_patterns=("main.rs", "lib.rs"),+ manifest_files=("Cargo.toml",),+ lock_files=("Cargo.lock",),+ blocked_dirs=("target",),+ builtin_calls=frozenset(+ {+ "println",+ "eprintln",+ "print",+ "eprint",+ "format",+ "format_args",+ "vec",+ "panic",+ "todo",+ "unimplemented",+ "unreachable",+ "assert",+ "assert_eq",+ "assert_ne",+ "debug_assert",+ "debug_assert_eq",+ "debug_assert_ne",+ "cfg",+ "include",+ "include_str",+ "include_bytes",+ "env",+ "option_env",+ "concat",+ "stringify",+ "line",+ "column",+ "file",+ "write",+ "writeln",+ }+ ),+ builtin_parents=frozenset(+ {+ "Error",+ "Display",+ "Debug",+ "Clone",+ "Copy",+ "Default",+ "PartialEq",+ "Eq",+ "PartialOrd",+ "Ord",+ "Hash",+ "Send",+ "Sync",+ "Sized",+ "Unpin",+ "Iterator",+ "IntoIterator",+ "From",+ "Into",+ "TryFrom",+ "TryInto",+ "AsRef",+ "AsMut",+ "Borrow",+ "BorrowMut",+ "Drop",+ "Deref",+ "DerefMut",+ "Add",+ "Sub",+ "Mul",+ "Div",+ "Rem",+ "Neg",+ "Fn",+ "FnMut",+ "FnOnce",+ }+ ),+ color_hex="#DEA584",+ ),+ LanguageSpec(+ tag="java",+ display_name="Java",+ extensions=frozenset({".java"}),+ grammar_package="tree_sitter_java",+ scm_file="java.scm",+ heritage_node_types=frozenset(+ {"class_declaration", "interface_declaration", "enum_declaration"}+ ),+ entry_point_patterns=("Main.java", "Application.java"),+ manifest_files=("pom.xml", "build.gradle", "build.gradle.kts"),+ blocked_dirs=(".gradle",),+ builtin_calls=frozenset(+ {+ "System",+ "Objects",+ "Arrays",+ "Collections",+ "Math",+ "Integer",+ "Long",+ "Double",+ "Float",+ "Boolean",+ "Character",+ "Byte",+ "Short",+ "String",+ "Object",+ "Class",+ "Thread",+ "Throwable",+ "Exception",+ "RuntimeException",+ "Error",+ "StringBuilder",+ "StringBuffer",+ }+ ),+ builtin_parents=frozenset(+ {+ "Object",+ "Throwable",+ "Exception",+ "RuntimeException",+ "Error",+ "Enum",+ "Serializable",+ "Cloneable",+ "Comparable",+ "Iterable",+ "AutoCloseable",+ "Closeable",+ }+ ),+ color_hex="#B07219",+ ),+ # -----------------------------------------------------------------+ # Partial-tier languages (AST + some imports, gaps in calls/bindings)+ # -----------------------------------------------------------------+ LanguageSpec(+ tag="cpp",+ display_name="C++",+ extensions=frozenset({".cpp", ".cc", ".cxx", ".h", ".hpp", ".hxx"}),+ grammar_package="tree_sitter_cpp",+ scm_file="cpp.scm",+ heritage_node_types=frozenset({"class_specifier", "struct_specifier"}),+ entry_point_patterns=("main.cpp", "main.cc"),+ builtin_calls=frozenset(+ {+ "printf",+ "scanf",+ "fprintf",+ "sprintf",+ "snprintf",+ "malloc",+ "calloc",+ "realloc",+ "free",+ "sizeof",+ "alignof",+ "typeid",+ "decltype",+ "static_cast",+ "dynamic_cast",+ "const_cast",+ "reinterpret_cast",+ "move",+ "forward",+ "make_shared",+ "make_unique",+ "make_pair",+ "cout",+ "cerr",+ "endl",+ }+ ),+ builtin_parents=frozenset(+ {+ "exception",+ "runtime_error",+ "logic_error",+ "invalid_argument",+ "out_of_range",+ "overflow_error",+ "string",+ "vector",+ "map",+ "set",+ "list",+ "deque",+ "unordered_map",+ "unordered_set",+ "shared_ptr",+ "unique_ptr",+ "weak_ptr",+ }+ ),+ color_hex="#F34B7D",+ ),+ LanguageSpec(+ tag="c",+ display_name="C",+ extensions=frozenset({".c"}),+ shares_grammar_with="cpp",+ scm_file="c.scm",+ heritage_node_types=frozenset(),+ entry_point_patterns=("main.c",),+ builtin_calls=frozenset(+ {+ "printf",+ "scanf",+ "fprintf",+ "sprintf",+ "snprintf",+ "malloc",+ "calloc",+ "realloc",+ "free",+ "memcpy",+ "memset",+ "memmove",+ "memcmp",+ "strlen",+ "strcpy",+ "strncpy",+ "strcat",+ "strcmp",+ "strncmp",+ "sizeof",+ "offsetof",+ "assert",+ "abort",+ "exit",+ }+ ),+ color_hex="#555555",+ ),+ # -----------------------------------------------------------------+ # Traversal-tier languages (scaffolded — grammar not yet wired)+ # -----------------------------------------------------------------+ LanguageSpec(+ tag="kotlin",+ display_name="Kotlin",+ extensions=frozenset({".kt", ".kts"}),+ grammar_package="tree_sitter_kotlin",+ scm_file="kotlin.scm",+ heritage_node_types=frozenset({"class_declaration", "object_declaration"}),+ manifest_files=("build.gradle.kts", "build.gradle"),+ blocked_dirs=(".gradle",),+ builtin_calls=frozenset(+ {+ "println",+ "print",+ "readLine",+ "arrayOf",+ "listOf",+ "mutableListOf",+ "setOf",+ "mutableSetOf",+ "mapOf",+ "mutableMapOf",+ "hashMapOf",+ "lazy",+ "require",+ "check",+ "error",+ "TODO",+ "run",+ "let",+ "also",+ "apply",+ "with",+ }+ ),+ builtin_parents=frozenset(+ {+ "Any",+ "Throwable",+ "Exception",+ "RuntimeException",+ "Error",+ "Enum",+ "Comparable",+ "Iterable",+ "Serializable",+ }+ ),+ color_hex="#A97BFF",+ ),+ LanguageSpec(+ tag="ruby",+ display_name="Ruby",+ extensions=frozenset({".rb"}),+ grammar_package="tree_sitter_ruby",+ scm_file="ruby.scm",+ heritage_node_types=frozenset({"class"}),+ manifest_files=("Gemfile",),+ lock_files=("Gemfile.lock",),+ shebang_tokens=("ruby",),+ builtin_calls=frozenset(+ {+ "puts",+ "print",+ "p",+ "pp",+ "raise",+ "fail",+ "require",+ "require_relative",+ "include",+ "extend",+ "prepend",+ "attr_reader",+ "attr_writer",+ "attr_accessor",+ "lambda",+ "proc",+ }+ ),+ builtin_parents=frozenset(+ {+ "Object",+ "BasicObject",+ "Exception",+ "StandardError",+ "RuntimeError",+ "ScriptError",+ "LoadError",+ "SyntaxError",+ "Comparable",+ "Enumerable",+ "Kernel",+ }+ ),+ color_hex="#CC342D",+ ),+ LanguageSpec(+ tag="csharp",+ display_name="C#",+ extensions=frozenset({".cs"}),+ grammar_package="tree_sitter_c_sharp",+ scm_file="csharp.scm",+ heritage_node_types=frozenset(+ {"class_declaration", "interface_declaration", "struct_declaration"}+ ),+ builtin_calls=frozenset(+ {+ "Console",+ "Math",+ "Convert",+ "String",+ "Object",+ "Array",+ "GC",+ "Environment",+ "Activator",+ "Task",+ "Interlocked",+ "nameof",+ "typeof",+ "sizeof",+ "default",+ }+ ),+ builtin_parents=frozenset(+ {+ "Object",+ "ValueType",+ "Enum",+ "Exception",+ "SystemException",+ "ApplicationException",+ "IDisposable",+ "IEnumerable",+ "IEnumerator",+ "IComparable",+ "ICloneable",+ "IEquatable",+ }+ ),+ color_hex="#178600",+ ),+ LanguageSpec(+ tag="php",+ display_name="PHP",+ extensions=frozenset({".php"}),+ grammar_package="tree_sitter_php",+ grammar_loader="language_php",+ scm_file="php.scm",+ heritage_node_types=frozenset(+ {"class_declaration", "interface_declaration", "enum_declaration"}+ ),+ manifest_files=("composer.json",),+ lock_files=("composer.lock",),+ blocked_dirs=("vendor",),+ builtin_calls=frozenset(+ {+ "echo",+ "print",+ "var_dump",+ "print_r",+ "isset",+ "empty",+ "unset",+ "array",+ "count",+ "strlen",+ "strpos",+ "substr",+ "implode",+ "explode",+ "json_encode",+ "json_decode",+ }+ ),+ builtin_parents=frozenset(+ {+ "stdClass",+ "Exception",+ "RuntimeException",+ "InvalidArgumentException",+ "LogicException",+ "Iterator",+ "IteratorAggregate",+ "Countable",+ "Serializable",+ "JsonSerializable",+ "Stringable",+ "Throwable",+ }+ ),+ color_hex="#4F5D95",+ ),+ LanguageSpec(+ tag="swift",+ display_name="Swift",+ extensions=frozenset({".swift"}),+ grammar_package="tree_sitter_swift",+ scm_file="swift.scm",+ heritage_node_types=frozenset({"class_declaration", "protocol_declaration"}),+ manifest_files=("Package.swift",),+ builtin_calls=frozenset(+ {+ "print",+ "debugPrint",+ "fatalError",+ "precondition",+ "assert",+ "min",+ "max",+ "abs",+ "stride",+ "zip",+ "map",+ "filter",+ "reduce",+ "sorted",+ }+ ),+ builtin_parents=frozenset(+ {+ "NSObject",+ "Codable",+ "Encodable",+ "Decodable",+ "Hashable",+ "Equatable",+ "Comparable",+ "CustomStringConvertible",+ "Error",+ "Sendable",+ }+ ),+ color_hex="#F05138",+ ),+ LanguageSpec(+ tag="scala",+ display_name="Scala",+ extensions=frozenset({".scala"}),+ grammar_package="tree_sitter_scala",+ scm_file="scala.scm",+ heritage_node_types=frozenset(+ {"class_definition", "trait_definition", "object_definition"}+ ),+ manifest_files=("build.sbt",),+ builtin_calls=frozenset(+ {+ "println",+ "print",+ "require",+ "assert",+ "Some",+ "None",+ "Left",+ "Right",+ "Nil",+ "List",+ "Map",+ "Set",+ "Vector",+ "Array",+ }+ ),+ builtin_parents=frozenset(+ {+ "Any",+ "AnyRef",+ "AnyVal",+ "Product",+ "Serializable",+ "Throwable",+ "Exception",+ "RuntimeException",+ "Ordered",+ "Ordering",+ }+ ),+ color_hex="#DC322F",+ ),+ # -----------------------------------------------------------------+ # Config / data / markup languages (passthrough — no AST)+ # -----------------------------------------------------------------+ LanguageSpec(+ tag="shell",+ display_name="Shell",+ extensions=frozenset({".sh", ".bash", ".zsh"}),+ is_infra=True,+ is_passthrough=True,+ shebang_tokens=("bash", " sh"),+ color_hex="#89E051",+ ),+ LanguageSpec(+ tag="yaml",+ display_name="YAML",+ extensions=frozenset({".yaml", ".yml"}),+ is_code=False,+ is_passthrough=True,+ color_hex="#CB171E",+ ),+ LanguageSpec(+ tag="json",+ display_name="JSON",+ extensions=frozenset({".json"}),+ is_code=False,+ is_passthrough=True,+ color_hex="#292929",+ ),+ LanguageSpec(+ tag="toml",+ display_name="TOML",+ extensions=frozenset({".toml"}),+ is_code=False,+ is_passthrough=True,+ color_hex="#9C4221",+ ),+ LanguageSpec(+ tag="proto",+ display_name="Protocol Buffers",+ extensions=frozenset({".proto"}),+ is_code=False,+ is_passthrough=True,+ is_api_contract=True,+ ),+ LanguageSpec(+ tag="graphql",+ display_name="GraphQL",+ extensions=frozenset({".graphql", ".gql"}),+ is_code=False,+ is_passthrough=True,+ is_api_contract=True,+ ),+ LanguageSpec(+ tag="terraform",+ display_name="Terraform",+ extensions=frozenset({".tf", ".hcl"}),+ is_infra=True,+ is_passthrough=True,+ color_hex="#5C4EE5",+ ),+ LanguageSpec(+ tag="dockerfile",+ display_name="Dockerfile",+ special_filenames=frozenset({"Dockerfile", "dockerfile"}),+ is_infra=True,+ is_passthrough=True,+ color_hex="#384D54",+ ),+ LanguageSpec(+ tag="makefile",+ display_name="Makefile",+ special_filenames=frozenset({"Makefile", "makefile", "GNUmakefile"}),+ is_infra=True,+ is_passthrough=True,+ color_hex="#427819",+ ),+ LanguageSpec(+ tag="markdown",+ display_name="Markdown",+ extensions=frozenset({".md", ".mdx"}),+ is_code=False,+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="sql",+ display_name="SQL",+ extensions=frozenset({".sql"}),+ is_code=False,+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="openapi",+ display_name="OpenAPI",+ is_code=False,+ is_passthrough=True,+ is_api_contract=True,+ ),+ # -----------------------------------------------------------------+ # Extra languages — git blame coverage only (passthrough + is_code)+ # These exist so git_indexer tracks their history even though+ # tree-sitter grammars are not installed.+ # -----------------------------------------------------------------+ LanguageSpec(+ tag="objectivec",+ display_name="Objective-C",+ extensions=frozenset({".m", ".mm"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="elixir",+ display_name="Elixir",+ extensions=frozenset({".ex", ".exs"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="erlang",+ display_name="Erlang",+ extensions=frozenset({".erl", ".hrl"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="lua",+ display_name="Lua",+ extensions=frozenset({".lua"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="r",+ display_name="R",+ extensions=frozenset({".r"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="dart",+ display_name="Dart",+ extensions=frozenset({".dart"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="zig",+ display_name="Zig",+ extensions=frozenset({".zig"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="julia",+ display_name="Julia",+ extensions=frozenset({".jl"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="clojure",+ display_name="Clojure",+ extensions=frozenset({".clj", ".cljs", ".cljc"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="elm",+ display_name="Elm",+ extensions=frozenset({".elm"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="haskell",+ display_name="Haskell",+ extensions=frozenset({".hs", ".lhs"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="ocaml",+ display_name="OCaml",+ extensions=frozenset({".ml", ".mli"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="fsharp",+ display_name="F#",+ extensions=frozenset({".fs", ".fsi", ".fsx"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="crystal",+ display_name="Crystal",+ extensions=frozenset({".cr"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="nim",+ display_name="Nim",+ extensions=frozenset({".nim"}),+ is_passthrough=True,+ ),+ LanguageSpec(+ tag="dlang",+ display_name="D",+ extensions=frozenset({".d"}),+ is_passthrough=True,+ ),+ # Sentinel for unclassified files+ LanguageSpec(+ tag="unknown",+ display_name="Unknown",+ is_code=False,+ is_passthrough=True,+ ),+)+++# =========================================================================+# LanguageRegistry+# =========================================================================+++class LanguageRegistry:+ """Central registry. All language-specific lookups go through here.++ Instantiated once at module level as ``REGISTRY``. The registry is+ immutable after construction — all data comes from ``_SPECS``.+ """++ __slots__ = ("_ext_map", "_filename_map", "_specs")++ def __init__(self, specs: tuple[LanguageSpec, ...] = _SPECS) -> None:+ self._specs: dict[str, LanguageSpec] = {s.tag: s for s in specs}++ # Build extension → tag map (first spec wins if extensions overlap)+ self._ext_map: dict[str, str] = {}+ for spec in specs:+ for ext in spec.extensions:+ if ext not in self._ext_map:+ self._ext_map[ext] = spec.tag++ # Build special filename → tag map+ self._filename_map: dict[str, str] = {}+ for spec in specs:+ for fn in spec.special_filenames:+ if fn not in self._filename_map:+ self._filename_map[fn] = spec.tag++ # -- Single-spec lookups ---------------------------------------------++ def get(self, tag: str) -> LanguageSpec | None:+ """Return the spec for a language tag, or None."""+ return self._specs.get(tag)++ def from_extension(self, ext: str) -> str:+ """Return the language tag for a file extension, or ``'unknown'``."""+ return self._ext_map.get(ext, "unknown")++ def from_filename(self, name: str) -> str | None:+ """Return the language tag for a special filename, or None."""+ return self._filename_map.get(name)++ # -- Aggregated lookups ----------------------------------------------++ def all_extensions(self) -> dict[str, str]:+ """Return ``{ext: tag}`` for all registered extensions."""+ return dict(self._ext_map)++ def all_special_filenames(self) -> dict[str, str]:+ """Return ``{filename: tag}`` for all special filenames."""+ return dict(self._filename_map)++ def all_code_extensions(self) -> frozenset[str]:+ """Return extensions for all ``is_code=True`` languages."""+ return frozenset(+ ext for spec in self._specs.values() if spec.is_code for ext in spec.extensions+ )++ def code_languages(self) -> frozenset[str]:+ """Return tags for code languages (not config/markup/data)."""+ return frozenset(s.tag for s in self._specs.values() if s.is_code and not s.is_passthrough)++ def config_languages(self) -> frozenset[str]:+ """Return tags for non-code languages (config/markup/data)."""+ return frozenset(s.tag for s in self._specs.values() if not s.is_code)++ def passthrough_languages(self) -> frozenset[str]:+ """Return tags for languages with no AST parser."""+ return frozenset(s.tag for s in self._specs.values() if s.is_passthrough)++ def infra_languages(self) -> frozenset[str]:+ """Return tags for infrastructure languages."""+ return frozenset(s.tag for s in self._specs.values() if s.is_infra)++ def entry_point_names(self) -> frozenset[str]:+ """Return the union of all entry-point filename patterns."""+ return frozenset(p for s in self._specs.values() for p in s.entry_point_patterns)++ def manifest_filenames(self) -> frozenset[str]:+ """Return the union of all manifest filenames."""+ return frozenset(f for s in self._specs.values() for f in s.manifest_files)++ def blocked_dirs(self) -> frozenset[str]:+ """Return the union of all per-language blocked directories."""+ return frozenset(d for s in self._specs.values() for d in s.blocked_dirs)++ def generated_suffixes(self) -> frozenset[str]:+ """Return the union of all generated-file suffixes."""+ return frozenset(sf for s in self._specs.values() for sf in s.generated_suffixes)++ def extensions_for(self, tags: Iterable[str]) -> frozenset[str]:+ """Return extensions for a specific set of language tags."""+ tag_set = set(tags)+ return frozenset(+ ext for spec in self._specs.values() if spec.tag in tag_set for ext in spec.extensions+ )++ def all_specs(self) -> list[LanguageSpec]:+ """Return all registered specs."""+ return list(self._specs.values())+++# Module-level singleton+REGISTRY = LanguageRegistry()diff --git a/packages/core/src/repowise/core/ingestion/languages/spec.py b/packages/core/src/repowise/core/ingestion/languages/spec.pynew file mode 100644index 000000000..31e332f16--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/languages/spec.py@@ -0,0 +1,59 @@+"""Language specification dataclass — pure data, no behaviour.++``LanguageSpec`` captures everything repowise needs to know about a+language's *identity*: file extensions, classification flags, ecosystem+metadata, builtin symbols, and display properties.++It deliberately excludes parser-specific concerns (tree-sitter node-type+mappings, visibility functions, extractor callables) which belong in+``parser.py``'s ``LanguageConfig``. This separation keeps the registry+a leaf dependency — it imports nothing from the ingestion pipeline.+"""++from __future__ import annotations++from dataclasses import dataclass, field+++@dataclass(frozen=True)+class LanguageSpec:+ """Complete identity specification for a single language."""++ # -- Identity --------------------------------------------------------+ tag: str # matches LanguageTag literal+ display_name: str # "Python", "C#", "C/C++"++ # -- File matching ---------------------------------------------------+ extensions: frozenset[str] = field(default_factory=frozenset) # (".py", ".pyi")+ special_filenames: frozenset[str] = field(default_factory=frozenset) # ("Dockerfile",)++ # -- Classification --------------------------------------------------+ is_code: bool = True # False for yaml, json, markdown, etc.+ is_infra: bool = False # True for dockerfile, makefile, terraform, shell+ is_passthrough: bool = False # True = no AST parser (config/data/markup)+ is_api_contract: bool = False # True for proto, graphql, openapi++ # -- Tree-sitter -----------------------------------------------------+ grammar_package: str | None = None # "tree_sitter_python"+ grammar_loader: str = "language" # function name in grammar package+ scm_file: str | None = None # "python.scm" — None = no AST queries+ shares_grammar_with: str | None = None # C shares cpp grammar++ # -- Heritage --------------------------------------------------------+ heritage_node_types: frozenset[str] = field(default_factory=frozenset)++ # -- Ecosystem -------------------------------------------------------+ entry_point_patterns: tuple[str, ...] = () # ("main.py", "app.py")+ manifest_files: tuple[str, ...] = () # ("pyproject.toml",)+ lock_files: tuple[str, ...] = () # ("poetry.lock",)+ generated_suffixes: tuple[str, ...] = () # ("_pb2.py",)+ shebang_tokens: tuple[str, ...] = () # ("python",)+ blocked_dirs: tuple[str, ...] = () # ("__pycache__",)+ blocked_extensions: tuple[str, ...] = () # (".pyc",)++ # -- Builtins --------------------------------------------------------+ builtin_calls: frozenset[str] = field(default_factory=frozenset)+ builtin_parents: frozenset[str] = field(default_factory=frozenset)++ # -- Display ---------------------------------------------------------+ color_hex: str = "#8b5cf6" # fallback purple ("other")diff --git a/packages/core/src/repowise/core/ingestion/models.py b/packages/core/src/repowise/core/ingestion/models.pyindex e3aa0fab7..71691d14a 100644--- a/packages/core/src/repowise/core/ingestion/models.py+++ b/packages/core/src/repowise/core/ingestion/models.py@@ -10,7 +10,9 @@ from __future__ import annotationsimport hashlibfrom dataclasses import dataclass, fieldfrom datetime import datetime-from typing import Literal+from typing import Literal, get_args++from .languages.registry import REGISTRY as _REGISTRY# ---------------------------------------------------------------------------# Language tags@@ -48,55 +50,24 @@ LanguageTag = Literal[# ---------------------------------------------------------------------------# Extension → language map (used by FileTraverser and ASTParser)+#+# Derived from the centralised LanguageRegistry. Only the extensions+# known to the original LanguageTag set are included here — the registry+# also covers extra git-blame-only languages.# ---------------------------------------------------------------------------+_LANGUAGE_TAG_VALUES: frozenset[str] = frozenset(get_args(LanguageTag))+EXTENSION_TO_LANGUAGE: dict[str, LanguageTag] = {- ".py": "python",- ".pyi": "python",- ".ts": "typescript",- ".tsx": "typescript",- ".js": "javascript",- ".jsx": "javascript",- ".mjs": "javascript",- ".cjs": "javascript",- ".go": "go",- ".rs": "rust",- ".java": "java",- ".cpp": "cpp",- ".cc": "cpp",- ".cxx": "cpp",- ".c": "c",- ".h": "cpp",- ".hpp": "cpp",- ".cs": "csharp",- ".rb": "ruby",- ".php": "php",- ".swift": "swift",- ".kt": "kotlin",- ".scala": "scala",- ".sh": "shell",- ".bash": "shell",- ".zsh": "shell",- ".yaml": "yaml",- ".yml": "yaml",- ".json": "json",- ".toml": "toml",- ".proto": "proto",- ".graphql": "graphql",- ".gql": "graphql",- ".tf": "terraform",- ".hcl": "terraform",- ".md": "markdown",- ".mdx": "markdown",- ".sql": "sql",+ ext: tag # type: ignore[misc]+ for ext, tag in _REGISTRY.all_extensions().items()+ if tag in _LANGUAGE_TAG_VALUES}SPECIAL_FILENAMES: dict[str, LanguageTag] = {- "Dockerfile": "dockerfile",- "dockerfile": "dockerfile",- "Makefile": "makefile",- "makefile": "makefile",- "GNUmakefile": "makefile",+ fn: tag # type: ignore[misc]+ for fn, tag in _REGISTRY.all_special_filenames().items()+ if tag in _LANGUAGE_TAG_VALUES}# ---------------------------------------------------------------------------diff --git a/packages/core/src/repowise/core/ingestion/parser.py b/packages/core/src/repowise/core/ingestion/parser.pyindex e7d6f0a96..deb214d8c 100644--- a/packages/core/src/repowise/core/ingestion/parser.py+++ b/packages/core/src/repowise/core/ingestion/parser.py@@ -31,12 +31,35 @@ from pathlib import Pathimport structlogfrom tree_sitter import Language, Node, Parser+from .extractors import (+ build_signature,+ extract_go_receiver_type,+ extract_heritage,+ extract_import_bindings,+ extract_module_docstring,+ extract_symbol_docstring,+ node_text,+ refine_go_type_kind,+ refine_kotlin_class_kind,+)+from .extractors.visibility import (+ csharp_visibility,+ go_visibility,+ java_visibility,+ kotlin_visibility,+ php_visibility,+ public_by_default,+ py_visibility,+ rust_visibility,+ scala_visibility,+ swift_visibility,+ ts_visibility,+)+from .languages.registry import REGISTRY as _LANG_REGISTRYfrom .models import (CallSite,FileInfo,- HeritageRelation,Import,- NamedBinding,ParsedFile,Symbol,)@@ -45,24 +68,17 @@ log = structlog.get_logger(__name__)QUERIES_DIR = Path(__file__).parent / "queries"-# Languages that intentionally have no AST parser. These are data, config,-# markup, or query files — there are no code symbols to extract, and that is-# expected. parse_file() returns an empty ParsedFile for them silently.-# Keep this list in sync with EXTENSION_TO_LANGUAGE in models.py.+# Languages that intentionally have no AST parser. Derived from the+# centralised LanguageRegistry — only non-code passthrough languages are+# included (not the extra git-blame-only languages).++# Excludes "openapi" (handled by special_handlers) and "unknown"._PASSTHROUGH_LANGUAGES: frozenset[str] = frozenset(- {- "json",- "yaml",- "toml",- "markdown",- "sql",- "shell",- "terraform",- "proto",- "graphql",- "dockerfile",- "makefile",- }+ 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 not in ("openapi", "unknown"))# ---------------------------------------------------------------------------@@ -71,44 +87,44 @@ _PASSTHROUGH_LANGUAGES: frozenset[str] = frozenset(def _build_language_registry() -> dict[str, Language]:- """Lazily load installed tree-sitter language packages."""- registry: dict[str, Language] = {}-- def _try_load(tag: str, loader: Callable[[], Language]) -> None:- try:- registry[tag] = loader()- except Exception as exc: # ImportError, AttributeError, …- log.debug("tree-sitter language unavailable", language=tag, reason=str(exc))+ """Lazily load installed tree-sitter language packages.- _try_load("python", lambda: Language(__import__("tree_sitter_python").language()))-- def _ts() -> None:- import tree_sitter_typescript as ts-- registry["typescript"] = Language(ts.language_typescript())- registry["tsx"] = Language(ts.language_tsx())+ Driven by ``LanguageSpec.grammar_package`` / ``grammar_loader`` /+ ``shares_grammar_with`` from the centralised registry.+ """+ registry: dict[str, Language] = {}- try:- _ts()- except Exception as exc:- log.debug("tree-sitter language unavailable", language="typescript", reason=str(exc))+ for spec in _LANG_REGISTRY.all_specs():+ # Languages that share another's grammar (e.g. C → cpp)+ if spec.shares_grammar_with:+ shared = registry.get(spec.shares_grammar_with)+ if shared:+ registry[spec.tag] = shared+ continue- _try_load("javascript", lambda: Language(__import__("tree_sitter_javascript").language()))- _try_load("go", lambda: Language(__import__("tree_sitter_go").language()))- _try_load("rust", lambda: Language(__import__("tree_sitter_rust").language()))- _try_load("java", lambda: Language(__import__("tree_sitter_java").language()))+ if not spec.grammar_package:+ continue- def _cpp() -> None:- import tree_sitter_cpp as ts_cpp+ try:+ mod = __import__(spec.grammar_package)+ loader_fn = getattr(mod, spec.grammar_loader)+ lang_obj = Language(loader_fn())+ registry[spec.tag] = lang_obj+ except Exception as exc:+ log.debug(+ "tree-sitter language unavailable",+ language=spec.tag,+ reason=str(exc),+ )- lang = Language(ts_cpp.language())- registry["cpp"] = lang- registry["c"] = lang # C is a subset of C++ for our purposes+ # TypeScript's tsx variant — special case: same package, different loader+ if "typescript" in registry and "tsx" not in registry:+ try:+ import tree_sitter_typescript as _ts_mod- try:- _cpp()- except Exception as exc:- log.debug("tree-sitter language unavailable", language="cpp", reason=str(exc))+ registry["tsx"] = Language(_ts_mod.language_tsx())+ except Exception as exc:+ log.debug("tree-sitter language unavailable", language="tsx", reason=str(exc))return registry@@ -127,6 +143,9 @@ def _get_language(tag: str) -> Language | None:# LanguageConfig# ---------------------------------------------------------------------------+# Private alias for internal use (kept for compatibility with _find_parent)+_node_text = node_text+@dataclassclass LanguageConfig:@@ -162,44 +181,6 @@ class LanguageConfig:entry_point_patterns: list[str] = field(default_factory=list)-def _py_visibility(name: str, _mods: list[str]) -> str:- if name.startswith("__") and name.endswith("__"):- return "public" # dunder- if name.startswith("_"):- return "private"- return "public"---def _ts_visibility(_name: str, mods: list[str]) -> str:- mods_lower = [m.lower() for m in mods]- if "private" in mods_lower:- return "private"- if "protected" in mods_lower:- return "protected"- return "public"---def _go_visibility(name: str, _mods: list[str]) -> str:- return "public" if name and name[0].isupper() else "private"---def _rust_visibility(_name: str, mods: list[str]) -> str:- return "public" if any("pub" in m for m in mods) else "private"---def _java_visibility(_name: str, mods: list[str]) -> str:- combined = " ".join(mods).lower()- if "private" in combined:- return "private"- if "protected" in combined:- return "protected"- return "public"---def _public_by_default(_name: str, _mods: list[str]) -> str:- return "public"--LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {"python": LanguageConfig(symbol_node_types={@@ -208,7 +189,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {},import_node_types=["import_statement", "import_from_statement"],export_node_types=[],- visibility_fn=_py_visibility,+ visibility_fn=py_visibility,parent_extraction="nesting",parent_class_types=frozenset({"class_definition"}),entry_point_patterns=["main.py", "app.py", "__main__.py", "manage.py", "wsgi.py"],@@ -228,7 +209,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {},import_node_types=["import_statement"],export_node_types=["export_statement"],- visibility_fn=_ts_visibility,+ visibility_fn=ts_visibility,parent_extraction="nesting",parent_class_types=frozenset({"class_declaration", "abstract_class_declaration"}),entry_point_patterns=["index.ts", "main.ts", "app.ts", "server.ts"],@@ -244,7 +225,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {},import_node_types=["import_statement"],export_node_types=["export_statement"],- visibility_fn=_public_by_default,+ visibility_fn=public_by_default,parent_extraction="nesting",parent_class_types=frozenset({"class_declaration"}),entry_point_patterns=["index.js", "main.js", "app.js", "server.js"],@@ -259,7 +240,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {},import_node_types=["import_declaration"],export_node_types=[],- visibility_fn=_go_visibility,+ visibility_fn=go_visibility,parent_extraction="receiver",parent_class_types=frozenset(),entry_point_patterns=["main.go", "cmd/main.go"],@@ -278,7 +259,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {},import_node_types=["use_declaration"],export_node_types=[],- visibility_fn=_rust_visibility,+ visibility_fn=rust_visibility,parent_extraction="impl",parent_class_types=frozenset({"impl_item"}),entry_point_patterns=["main.rs", "lib.rs"],@@ -293,7 +274,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {},import_node_types=["import_declaration"],export_node_types=[],- visibility_fn=_java_visibility,+ visibility_fn=java_visibility,parent_extraction="nesting",parent_class_types=frozenset({"class_declaration", "interface_declaration", "enum_declaration"}@@ -315,7 +296,7 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {},import_node_types=["preproc_include"],export_node_types=[],- visibility_fn=_public_by_default,+ visibility_fn=public_by_default,parent_extraction="nesting",parent_class_types=frozenset({"class_specifier", "struct_specifier"}),entry_point_patterns=["main.cpp", "main.cc"],@@ -332,11 +313,106 @@ LANGUAGE_CONFIGS: dict[str, LanguageConfig] = {},import_node_types=["preproc_include"],export_node_types=[],- visibility_fn=_public_by_default,+ visibility_fn=public_by_default,parent_extraction="none",parent_class_types=frozenset(),entry_point_patterns=["main.c"],),+ "kotlin": LanguageConfig(+ symbol_node_types={+ "function_declaration": "function",+ "class_declaration": "class",+ "object_declaration": "class",+ },+ import_node_types=["import"],+ export_node_types=[],+ visibility_fn=kotlin_visibility,+ parent_extraction="nesting",+ parent_class_types=frozenset({"class_declaration", "object_declaration"}),+ entry_point_patterns=["Main.kt", "Application.kt"],+ ),+ "ruby": LanguageConfig(+ symbol_node_types={+ "method": "function",+ "singleton_method": "function",+ "class": "class",+ "module": "module",+ },+ import_node_types=["call"],+ export_node_types=[],+ visibility_fn=public_by_default,+ parent_extraction="nesting",+ parent_class_types=frozenset({"class", "module"}),+ entry_point_patterns=["main.rb", "app.rb", "config.ru"],+ ),+ "csharp": LanguageConfig(+ symbol_node_types={+ "class_declaration": "class",+ "interface_declaration": "interface",+ "struct_declaration": "struct",+ "enum_declaration": "enum",+ "method_declaration": "method",+ "constructor_declaration": "function",+ "property_declaration": "variable",+ },+ import_node_types=["using_directive"],+ export_node_types=[],+ visibility_fn=csharp_visibility,+ parent_extraction="nesting",+ parent_class_types=frozenset(+ {"class_declaration", "interface_declaration", "struct_declaration", "enum_declaration"}+ ),+ entry_point_patterns=["Program.cs", "Startup.cs"],+ ),+ "swift": LanguageConfig(+ symbol_node_types={+ "class_declaration": "class",+ "protocol_declaration": "interface",+ "function_declaration": "function",+ "protocol_function_declaration": "function",+ "property_declaration": "variable",+ },+ import_node_types=["import_declaration"],+ export_node_types=[],+ visibility_fn=swift_visibility,+ parent_extraction="nesting",+ parent_class_types=frozenset({"class_declaration", "protocol_declaration"}),+ entry_point_patterns=["main.swift", "App.swift"],+ ),+ "scala": LanguageConfig(+ symbol_node_types={+ "class_definition": "class",+ "trait_definition": "trait",+ "object_definition": "class",+ "function_definition": "function",+ "function_declaration": "function",+ "val_definition": "variable",+ },+ import_node_types=["import_declaration"],+ export_node_types=[],+ visibility_fn=scala_visibility,+ parent_extraction="nesting",+ parent_class_types=frozenset({"class_definition", "trait_definition", "object_definition"}),+ entry_point_patterns=["Main.scala", "App.scala"],+ ),+ "php": LanguageConfig(+ symbol_node_types={+ "class_declaration": "class",+ "interface_declaration": "interface",+ "trait_declaration": "trait",+ "enum_declaration": "enum",+ "method_declaration": "method",+ "function_definition": "function",+ },+ import_node_types=["namespace_use_declaration"],+ export_node_types=[],+ visibility_fn=php_visibility,+ parent_extraction="nesting",+ parent_class_types=frozenset(+ {"class_declaration", "interface_declaration", "trait_declaration", "enum_declaration"}+ ),+ entry_point_patterns=["index.php", "public/index.php"],+ ),}@@ -370,11 +446,6 @@ class ASTParser:language = _get_language(lang)if config is None or language is None:- # If the language has a LANGUAGE_CONFIGS entry but its tree-sitter- # grammar failed to load, that is unexpected — log it once per file- # so developers can investigate. For all other cases (data files,- # markup, config, languages not yet supported) this is intentional- # and we return silently without spamming the log.if config is not None and language is None:log.debug("tree-sitter grammar unavailable",@@ -407,9 +478,9 @@ class ASTParser:symbols = self._extract_symbols(tree, query, config, file_info, src)imports = self._extract_imports(tree, query, config, file_info, src)calls = self._extract_calls(tree, query, config, file_info, src, symbols)- heritage = _extract_heritage(tree, query, config, file_info, src)+ heritage = extract_heritage(tree, query, config, file_info, src, run_query=_run_query)exports = self._derive_exports(symbols, config, src)- docstring = _extract_module_docstring(root, src, lang)+ docstring = extract_module_docstring(root, src, lang)return ParsedFile(file_info=file_info,@@ -431,8 +502,7 @@ class ASTParser:if lang in self._query_cache:return self._query_cache[lang]- # C files reuse the cpp query- scm_lang = "cpp" if lang == "c" else lang+ scm_lang = langscm_path = QUERIES_DIR / f"{scm_lang}.scm"if not scm_path.exists():@@ -500,14 +570,17 @@ class ASTParser:# Refine "struct" kind for Go type_spec (check if struct or interface body)if kind == "struct" and config.parent_extraction == "receiver":- kind = _refine_go_type_kind(def_node, src)+ kind = refine_go_type_kind(def_node, src)++ # Refine "class" kind for Kotlin (interface / enum class share class_declaration)+ if kind == "class" and file_info.language == "kotlin" and def_node.type == "class_declaration":+ kind = refine_kotlin_class_kind(def_node)# Params signature textparams_text = _node_text(params_nodes[0], src) if params_nodes else ""# Visibilitymodifier_texts = [_node_text(m, src) for m in modifier_nodes]- # Also check if parent in decorated_definition has decoratorsif def_node.parent and def_node.parent.type == "decorated_definition":for sibling in def_node.parent.children:if sibling.type == "decorator":@@ -522,10 +595,10 @@ class ASTParser:kind = "method"# Build signature- signature = _build_signature(node_type, name, params_text, def_node, src)+ signature = build_signature(node_type, name, params_text, def_node, src)- # Docstring — walk the body of the def_node- docstring = _extract_symbol_docstring(def_node, src, file_info.language)+ # Docstring+ docstring = extract_symbol_docstring(def_node, src, file_info.language)# Async detectionis_async = _is_async_node(def_node, src)@@ -568,7 +641,7 @@ class ASTParser:if config.parent_extraction == "receiver":# Go: extract type name from receiver parameter listif receiver_nodes:- return _extract_go_receiver_type(_node_text(receiver_nodes[0], src))+ return extract_go_receiver_type(_node_text(receiver_nodes[0], src))return Noneif config.parent_extraction in ("nesting", "impl"):@@ -622,9 +695,7 @@ class ASTParser:continue# Language-specific import name + binding extraction- imported_names, bindings = _extract_import_bindings(- stmt_node, src, file_info.language- )+ imported_names, bindings = extract_import_bindings(stmt_node, src, file_info.language)is_relative = module_text.startswith(".") or module_text.startswith("./")imports.append(@@ -653,13 +724,7 @@ class ASTParser:src: str,symbols: list[Symbol],) -> list[CallSite]:- """Extract function/method call sites from the AST.-- Uses @call.target, @call.receiver, and @call.arguments captures- defined in the .scm query files. Each call is associated with its- enclosing symbol (caller) by checking which symbol's line range- contains the call site.- """+ """Extract function/method call sites from the AST."""if query is None:return []@@ -667,15 +732,13 @@ class ASTParser:_call_builtins = get_builtin_calls(file_info.language)- # Build a sorted list of (start_line, end_line, symbol_id) for- # fast enclosing-symbol lookup via binary search.symbol_ranges = sorted([(s.start_line, s.end_line, s.id) for s in symbols],- key=lambda t: (t[0], -t[1]), # start asc, widest span first+ key=lambda t: (t[0], -t[1]),)calls: list[CallSite] = []- seen: set[tuple[int, str, str | None]] = set() # (line, target, receiver) dedup+ seen: set[tuple[int, str, str | None]] = set()for capture_dict in _run_query(query, tree.root_node): # type: ignore[attr-defined]site_nodes = capture_dict.get("call.site", [])@@ -691,29 +754,22 @@ class ASTParser:if not target_name:continue- # Skip language builtins — they pollute the call graph- # because Tier 3 global resolution can match them to- # unrelated user symbols with the same name.if target_name in _call_builtins:continue- line = site_node.start_point[0] + 1 # 1-indexed+ line = site_node.start_point[0] + 1receiver_name = _node_text(receiver_nodes[0], src).strip() if receiver_nodes else None- # Dedup: same line + target + receiver means same call captured- # by multiple overlapping query patternsdedup_key = (line, target_name, receiver_name)if dedup_key in seen:continueseen.add(dedup_key)- # Count argumentsarg_count: int | None = Noneif arg_nodes:arg_node = arg_nodes[0]arg_count = _count_arguments(arg_node)- # Find enclosing symbolcaller_id = _find_enclosing_symbol(line, symbol_ranges)calls.append(@@ -740,9 +796,7 @@ class ASTParser:) -> list[str]:"""Derive the list of exported names from parsed symbols."""if config.export_node_types:- # Languages with explicit exports (TS, JS) — public top-level symbolsreturn [s.name for s in symbols if s.visibility == "public" and s.parent_name is None]- # Languages where all top-level public symbols are exported (Python, Go, …)return [s.name for s in symbols if s.visibility == "public" and s.parent_name is None]@@ -767,11 +821,7 @@ def parse_file(file_info: FileInfo, source: bytes) -> ParsedFile:def _run_query(query: object, root_node: Node) -> list[dict[str, list[Node]]]:- """Execute a tree-sitter query and return a list of capture dicts.-- Handles both the legacy tuple API and the newer QueryMatch API across- tree-sitter versions >= 0.22.- """+ """Execute a tree-sitter query and return a list of capture dicts."""results: list[dict[str, list[Node]]] = []try:from tree_sitter import QueryCursor # type: ignore[attr-defined]@@ -779,13 +829,11 @@ def _run_query(query: object, root_node: Node) -> list[dict[str, list[Node]]]:cursor = QueryCursor(query) # type: ignore[call-arg]for match in cursor.matches(root_node):if hasattr(match, "captures"):- # tree-sitter >= 0.23: QueryMatch objectresults.append(match.captures)elif isinstance(match, tuple) and len(match) == 2:_, caps = matchresults.append(caps)except Exception:- # Fallback: query.matches() returning list of (index, dict) tuplestry:for item in query.matches(root_node): # type: ignore[attr-defined]if isinstance(item, tuple) and len(item) == 2:@@ -796,14 +844,6 @@ def _run_query(query: object, root_node: Node) -> list[dict[str, list[Node]]]:return results-def _node_text(node: Node | None, src: str) -> str:- if node is None:- return ""- if node.text is not None:- return node.text.decode("utf-8", errors="replace")- return src[node.start_byte : node.end_byte]--def _collect_error_nodes(root: Node) -> list[str]:"""Return error descriptions for any ERROR nodes in the tree."""errors: list[str] = []@@ -818,911 +858,10 @@ def _collect_error_nodes(root: Node) -> list[str]:return errors-def _extract_module_docstring(root: Node, src: str, lang: str) -> str | None:- """Extract a module/file-level docstring or leading comment."""- if lang == "python":- for child in root.children:- if child.type == "expression_statement":- for sub in child.children:- if sub.type == "string":- return _clean_string_literal(_node_text(sub, src))- break- elif child.type not in (- "comment",- "newline",- "import_statement",- "import_from_statement",- "future_import_statement",- ):- break- elif lang in ("typescript", "javascript"):- # Look for leading /** ... */ comment- for child in root.children:- if child.type == "comment":- text = _node_text(child, src).strip()- if text.startswith("/**"):- return _clean_jsdoc(text)- elif child.type not in ("comment",):- break- elif lang == "go":- # Package comment is a series of // lines before package_clause- lines: list[str] = []- for child in root.children:- if child.type == "comment":- lines.append(_node_text(child, src).lstrip("/ ").strip())- elif child.type == "package_clause":- break- return "\n".join(lines) if lines else None- elif lang == "rust":- # //! inner doc comments or /// outer doc comments at top- for child in root.children:- if child.type in ("line_comment", "block_comment"):- text = _node_text(child, src).strip()- if text.startswith("//!") or text.startswith("/*!"):- return text.lstrip("/!* ").strip()- else:- break- return None---def _extract_symbol_docstring(def_node: Node, src: str, lang: str) -> str | None:- """Extract the docstring from a symbol's body node."""- if lang == "python":- body = def_node.child_by_field_name("body")- if body is None:- return None- for child in body.children:- if child.type == "expression_statement":- for sub in child.children:- if sub.type == "string":- return _clean_string_literal(_node_text(sub, src))- return None- elif child.type not in ("comment", "newline"):- return None- return None-- elif lang in ("typescript", "javascript"):- return _find_preceding_jsdoc(def_node, src)-- elif lang == "go":- # Leading // comment lines before the function- 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":- lines.insert(0, _node_text(siblings[i], src).lstrip("/ ").strip())- i -= 1- return "\n".join(lines) if lines else None-- elif lang == "rust":- # /// doc comments before the item- 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 in ("line_comment", "block_comment"):- text = _node_text(siblings[i], src).strip()- if text.startswith("///"):- lines.insert(0, text.lstrip("/ ").strip())- i -= 1- else:- break- return "\n".join(lines) if lines else None-- elif lang == "java":- # /** Javadoc */ comment before the method/class- return _find_preceding_block_comment(def_node, src, "/**")-- return None---def _build_signature(node_type: str, name: str, params_text: str, def_node: Node, src: str) -> str:- """Build a human-readable signature string."""- # Helper: try multiple field names for "return type", fall back gracefully.- def _ret(fields: tuple[str, ...]) -> str:- for f in fields:- n = def_node.child_by_field_name(f)- if n is not None:- return f" -> {_node_text(n, src)}"- return ""-- if node_type == "function_definition":- # Detect async via child "async" keyword (tree-sitter-python >= 0.23)- prefix = "async " if any(c.type == "async" for c in def_node.children) else ""- return f"{prefix}def {name}{params_text}{_ret(('return_type',))}"- if node_type == "function_item":- # Rust: return_type field- return f"fn {name}{params_text}{_ret(('return_type',))}"- if node_type in ("function_declaration", "generator_function_declaration"):- # TS/JS use return_type; Go uses result- return f"function {name}{params_text}{_ret(('return_type', 'result'))}"- if node_type in ("class_definition", "class_declaration", "abstract_class_declaration"):- base = f"class {name}"- if params_text:- base += params_text- return base- if node_type == "interface_declaration":- return f"interface {name}"- if node_type == "type_alias_declaration":- return f"type {name}"- if node_type == "enum_declaration":- return f"enum {name}"- if node_type == "method_definition":- # TypeScript/JavaScript class method- return f"{name}{params_text}{_ret(('return_type',))}"- if node_type == "method_declaration":- # Go method: include receiver text and result type- recv_node = def_node.child_by_field_name("receiver")- recv_text = _node_text(recv_node, src) if recv_node else ""- recv_prefix = f"{recv_text} " if recv_text else ""- return f"func {recv_prefix}{name}{params_text}{_ret(('result',))}"- if node_type in ("struct_item", "struct_specifier"):- return f"struct {name}"- if node_type in ("enum_item", "enum_specifier"):- return f"enum {name}"- if node_type == "trait_item":- return f"trait {name}"- if node_type == "impl_item":- return f"impl {name}"- if node_type in ("class_specifier",):- return f"class {name}"- # Fallback- return f"{name}{params_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.- """- names: list[str] = []- bindings: list[NamedBinding] = []-- 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)-- return names, bindings---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 [], []---# ----------------------------------------------------------------------------# Heritage (inheritance / interface implementation) extraction-# -----------------------------------------------------------------------------# Maps language → set of node types that can have heritage info-_HERITAGE_NODE_TYPES: dict[str, frozenset[str]] = {- "python": frozenset({"class_definition"}),- "typescript": frozenset({"class_declaration", "abstract_class_declaration", "interface_declaration"}),- "javascript": frozenset({"class_declaration"}),- "java": frozenset({"class_declaration", "interface_declaration", "enum_declaration"}),- "go": frozenset({"type_spec"}),- "rust": frozenset({"impl_item", "trait_item"}),- "cpp": frozenset({"class_specifier", "struct_specifier"}),- "c": frozenset(),- "kotlin": frozenset({"class_declaration", "object_declaration"}),- "ruby": frozenset({"class"}),- "csharp": frozenset({"class_declaration", "interface_declaration", "struct_declaration"}),-}---def _extract_heritage(- tree: object,- query: object,- config: "LanguageConfig",- file_info: "FileInfo",- src: str,-) -> 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- heritage_types = _HERITAGE_NODE_TYPES.get(lang, frozenset())- 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 — they carry no architectural- # signal and pollute the heritage graph.- if _parent_builtins:- relations = [r for r in relations if r.parent_name not in _parent_builtins]-- return relations---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:- # Also check for argument_list child (some grammar versions)- 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- # Skip keyword arguments like metaclass=Meta- if child.type == "keyword_argument":- continue- parent = _node_text(child, src).strip()- if parent:- # Strip module prefix for qualified names (e.g., abc.ABC → ABC)- 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()- # Strip 'extends' keyword if captured- 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_spec → type field is the body (struct_type or interface_type)- 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- # Embedded field: no name, just a type- 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:- # This is an embedded field- 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":- # Interface embedding: interface { io.Reader }- for child in type_node.children:- if child.type in ("{", "}", "\n"):- continue- # Embedded interfaces appear as type names without method signatures- 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."""- if def_node.type == "impl_item":- # Check for 'impl Trait for Type' pattern- 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":- # trait Foo: Bar + Baz (supertrait bounds)- 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,- ))---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- # base_class_clause children may include access specifiers- text = _node_text(base, src).strip()- # Strip access specifier (public/protected/private/virtual)- 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()- # Remove constructor call parens- 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."""- superclass = def_node.child_by_field_name("superclass")- if superclass:- parent = _node_text(superclass, src).strip()- # Strip the '<' if it was captured- parent = parent.removeprefix("<").strip()- bare = parent.split("::")[-1]- if bare:- out.append(HeritageRelation(- child_name=name, parent_name=bare, 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."""- for child in def_node.children:- if child.type == "base_list":- for base in child.children:- if base.type in (":", ","):- continue- text = _node_text(base, src).strip()- bare = text.split(".")[-1].split("<")[0].strip()- if bare and bare != name:- # Convention: interfaces start with I- kind = "implements" if bare.startswith("I") and len(bare) > 1 and bare[1].isupper() else "extends"- out.append(HeritageRelation(- child_name=name, parent_name=bare, kind=kind, line=line,- ))---_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,-}---def _extract_go_receiver_type(receiver_text: str) -> str | None:- """Extract 'Calculator' from '(c *Calculator)' or '(c Calculator)'."""- text = receiver_text.strip("() ")- parts = text.split()- for part in reversed(parts):- clean = part.lstrip("*")- if clean and clean[0].isupper():- return clean- return None---def _refine_go_type_kind(type_spec_node: Node, src: str) -> str:- """Refine the generic 'struct' kind for Go type_spec nodes."""- type_node = type_spec_node.child_by_field_name("type")- if type_node is None:- return "struct"- type_text = _node_text(type_node, src).strip()- if type_text.startswith("struct"):- return "struct"- if type_text.startswith("interface"):- return "interface"- return "type_alias"--def _is_async_node(node: Node, src: str) -> bool:return node.type == "async_function_definition" or any(c.type == "async" for c in node.children)-def _clean_string_literal(text: str) -> str:- text = text.strip()- for triple in ('"""', "'''"):- if text.startswith(triple) and text.endswith(triple) and len(text) >= 6:- return text[3:-3].strip()- for q in ('"', "'"):- if text.startswith(q) and text.endswith(q) and len(text) >= 2:- return text[1:-1].strip()- return text---def _find_preceding_jsdoc(node: Node, src: str) -> str | None:- parent = node.parent- if parent is None:- return None- siblings = list(parent.children)- idx = next((i for i, s in enumerate(siblings) if s.id == node.id), -1)- if idx <= 0:- return None- prev = siblings[idx - 1]- if prev.type == "comment":- text = _node_text(prev, src).strip()- if text.startswith("/**"):- return _clean_jsdoc(text)- return None---def _find_preceding_block_comment(node: Node, src: str, prefix: str) -> str | None:- parent = node.parent- if parent is None:- return None- siblings = list(parent.children)- idx = next((i for i, s in enumerate(siblings) if s.id == node.id), -1)- if idx <= 0:- return None- prev = siblings[idx - 1]- if prev.type in ("block_comment", "comment"):- text = _node_text(prev, src).strip()- if text.startswith(prefix):- return _clean_jsdoc(text)- return None---def _clean_jsdoc(text: str) -> str:- lines = text.splitlines()- cleaned: list[str] = []- for line in lines:- line = line.strip().lstrip("/*").lstrip()- if line:- cleaned.append(line)- return "\n".join(cleaned).strip()--def _build_qualified_name(file_path: str, parent_name: str | None, name: str) -> str:module = Path(file_path).with_suffix("").as_posix().replace("/", ".")if parent_name:@@ -1736,32 +875,22 @@ def _build_qualified_name(file_path: str, parent_name: str | None, name: str) ->def _count_arguments(arg_node: Node) -> int:- """Count the number of arguments in an argument/argument_list node.-- Skips punctuation children (commas, parens) and counts only- substantive argument nodes.- """- _SKIP_TYPES = frozenset({"(", ")", ",", "[", "]"})- return sum(1 for child in arg_node.children if child.type not in _SKIP_TYPES)+ """Count the number of arguments in an argument/argument_list node."""+ skip_types = frozenset({"(", ")", ",", "[", "]"})+ return sum(1 for child in arg_node.children if child.type not in skip_types)def _find_enclosing_symbol(line: int,symbol_ranges: list[tuple[int, int, str]],) -> str | None:- """Find the innermost symbol whose line range contains *line*.-- Uses a linear scan on the pre-sorted ranges. For typical file sizes- (< 500 symbols) this is faster than bisect due to low constant factor.- Returns the tightest (smallest span) enclosing symbol ID, or None if- the call is at module level.- """+ """Find the innermost symbol whose line range contains *line*."""best_id: str | None = Nonebest_span = float("inf")for start, end, sym_id in symbol_ranges:if start > line:- break # ranges sorted by start_line — no further match possible+ breakif start <= line <= end:span = end - startif span < best_span:diff --git a/packages/core/src/repowise/core/ingestion/parsers/__init__.py b/packages/core/src/repowise/core/ingestion/parsers/__init__.pydeleted file mode 100644index 6973ed266..000000000--- a/packages/core/src/repowise/core/ingestion/parsers/__init__.py+++ /dev/null@@ -1,4 +0,0 @@-# This directory is intentionally empty.-# Language-specific parsing is handled by the unified ASTParser in-# repowise.core.ingestion.parser using per-language .scm query files-# in packages/core/queries/.diff --git a/packages/core/src/repowise/core/ingestion/parsers/base.py b/packages/core/src/repowise/core/ingestion/parsers/base.pydeleted file mode 100644index 42eeaea61..000000000--- a/packages/core/src/repowise/core/ingestion/parsers/base.py+++ /dev/null@@ -1,3 +0,0 @@-# Replaced by the unified ASTParser architecture.-# See packages/core/src/repowise/core/ingestion/parser.py and-# packages/core/queries/*.scm for the current implementation.diff --git a/packages/core/src/repowise/core/ingestion/parsers/go.py b/packages/core/src/repowise/core/ingestion/parsers/go.pydeleted file mode 100644index 52d633244..000000000--- a/packages/core/src/repowise/core/ingestion/parsers/go.py+++ /dev/null@@ -1,2 +0,0 @@-# Replaced by the unified ASTParser architecture.-# See packages/core/queries/go.scm for the symbol/import queries.diff --git a/packages/core/src/repowise/core/ingestion/parsers/python.py b/packages/core/src/repowise/core/ingestion/parsers/python.pydeleted file mode 100644index 8b6e1042e..000000000--- a/packages/core/src/repowise/core/ingestion/parsers/python.py+++ /dev/null@@ -1,2 +0,0 @@-# Replaced by the unified ASTParser architecture.-# See packages/core/queries/python.scm for the symbol/import queries.diff --git a/packages/core/src/repowise/core/ingestion/parsers/typescript.py b/packages/core/src/repowise/core/ingestion/parsers/typescript.pydeleted file mode 100644index 2767ca9d5..000000000--- a/packages/core/src/repowise/core/ingestion/parsers/typescript.py+++ /dev/null@@ -1,2 +0,0 @@-# Replaced by the unified ASTParser architecture.-# See packages/core/queries/typescript.scm and javascript.scm.diff --git a/packages/core/src/repowise/core/ingestion/queries/c.scm b/packages/core/src/repowise/core/ingestion/queries/c.scmindex eb8e36020..a0962b91a 100644--- a/packages/core/src/repowise/core/ingestion/queries/c.scm+++ b/packages/core/src/repowise/core/ingestion/queries/c.scm@@ -64,3 +64,22 @@(preproc_includepath: (string_literal) @import.module) @import.statement++; ---------------------------------------------------------------------------+; Calls+; ---------------------------------------------------------------------------++; Simple function call: foo(args)+(call_expression+ function: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; Field call: ptr->func(args) or obj.func(args)+(call_expression+ function: (field_expression+ argument: (identifier) @call.receiver+ field: (field_identifier) @call.target+ )+ arguments: (argument_list) @call.arguments+) @call.sitediff --git a/packages/core/src/repowise/core/ingestion/queries/csharp.scm b/packages/core/src/repowise/core/ingestion/queries/csharp.scmnew file mode 100644index 000000000..38b347c56--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/queries/csharp.scm@@ -0,0 +1,116 @@+; =============================================================================+; repowise — C# symbol, import, and call queries+; tree-sitter-c-sharp >= 0.23+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols — modifier-capturing patterns first (dedup keeps first match)+; ---------------------------------------------------------------------------++(class_declaration+ (modifier) @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++(interface_declaration+ (modifier) @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++(struct_declaration+ (modifier) @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++(enum_declaration+ (modifier) @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++(method_declaration+ (modifier) @symbol.modifiers+ name: (identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+) @symbol.def++(constructor_declaration+ (modifier) @symbol.modifiers+ name: (identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+) @symbol.def++(property_declaration+ (modifier) @symbol.modifiers+ name: (identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Symbols — fallback without modifiers+; ---------------------------------------------------------------------------++(class_declaration+ name: (identifier) @symbol.name+) @symbol.def++(interface_declaration+ name: (identifier) @symbol.name+) @symbol.def++(struct_declaration+ name: (identifier) @symbol.name+) @symbol.def++(enum_declaration+ name: (identifier) @symbol.name+) @symbol.def++(method_declaration+ name: (identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+) @symbol.def++(constructor_declaration+ name: (identifier) @symbol.name+ parameters: (parameter_list) @symbol.params+) @symbol.def++(property_declaration+ name: (identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Imports (using directives)+; ---------------------------------------------------------------------------++(using_directive+ (identifier) @import.module+) @import.statement++(using_directive+ (qualified_name) @import.module+) @import.statement++; ---------------------------------------------------------------------------+; Calls+; ---------------------------------------------------------------------------++; Simple call: Method(args)+(invocation_expression+ function: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; Member call: obj.Method(args)+(invocation_expression+ function: (member_access_expression+ expression: (identifier) @call.receiver+ name: (identifier) @call.target+ )+ arguments: (argument_list) @call.arguments+) @call.site++; Constructor: new ClassName(args)+(object_creation_expression+ type: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.sitediff --git a/packages/core/src/repowise/core/ingestion/queries/kotlin.scm b/packages/core/src/repowise/core/ingestion/queries/kotlin.scmindex 6190b04ab..585c6b133 100644--- a/packages/core/src/repowise/core/ingestion/queries/kotlin.scm+++ b/packages/core/src/repowise/core/ingestion/queries/kotlin.scm@@ -1,25 +1,49 @@; =============================================================================-; repowise — Kotlin symbol and import queries-; tree-sitter-kotlin (install separately if needed)+; repowise — Kotlin symbol, import, and call queries+; tree-sitter-kotlin >= 1.0; =============================================================================+; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------+(function_declaration- (simple_identifier) @symbol.name+ (modifiers)? @symbol.modifiers+ (identifier) @symbol.name(function_value_parameters) @symbol.params) @symbol.def(class_declaration- (type_identifier) @symbol.name+ (identifier) @symbol.name) @symbol.def(object_declaration- (type_identifier) @symbol.name+ (identifier) @symbol.name) @symbol.def-(interface_declaration- (type_identifier) @symbol.name-) @symbol.def+; ---------------------------------------------------------------------------+; Imports+; ----------------------------------------------------------------------------(import_header- (identifier) @import.module+(import+ (qualified_identifier) @import.module) @import.statement++; ---------------------------------------------------------------------------+; Calls+; ---------------------------------------------------------------------------++; Simple call: foo(args)+(call_expression+ (identifier) @call.target+ (value_arguments) @call.arguments+) @call.site++; Member call: obj.method(args)+(call_expression+ (navigation_expression+ (identifier) @call.receiver+ (identifier) @call.target+ )+ (value_arguments) @call.arguments+) @call.sitediff --git a/packages/core/src/repowise/core/ingestion/queries/php.scm b/packages/core/src/repowise/core/ingestion/queries/php.scmnew file mode 100644index 000000000..5fed1da73--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/queries/php.scm@@ -0,0 +1,101 @@+; =============================================================================+; repowise — PHP symbol, import, and call queries+; tree-sitter-php >= 0.23 (uses language_php())+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++(class_declaration+ name: (name) @symbol.name+) @symbol.def++(interface_declaration+ name: (name) @symbol.name+) @symbol.def++(trait_declaration+ name: (name) @symbol.name+) @symbol.def++(enum_declaration+ name: (name) @symbol.name+) @symbol.def++(method_declaration+ (visibility_modifier) @symbol.modifiers+ name: (name) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++; Fallback: methods without explicit visibility (defaults to public in PHP)+(method_declaration+ name: (name) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++(function_definition+ name: (name) @symbol.name+ parameters: (formal_parameters) @symbol.params+) @symbol.def++; ---------------------------------------------------------------------------+; Imports (use declarations + require/include)+; ---------------------------------------------------------------------------++(namespace_use_declaration+ (namespace_use_clause+ (qualified_name) @import.module+ )+) @import.statement++; require/include file imports+(require_expression (encapsed_string (string_content) @import.module)) @import.statement+(require_once_expression (encapsed_string (string_content) @import.module)) @import.statement+(include_expression (encapsed_string (string_content) @import.module)) @import.statement+(include_once_expression (encapsed_string (string_content) @import.module)) @import.statement++; ---------------------------------------------------------------------------+; Calls+; ---------------------------------------------------------------------------++; Function call: func(args)+(function_call_expression+ function: (name) @call.target+ (arguments) @call.arguments+) @call.site++; Qualified function call: Namespace\func(args)+(function_call_expression+ function: (qualified_name+ (name) @call.target+ )+ (arguments) @call.arguments+) @call.site++; Method call: $obj->method(args)+(member_call_expression+ name: (name) @call.target+ (arguments) @call.arguments+) @call.site++; Static call: ClassName::method(args)+(scoped_call_expression+ name: (name) @call.target+ (arguments) @call.arguments+) @call.site++; Constructor: new ClassName(args)+(object_creation_expression+ (qualified_name+ (name) @call.target+ )+ (arguments) @call.arguments+) @call.site++; Constructor (simple name): new ClassName(args)+(object_creation_expression+ (name) @call.target+ (arguments) @call.arguments+) @call.sitediff --git a/packages/core/src/repowise/core/ingestion/queries/ruby.scm b/packages/core/src/repowise/core/ingestion/queries/ruby.scmindex 05de0efcd..922e27f2f 100644--- a/packages/core/src/repowise/core/ingestion/queries/ruby.scm+++ b/packages/core/src/repowise/core/ingestion/queries/ruby.scm@@ -28,3 +28,25 @@)(#match? @_require_method "^require")) @import.statement++; ---------------------------------------------------------------------------+; Calls+; ---------------------------------------------------------------------------++; Simple call: foo(args)+(call+ method: (identifier) @call.target+ arguments: (argument_list) @call.arguments+) @call.site++; Class/module method call: ClassName.method(args)+(call+ receiver: (constant) @call.receiver+ method: (identifier) @call.target+) @call.site++; Method call on variable: obj.method(args)+(call+ receiver: (identifier) @call.receiver+ method: (identifier) @call.target+) @call.sitediff --git a/packages/core/src/repowise/core/ingestion/queries/scala.scm b/packages/core/src/repowise/core/ingestion/queries/scala.scmnew file mode 100644index 000000000..da63b8b1c--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/queries/scala.scm@@ -0,0 +1,61 @@+; =============================================================================+; repowise — Scala symbol, import, and call queries+; tree-sitter-scala >= 0.23+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols+; ---------------------------------------------------------------------------++(class_definition+ name: (identifier) @symbol.name+) @symbol.def++(trait_definition+ name: (identifier) @symbol.name+) @symbol.def++(object_definition+ name: (identifier) @symbol.name+) @symbol.def++(function_definition+ name: (identifier) @symbol.name+ (parameters) @symbol.params+) @symbol.def++(function_declaration+ name: (identifier) @symbol.name+ (parameters) @symbol.params+) @symbol.def++(val_definition+ pattern: (identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Imports+; ---------------------------------------------------------------------------++(import_declaration+ (identifier) @import.module+) @import.statement++; ---------------------------------------------------------------------------+; Calls+; ---------------------------------------------------------------------------++; Simple call: foo(args)+(call_expression+ function: (identifier) @call.target+ arguments: (arguments) @call.arguments+) @call.site++; Member call: obj.method(args) — uses select_expression in tree-sitter-scala+(call_expression+ function: (field_expression+ value: (identifier) @call.receiver+ field: (identifier) @call.target+ )+ arguments: (arguments) @call.arguments+) @call.sitediff --git a/packages/core/src/repowise/core/ingestion/queries/swift.scm b/packages/core/src/repowise/core/ingestion/queries/swift.scmnew file mode 100644index 000000000..d68147c77--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/queries/swift.scm@@ -0,0 +1,81 @@+; =============================================================================+; repowise — Swift symbol, import, and call queries+; tree-sitter-swift+; =============================================================================++; ---------------------------------------------------------------------------+; Symbols — with modifiers (priority: these come first so dedup keeps them)+; ---------------------------------------------------------------------------++(function_declaration+ (modifiers) @symbol.modifiers+ (simple_identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Symbols — without modifiers (fallback)+; ---------------------------------------------------------------------------++; class/struct/enum all use class_declaration+(class_declaration+ (type_identifier) @symbol.name+) @symbol.def++; extension Foo: Protocol — name is nested under user_type+(class_declaration+ (user_type+ (type_identifier) @symbol.name+ )+) @symbol.def++(protocol_declaration+ (type_identifier) @symbol.name+) @symbol.def++(function_declaration+ (simple_identifier) @symbol.name+) @symbol.def++(property_declaration+ (pattern+ (simple_identifier) @symbol.name+ )+) @symbol.def++; Protocol method declarations+(protocol_function_declaration+ (simple_identifier) @symbol.name+) @symbol.def++; ---------------------------------------------------------------------------+; Imports+; ---------------------------------------------------------------------------++(import_declaration+ (identifier) @import.module+) @import.statement++; ---------------------------------------------------------------------------+; Calls+; ---------------------------------------------------------------------------++; Simple call: foo(args)+(call_expression+ (simple_identifier) @call.target+ (call_suffix+ (value_arguments) @call.arguments+ )+) @call.site++; Member call: obj.method(args)+(call_expression+ (navigation_expression+ (simple_identifier) @call.receiver+ (navigation_suffix+ (simple_identifier) @call.target+ )+ )+ (call_suffix+ (value_arguments) @call.arguments+ )+) @call.sitediff --git a/packages/core/src/repowise/core/ingestion/resolvers/__init__.py b/packages/core/src/repowise/core/ingestion/resolvers/__init__.pynew file mode 100644index 000000000..462492e1f--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/__init__.py@@ -0,0 +1,56 @@+"""Per-language import resolution dispatch."""++from __future__ import annotations++from collections.abc import Callable++from .context import ResolverContext+from .cpp import resolve_cpp_import+from .csharp import resolve_csharp_import+from .generic import resolve_generic_import+from .go import resolve_go_import+from .kotlin import resolve_kotlin_import+from .php import resolve_php_import+from .python import resolve_python_import+from .ruby import resolve_ruby_import+from .rust import resolve_rust_import+from .scala import resolve_scala_import+from .swift import resolve_swift_import+from .typescript import resolve_ts_js_import++ResolverFn = Callable[[str, str, ResolverContext], str | None]++_RESOLVERS: dict[str, ResolverFn] = {+ "python": resolve_python_import,+ "typescript": resolve_ts_js_import,+ "javascript": resolve_ts_js_import,+ "go": resolve_go_import,+ "rust": resolve_rust_import,+ "cpp": resolve_cpp_import,+ "c": resolve_cpp_import,+ "kotlin": resolve_kotlin_import,+ "ruby": resolve_ruby_import,+ "csharp": resolve_csharp_import,+ "swift": resolve_swift_import,+ "scala": resolve_scala_import,+ "php": resolve_php_import,+}+++def resolve_import(+ module_path: str,+ importer_path: str,+ language: str,+ ctx: ResolverContext,+) -> str | None:+ """Dispatch to the appropriate language resolver, or fall back to generic."""+ if not module_path:+ return None+ resolver = _RESOLVERS.get(language, resolve_generic_import)+ return resolver(module_path, importer_path, ctx)+++__all__ = [+ "ResolverContext",+ "resolve_import",+]diff --git a/packages/core/src/repowise/core/ingestion/resolvers/context.py b/packages/core/src/repowise/core/ingestion/resolvers/context.pynew file mode 100644index 000000000..13c437549--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/context.py@@ -0,0 +1,131 @@+"""Shared context for import resolver functions."""++from __future__ import annotations++import json+import shlex+from dataclasses import dataclass, field+from pathlib import Path+from typing import Any++import networkx as nx+import structlog++log = structlog.get_logger(__name__)+++@dataclass+class ResolverContext:+ """State shared across all per-language import resolver functions.++ Constructed once per ``GraphBuilder.build()`` invocation and passed to+ every ``resolve_*_import()`` call.+ """++ path_set: set[str]+ stem_map: dict[str, list[str]]+ graph: nx.DiGraph+ repo_path: Path | None = None++ # Language-specific state+ tsconfig_resolver: Any | None = None+ go_module_path: str | None = None+ parsed_files: dict | None = None # for Rust crate root detection+ compile_commands_cache: dict[str, dict] | None = field(default=None, repr=False)++ 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 add_external_node(self, module_path: str) -> str:+ """Register an external dependency node and return its key."""+ key = f"external:{module_path}"+ if key not in self.graph.nodes:+ self.graph.add_node(key, language="external", symbol_count=0, has_error=False)+ return key++ # ------------------------------------------------------------------+ # C/C++ compile_commands helpers (cached on the context)+ # ------------------------------------------------------------------++ def load_compile_commands(self) -> dict[str, dict] | None:+ """Load and cache compile_commands.json if present in the repo."""+ if self.compile_commands_cache is not None:+ return self.compile_commands_cache+ if not self.repo_path:+ return None+ for candidate in [+ self.repo_path / "compile_commands.json",+ self.repo_path / "build" / "compile_commands.json",+ ]:+ if candidate.exists():+ try:+ with open(candidate) as f:+ commands = json.load(f)+ result: dict[str, dict] = {}+ for entry in commands:+ file_path = Path(entry.get("file", ""))+ if file_path.is_absolute():+ try:+ file_rel = file_path.relative_to(self.repo_path)+ except ValueError:+ continue+ else:+ file_rel = file_path+ result[file_rel.as_posix()] = entry+ if result:+ self.compile_commands_cache = result+ log.info(+ "Loaded compile_commands.json",+ path=str(candidate),+ entries=len(self.compile_commands_cache),+ )+ return self.compile_commands_cache+ log.debug(+ "compile_commands.json had no resolvable entries", path=str(candidate)+ )+ except Exception as exc:+ log.debug("Failed to load compile_commands.json", error=str(exc))+ return None++ def extract_include_dirs(self, source_file: str) -> list[str]:+ """Return absolute include directories for *source_file* from compile_commands.json."""+ commands = self.load_compile_commands()+ if not commands or source_file not in commands:+ return []+ entry = commands[source_file]+ cmd_dir = Path(entry.get("directory", str(self.repo_path or "")))+ if "arguments" in entry:+ tokens = list(entry["arguments"])+ else:+ command = entry.get("command", "")+ try:+ tokens = shlex.split(command)+ except ValueError:+ return []+ include_dirs: list[str] = []+ i = 0+ while i < len(tokens):+ tok = tokens[i]+ if tok in ("-I", "-isystem", "-iquote"):+ if i + 1 < len(tokens):+ include_dirs.append(tokens[i + 1])+ i += 2+ else:+ i += 1+ elif tok.startswith("-I") and len(tok) > 2:+ include_dirs.append(tok[2:])+ i += 1+ elif tok.startswith("-isystem") and len(tok) > 8:+ include_dirs.append(tok[8:])+ i += 1+ else:+ i += 1+ result: list[str] = []+ for d in include_dirs:+ p = Path(d)+ if not p.is_absolute():+ p = cmd_dir / p+ result.append(str(p.resolve()))+ return resultdiff --git a/packages/core/src/repowise/core/ingestion/resolvers/cpp.py b/packages/core/src/repowise/core/ingestion/resolvers/cpp.pynew file mode 100644index 000000000..fb9ed326c--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/cpp.py@@ -0,0 +1,37 @@+"""C / C++ import resolution."""++from __future__ import annotations++from pathlib import Path++from .context import ResolverContext+++def resolve_cpp_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:+ """Resolve a C/C++ ``#include`` to a repo-relative file path."""+ importer_dir = Path(importer_path).parent+ repo_root = ctx.repo_path.resolve() if ctx.repo_path else None++ # 1. Try compile_commands.json include paths+ for inc_dir in ctx.extract_include_dirs(importer_path):+ candidate = (Path(inc_dir) / module_path).resolve()+ if repo_root:+ try:+ rel = candidate.relative_to(repo_root).as_posix()+ if rel in ctx.path_set:+ return rel+ except ValueError:+ pass++ # 2. Try relative to the importer's directory+ if repo_root:+ try:+ rel = (importer_dir / module_path).resolve().relative_to(repo_root).as_posix()+ if rel in ctx.path_set:+ return rel+ except ValueError:+ pass++ # 3. Stem-matching fallback+ stem = Path(module_path).stem.lower()+ return ctx.stem_lookup(stem)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/csharp.py b/packages/core/src/repowise/core/ingestion/resolvers/csharp.pynew file mode 100644index 000000000..38a35a6be--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/csharp.py@@ -0,0 +1,25 @@+"""C# import resolution."""++from __future__ import annotations++from .context import ResolverContext+++def resolve_csharp_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:+ """Resolve a C# using directive to a repo-relative file path."""+ parts = module_path.split(".")+ local = parts[-1]++ # Try stem lookup on the last namespace component+ result = ctx.stem_lookup(local.lower())+ if result and result.endswith(".cs"):+ return result++ # Try matching namespace components as directory path+ if len(parts) > 1:+ dir_suffix = "/".join(parts)+ for p in ctx.path_set:+ if p.endswith(".cs") and dir_suffix.lower() in p.lower():+ return p++ return ctx.add_external_node(module_path)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/generic.py b/packages/core/src/repowise/core/ingestion/resolvers/generic.pynew file mode 100644index 000000000..55a586e98--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/generic.py@@ -0,0 +1,15 @@+"""Generic stem-based import resolution fallback."""++from __future__ import annotations++from pathlib import Path++from .context import ResolverContext+++def resolve_generic_import(+ module_path: str, importer_path: str, ctx: ResolverContext+) -> str | None:+ """Fall back to stem matching for unsupported languages."""+ stem = Path(module_path).stem.lower()+ return ctx.stem_lookup(stem)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/go.py b/packages/core/src/repowise/core/ingestion/resolvers/go.pynew file mode 100644index 000000000..9a2786f12--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/go.py@@ -0,0 +1,54 @@+"""Go import resolution."""++from __future__ import annotations++from pathlib import Path++from .context import ResolverContext+++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+ try:+ for line in go_mod.read_text(encoding="utf-8", errors="ignore").splitlines():+ line = line.strip()+ if line.startswith("module "):+ return line.split(None, 1)[1].strip()+ except Exception:+ pass+ return None+++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+ 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}"):+ return p+ # Try stem matching as fallback for the package name+ pkg_name = rel_dir.rsplit("/", 1)[-1].lower() if rel_dir 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+ stem = module_path.rsplit("/", 1)[-1].lower()+ result = ctx.stem_lookup(stem)+ if result:+ return result++ # External package+ return ctx.add_external_node(module_path)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.pynew file mode 100644index 000000000..4249b2bfb--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/kotlin.py@@ -0,0 +1,32 @@+"""Kotlin import resolution."""++from __future__ import annotations++from pathlib import PurePosixPath++from .context import ResolverContext+++def resolve_kotlin_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:+ """Resolve a Kotlin import to a repo-relative file path."""+ parts = module_path.split(".")+ local = parts[-1]++ if local == "*":+ return None++ # Try stem lookup on the class/function name+ result = ctx.stem_lookup(local.lower())+ if result and (result.endswith(".kt") or result.endswith(".kts")):+ return result++ # Try matching the package path as a directory structure+ if len(parts) > 1:+ dir_suffix = "/".join(parts[:-1])+ for p in ctx.path_set:+ if p.endswith(".kt") and dir_suffix in p:+ stem = PurePosixPath(p).stem+ if stem.lower() == local.lower():+ return p++ return ctx.add_external_node(module_path)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/php.py b/packages/core/src/repowise/core/ingestion/resolvers/php.pynew file mode 100644index 000000000..6256b15cf--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/php.py@@ -0,0 +1,26 @@+"""PHP import resolution."""++from __future__ import annotations++from .context import ResolverContext+++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."""+ # Convert namespace separators to path separators+ path_form = module_path.replace("\\", "/")+ parts = path_form.split("/")+ local = parts[-1]++ # Try stem lookup on the class name+ result = ctx.stem_lookup(local.lower())+ if result and result.endswith(".php"):+ return result++ # Try PSR-4 style: namespace path maps to directory+ php_name = f"{local}.php"+ for p in ctx.path_set:+ if p.endswith(php_name):+ return p++ return ctx.add_external_node(module_path)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/python.py b/packages/core/src/repowise/core/ingestion/resolvers/python.pynew file mode 100644index 000000000..7e3924a31--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/python.py@@ -0,0 +1,44 @@+"""Python import resolution."""++from __future__ import annotations++from pathlib import Path++from .context import ResolverContext+++def resolve_python_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:+ """Resolve a Python import to a repo-relative file path."""+ importer_dir = Path(importer_path).parent++ # Relative import: ".sibling" or "..parent.module"+ if module_path.startswith("."):+ dots = len(module_path) - len(module_path.lstrip("."))+ rest = module_path[dots:].replace(".", "/")+ base = importer_dir+ for _ in range(dots - 1):+ base = base.parent+ candidates = [+ (base / rest).with_suffix(".py").as_posix() if rest else None,+ (base / rest / "__init__.py").as_posix() if rest else None,+ ]+ for c in candidates:+ if c and c in ctx.path_set:+ return c+ return None++ # Absolute import: try obvious filesystem layouts+ dotted = module_path.replace(".", "/")+ candidates = [+ f"{dotted}.py",+ f"{dotted}/__init__.py",+ f"src/{dotted}.py",+ f"src/{dotted}/__init__.py",+ ]+ for c in candidates:+ if c in ctx.path_set:+ return c++ # Stem-only fallback+ stem = module_path.split(".")[-1].lower()+ return ctx.stem_lookup(stem)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/ruby.py b/packages/core/src/repowise/core/ingestion/resolvers/ruby.pynew file mode 100644index 000000000..d447d9f67--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/ruby.py@@ -0,0 +1,34 @@+"""Ruby import resolution."""++from __future__ import annotations++from pathlib import PurePosixPath++from .context import ResolverContext+++def resolve_ruby_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:+ """Resolve a Ruby require/require_relative to a repo-relative file path."""+ # require_relative uses paths relative to the current file+ if module_path.startswith("."):+ importer_dir = PurePosixPath(importer_path).parent+ candidate = (importer_dir / module_path).as_posix()+ # Try with .rb extension+ for suffix in (".rb", ""):+ full = f"{candidate}{suffix}"+ if full in ctx.path_set:+ return full++ # Try stem lookup+ stem = PurePosixPath(module_path).stem.lower().replace("-", "_")+ result = ctx.stem_lookup(stem)+ if result and result.endswith(".rb"):+ return result++ # Try matching the path directly+ rb_name = f"{module_path}.rb"+ for p in ctx.path_set:+ if p.endswith(rb_name) or PurePosixPath(p).name == PurePosixPath(rb_name).name:+ return p++ return ctx.add_external_node(module_path)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/rust.py b/packages/core/src/repowise/core/ingestion/resolvers/rust.pynew file mode 100644index 000000000..5ccf1cc07--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/rust.py@@ -0,0 +1,86 @@+"""Rust import resolution."""++from __future__ import annotations++from pathlib import Path++from .context import ResolverContext+++def resolve_rust_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:+ """Resolve a Rust ``use`` path to a repo-relative file."""+ parts = module_path.split("::")+ if not parts:+ return None++ prefix = parts[0]++ # --- crate:: — resolve from the crate root ---+ if prefix == "crate":+ crate_root = _find_rust_crate_root(importer_path, ctx)+ return _probe_rust_path(crate_root, parts[1:], ctx.path_set)++ # --- self:: — resolve from the current module's directory ---+ if prefix == "self":+ importer_dir = str(Path(importer_path).parent.as_posix())+ return _probe_rust_path(importer_dir, parts[1:], ctx.path_set)++ # --- super:: — resolve from the parent directory ---+ if prefix == "super":+ parent_dir = str(Path(importer_path).parent.parent.as_posix())+ return _probe_rust_path(parent_dir, parts[1:], ctx.path_set)++ # --- External crate (no prefix or unknown crate name) ---+ # Check if it might be a local module at the crate root first+ crate_root = _find_rust_crate_root(importer_path, ctx)+ resolved = _probe_rust_path(crate_root, parts, ctx.path_set)+ if resolved is not None:+ return resolved++ # External crate+ return ctx.add_external_node(module_path)+++def _find_rust_crate_root(importer_path: str, ctx: ResolverContext) -> str:+ """Find the ``src/`` directory containing the importer (Rust crate root)."""+ parsed_files = ctx.parsed_files or {}+ parts = Path(importer_path).parts+ for i in range(len(parts) - 1, -1, -1):+ candidate_dir = Path(*parts[:i]) if i > 0 else Path(".")+ for root_file in ("lib.rs", "main.rs"):+ root_path = (candidate_dir / root_file).as_posix()+ if root_path in parsed_files:+ return candidate_dir.as_posix()+ if parts[i] == "src" and i > 0:+ return candidate_dir.as_posix()+ return Path(importer_path).parent.as_posix()+++def _probe_rust_path(+ base_dir: str,+ path_parts: list[str],+ path_set: set[str],+) -> str | None:+ """Probe for a Rust module path, trying ``.rs`` and ``mod.rs`` variants."""+ if not path_parts:+ return None++ base = Path(base_dir)++ for depth in range(len(path_parts), 0, -1):+ module_parts = path_parts[:depth]+ module_dir = base+ for p in module_parts[:-1]:+ module_dir = module_dir / p++ last = module_parts[-1]+ # Try <dir>/<last>.rs+ candidate = (module_dir / f"{last}.rs").as_posix()+ if candidate in path_set:+ return candidate+ # Try <dir>/<last>/mod.rs+ candidate = (module_dir / last / "mod.rs").as_posix()+ if candidate in path_set:+ return candidate++ return Nonediff --git a/packages/core/src/repowise/core/ingestion/resolvers/scala.py b/packages/core/src/repowise/core/ingestion/resolvers/scala.pynew file mode 100644index 000000000..4b4d12ec3--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/scala.py@@ -0,0 +1,30 @@+"""Scala import resolution."""++from __future__ import annotations++from .context import ResolverContext+++def resolve_scala_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:+ """Resolve a Scala import to a repo-relative file path."""+ parts = module_path.split(".")+ local = parts[-1]++ if local in ("*", "_"):+ return None++ # Try stem lookup on the last name component+ result = ctx.stem_lookup(local.lower())+ if result and result.endswith(".scala"):+ return result++ # Try matching package path as directory structure+ if len(parts) > 1:+ dir_suffix = "/".join(parts[:-1])+ for p in ctx.path_set:+ if p.endswith(".scala") and dir_suffix.lower() in p.lower():+ stem = p.rsplit("/", 1)[-1].rsplit(".", 1)[0]+ if stem.lower() == local.lower():+ return p++ return ctx.add_external_node(module_path)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/swift.py b/packages/core/src/repowise/core/ingestion/resolvers/swift.pynew file mode 100644index 000000000..30973cc21--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/swift.py@@ -0,0 +1,27 @@+"""Swift import resolution."""++from __future__ import annotations++from pathlib import PurePosixPath++from .context import ResolverContext+++def resolve_swift_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:+ """Resolve a Swift import to a repo-relative file path."""+ parts = module_path.split(".")+ local = parts[-1]++ # Try stem lookup+ result = ctx.stem_lookup(local.lower())+ if result and result.endswith(".swift"):+ return result++ # Look for directory matching module name+ for p in ctx.path_set:+ if p.endswith(".swift"):+ parent_name = PurePosixPath(p).parent.name.lower()+ if parent_name == module_path.lower():+ return p++ return ctx.add_external_node(module_path)diff --git a/packages/core/src/repowise/core/ingestion/resolvers/typescript.py b/packages/core/src/repowise/core/ingestion/resolvers/typescript.pynew file mode 100644index 000000000..1717f2561--- /dev/null+++ b/packages/core/src/repowise/core/ingestion/resolvers/typescript.py@@ -0,0 +1,37 @@+"""TypeScript / JavaScript import resolution."""++from __future__ import annotations++from pathlib import Path++from .context import ResolverContext+++def resolve_ts_js_import(module_path: str, importer_path: str, ctx: ResolverContext) -> str | None:+ """Resolve a TypeScript or JavaScript import to a repo-relative file path."""+ importer_dir = Path(importer_path).parent++ if module_path.startswith("."):+ base = importer_dir / module_path+ for ext in (".ts", ".tsx", ".js", ".jsx", "/index.ts", "/index.js"):+ candidate = Path(str(base) + ext).as_posix()+ if candidate in ctx.path_set:+ return candidate+ candidate = (+ base.with_suffix(ext).as_posix()+ if not ext.startswith("/")+ else (base / "index.ts").as_posix()+ )+ if candidate in ctx.path_set:+ return candidate+ return None++ # Non-relative: try tsconfig path-alias resolution first.+ if ctx.tsconfig_resolver is not None:+ importer_abs = str(ctx.repo_path / importer_path) if ctx.repo_path else importer_path+ alias_resolved = ctx.tsconfig_resolver.resolve(module_path, importer_abs)+ if alias_resolved is not None:+ return alias_resolved++ # Fallback: external npm package.+ return ctx.add_external_node(module_path)diff --git a/packages/core/src/repowise/core/ingestion/traverser.py b/packages/core/src/repowise/core/ingestion/traverser.pyindex 79f15c4a8..a78bbdffa 100644--- a/packages/core/src/repowise/core/ingestion/traverser.py+++ b/packages/core/src/repowise/core/ingestion/traverser.py@@ -25,6 +25,7 @@ from pathlib import Pathimport pathspecimport structlog+from .languages.registry import REGISTRY as _LANG_REGISTRYfrom .models import (EXTENSION_TO_LANGUAGE,SPECIAL_FILENAMES,@@ -34,7 +35,6 @@ from .models import (RepoStructure,)-# ---------------------------------------------------------------------------# Traversal statistics# ---------------------------------------------------------------------------@@ -141,13 +141,7 @@ _GENERATED_MARKERS: tuple[str, ...] = ("@generated",)-_GENERATED_SUFFIXES: tuple[str, ...] = (- "_pb2.py",- "_pb2_grpc.py",- "_pb.ts",- "_pb.js",- "_grpc.pb.go",-)+_GENERATED_SUFFIXES: tuple[str, ...] = tuple(_LANG_REGISTRY.generated_suffixes())# Manifest files that indicate a package root (for monorepo detection)_MANIFEST_FILES: frozenset[str] = frozenset(@@ -159,25 +153,8 @@ _ENTRY_POINT_STEMS: frozenset[str] = frozenset({"main", "index", "app", "run", "server", "start", "wsgi", "asgi"})-_ENTRY_POINT_NAMES: frozenset[str] = frozenset(- {- "main.py",- "app.py",- "run.py",- "server.py",- "wsgi.py",- "asgi.py",- "index.ts",- "index.js",- "main.ts",- "main.js",- "app.ts",- "main.go",- "main.rs",- "lib.rs",- "Main.java",- "Application.java",- }+_ENTRY_POINT_NAMES: frozenset[str] = _LANG_REGISTRY.entry_point_names() | frozenset(+ {"run.py", "server.py"} # extra traverser-specific patterns not in language specs)# Default file-size limit@@ -186,20 +163,14 @@ _DEFAULT_MAX_FILE_SIZE_BYTES: int = 500 * 1024 # 500 KB# Languages for which generated-file detection is skipped. These files have# no AST parsing anyway, so reading 512 bytes to check for generated markers# adds no value.+# Languages for which generated-file detection is skipped — same as parser's+# passthrough set (no AST parsing, so reading 512 bytes for markers is pointless)._SKIP_GENERATED_CHECK: frozenset[str] = frozenset(- {- "json",- "yaml",- "toml",- "markdown",- "sql",- "shell",- "terraform",- "proto",- "graphql",- "dockerfile",- "makefile",- }+ 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 not in ("openapi", "unknown"))@@ -517,14 +488,10 @@ def _detect_by_shebang(abs_path: Path) -> LanguageTag:first_line = f.readline(200)if not first_line.startswith("#!"):return "unknown"- if "python" in first_line:- return "python"- if "node" in first_line:- return "javascript"- if "bash" in first_line or " sh" in first_line:- return "shell"- if "ruby" in first_line:- return "ruby"+ for spec in _LANG_REGISTRY.all_specs():+ for token in spec.shebang_tokens:+ if token in first_line:+ return spec.tag # type: ignore[return-value]except OSError:passreturn "unknown"diff --git a/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.py b/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.pyindex 71d5d0a92..e11b3da44 100644--- a/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.py+++ b/packages/core/src/repowise/core/workspace/extractors/grpc_extractor.py@@ -13,6 +13,8 @@ import refrom pathlib import Pathfrom typing import TYPE_CHECKING+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY+if TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -22,19 +24,35 @@ _log = logging.getLogger("repowise.workspace.extractors.grpc")# Constants# ----------------------------------------------------------------------------_BLOCKED_DIRS = frozenset({- ".git", "node_modules", "__pycache__", ".venv", "venv",- "dist", "build", "target", "vendor", ".next", ".nuxt",- ".tox", ".mypy_cache", ".gradle", ".mvn", "out", "bin",-})+_BLOCKED_DIRS = frozenset(+ {+ ".git",+ "node_modules",+ "__pycache__",+ ".venv",+ "venv",+ "dist",+ "build",+ "target",+ "vendor",+ ".next",+ ".nuxt",+ ".tox",+ ".mypy_cache",+ ".gradle",+ ".mvn",+ "out",+ "bin",+ }+)_MAX_FILE_SIZE = 512 * 1024-_PROTO_EXTENSIONS = frozenset({".proto"})+_PROTO_EXTENSIONS = _LANG_REGISTRY.extensions_for(["proto"])-_SOURCE_EXTENSIONS = frozenset({- ".go", ".java", ".py", ".ts", ".tsx", ".js", ".jsx",-})+_SOURCE_EXTENSIONS = _LANG_REGISTRY.extensions_for(+ ["go", "java", "python", "typescript", "javascript"]+)_ALL_EXTENSIONS = _PROTO_EXTENSIONS | _SOURCE_EXTENSIONS@@ -149,10 +167,7 @@ class GrpcExtractor:repo_root = repo_path.resolve()for dirpath, dirnames, filenames in os.walk(repo_root):- dirnames[:] = [- d for d in dirnames- if d not in _BLOCKED_DIRS and not d.startswith(".")- ]+ dirnames[:] = [d for d in dirnames if d not in _BLOCKED_DIRS and not d.startswith(".")]for fname in filenames:fpath = Path(dirpath) / fnamesuffix = fpath.suffix.lower()@@ -177,103 +192,115 @@ class GrpcExtractor:for _svc_name, full_path, methods in services:for method in methods:contract_id = f"grpc::{full_path}/{method}"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="grpc",- role="provider",- file_path=rel_path,- symbol_name=f"{full_path}/{method}",- confidence=0.85,- service=None,- meta={- "package": _package,- "service": _svc_name,- "method": method,- "source": "proto",- },- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="provider",+ file_path=rel_path,+ symbol_name=f"{full_path}/{method}",+ confidence=0.85,+ service=None,+ meta={+ "package": _package,+ "service": _svc_name,+ "method": method,+ "source": "proto",+ },+ )+ )# --- Go ---elif suffix == ".go":for m in _GO_PROVIDER_RE.finditer(content):svc = m.group(1)contract_id = f"grpc::{svc}/*"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="grpc",- role="provider",- file_path=rel_path,- symbol_name=f"go:Register{svc}Server",- confidence=0.8,- service=None,- meta={"service": svc, "source": "go_register"},- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="provider",+ file_path=rel_path,+ symbol_name=f"go:Register{svc}Server",+ confidence=0.8,+ service=None,+ meta={"service": svc, "source": "go_register"},+ )+ )for m in _GO_CONSUMER_RE.finditer(content):svc = m.group(1)contract_id = f"grpc::{svc}/*"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="grpc",- role="consumer",- file_path=rel_path,- symbol_name=f"go:New{svc}Client",- confidence=0.7,- service=None,- meta={"service": svc, "source": "go_client"},- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="consumer",+ file_path=rel_path,+ symbol_name=f"go:New{svc}Client",+ confidence=0.7,+ service=None,+ meta={"service": svc, "source": "go_client"},+ )+ )# --- Java ---elif suffix == ".java":for m in _JAVA_PROVIDER_RE.finditer(content):svc = m.group(1)contract_id = f"grpc::{svc}/*"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="grpc",- role="provider",- file_path=rel_path,- symbol_name=f"java:extends {svc}Grpc.ImplBase",- confidence=0.8,- service=None,- meta={"service": svc, "source": "java_extends"},- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="provider",+ file_path=rel_path,+ symbol_name=f"java:extends {svc}Grpc.ImplBase",+ confidence=0.8,+ service=None,+ meta={"service": svc, "source": "java_extends"},+ )+ )for m in _JAVA_CONSUMER_RE.finditer(content):svc = m.group(1)contract_id = f"grpc::{svc}/*"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="grpc",- role="consumer",- file_path=rel_path,- symbol_name=f"java:{svc}Grpc.newStub",- confidence=0.7,- service=None,- meta={"service": svc, "source": "java_stub"},- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="consumer",+ file_path=rel_path,+ symbol_name=f"java:{svc}Grpc.newStub",+ confidence=0.7,+ service=None,+ meta={"service": svc, "source": "java_stub"},+ )+ )# --- Python ---elif suffix == ".py":for m in _PY_PROVIDER_RE.finditer(content):svc = m.group(1)contract_id = f"grpc::{svc}/*"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="grpc",- role="provider",- file_path=rel_path,- symbol_name=f"py:add_{svc}Servicer_to_server",- confidence=0.8,- service=None,- meta={"service": svc, "source": "py_servicer"},- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="provider",+ file_path=rel_path,+ symbol_name=f"py:add_{svc}Servicer_to_server",+ confidence=0.8,+ service=None,+ meta={"service": svc, "source": "py_servicer"},+ )+ )for m in _PY_CONSUMER_RE.finditer(content):svc = m.group(1)@@ -282,17 +309,19 @@ class GrpcExtractor:if any(svc_lower.startswith(p) for p in ("mock", "test", "fake")):continuecontract_id = f"grpc::{svc}/*"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="grpc",- role="consumer",- file_path=rel_path,- symbol_name=f"py:{svc}Stub",- confidence=0.7,- service=None,- meta={"service": svc, "source": "py_stub"},- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="consumer",+ file_path=rel_path,+ symbol_name=f"py:{svc}Stub",+ confidence=0.7,+ service=None,+ meta={"service": svc, "source": "py_stub"},+ )+ )# --- TypeScript ---elif suffix in (".ts", ".tsx", ".js", ".jsx"):@@ -300,20 +329,22 @@ class GrpcExtractor:svc = m.group(1)method = m.group(2)contract_id = f"grpc::{svc}/{method}"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="grpc",- role="provider",- file_path=rel_path,- symbol_name=f"ts:@GrpcMethod('{svc}', '{method}')",- confidence=0.8,- service=None,- meta={- "service": svc,- "method": method,- "source": "ts_decorator",- },- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="grpc",+ role="provider",+ file_path=rel_path,+ symbol_name=f"ts:@GrpcMethod('{svc}', '{method}')",+ confidence=0.8,+ service=None,+ meta={+ "service": svc,+ "method": method,+ "source": "ts_decorator",+ },+ )+ )return contractsdiff --git a/packages/core/src/repowise/core/workspace/extractors/http_extractor.py b/packages/core/src/repowise/core/workspace/extractors/http_extractor.pyindex 2f00b4687..eb789082f 100644--- a/packages/core/src/repowise/core/workspace/extractors/http_extractor.py+++ b/packages/core/src/repowise/core/workspace/extractors/http_extractor.py@@ -13,6 +13,8 @@ import refrom pathlib import Pathfrom typing import TYPE_CHECKING+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY+if TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -22,21 +24,35 @@ _log = logging.getLogger("repowise.workspace.extractors.http")# Constants# ----------------------------------------------------------------------------_BLOCKED_DIRS = frozenset({- ".git", "node_modules", "__pycache__", ".venv", "venv",- "dist", "build", "target", "vendor", ".next", ".nuxt",- ".tox", ".mypy_cache", ".gradle", ".mvn", "out", "bin",-})+_BLOCKED_DIRS = frozenset(+ {+ ".git",+ "node_modules",+ "__pycache__",+ ".venv",+ "venv",+ "dist",+ "build",+ "target",+ "vendor",+ ".next",+ ".nuxt",+ ".tox",+ ".mypy_cache",+ ".gradle",+ ".mvn",+ "out",+ "bin",+ }+)_MAX_FILE_SIZE = 512 * 1024 # 512 KB-_PROVIDER_EXTENSIONS = frozenset({- ".py", ".ts", ".tsx", ".js", ".jsx", ".java", ".php", ".go",-})+_PROVIDER_EXTENSIONS = _LANG_REGISTRY.extensions_for(+ ["python", "typescript", "javascript", "java", "php", "go"]+)-_CONSUMER_EXTENSIONS = frozenset({- ".py", ".ts", ".tsx", ".js", ".jsx",-})+_CONSUMER_EXTENSIONS = _LANG_REGISTRY.extensions_for(["python", "typescript", "javascript"])_ALL_EXTENSIONS = _PROVIDER_EXTENSIONS | _CONSUMER_EXTENSIONS@@ -178,10 +194,7 @@ class HttpExtractor:repo_root = repo_path.resolve()for dirpath, dirnames, filenames in os.walk(repo_root):- dirnames[:] = [- d for d in dirnames- if d not in _BLOCKED_DIRS and not d.startswith(".")- ]+ dirnames[:] = [d for d in dirnames if d not in _BLOCKED_DIRS and not d.startswith(".")]for fname in filenames:fpath = Path(dirpath) / fnamesuffix = fpath.suffix.lower()@@ -244,21 +257,23 @@ class HttpExtractor:contract_id = f"http::{method}::{norm_path}"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="http",- role="provider",- file_path=rel_path,- symbol_name=f"{framework}:{method} {path_raw}",- confidence=0.85,- service=None,- meta={- "method": method,- "path": norm_path,- "framework": framework,- },- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="http",+ role="provider",+ file_path=rel_path,+ symbol_name=f"{framework}:{method} {path_raw}",+ confidence=0.85,+ service=None,+ meta={+ "method": method,+ "path": norm_path,+ "framework": framework,+ },+ )+ )# --- Consumers ---if suffix in _CONSUMER_EXTENSIONS:@@ -269,17 +284,19 @@ class HttpExtractor:path = _extract_path_from_url(url)norm_path = normalize_http_path(path)contract_id = f"http::{method}::{norm_path}"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="http",- role="consumer",- file_path=rel_path,- symbol_name=f"fetch:{method} {url}",- confidence=0.75,- service=None,- meta={"method": method, "path": norm_path, "client": "fetch"},- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="http",+ role="consumer",+ file_path=rel_path,+ symbol_name=f"fetch:{method} {url}",+ confidence=0.75,+ service=None,+ meta={"method": method, "path": norm_path, "client": "fetch"},+ )+ )# fetch() without explicit method → GET (but skip if already matched with method)fetch_method_urls = {m.group(1) for m in _FETCH_METHOD_RE.finditer(content)}@@ -290,17 +307,19 @@ class HttpExtractor:path = _extract_path_from_url(url)norm_path = normalize_http_path(path)contract_id = f"http::GET::{norm_path}"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="http",- role="consumer",- file_path=rel_path,- symbol_name=f"fetch:GET {url}",- confidence=0.75,- service=None,- meta={"method": "GET", "path": norm_path, "client": "fetch"},- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="http",+ role="consumer",+ file_path=rel_path,+ symbol_name=f"fetch:GET {url}",+ confidence=0.75,+ service=None,+ meta={"method": "GET", "path": norm_path, "client": "fetch"},+ )+ )# axiosfor match in _AXIOS_RE.finditer(content):@@ -309,17 +328,19 @@ class HttpExtractor:path = _extract_path_from_url(url)norm_path = normalize_http_path(path)contract_id = f"http::{method}::{norm_path}"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="http",- role="consumer",- file_path=rel_path,- symbol_name=f"axios:{method} {url}",- confidence=0.75,- service=None,- meta={"method": method, "path": norm_path, "client": "axios"},- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="http",+ role="consumer",+ file_path=rel_path,+ symbol_name=f"axios:{method} {url}",+ confidence=0.75,+ service=None,+ meta={"method": method, "path": norm_path, "client": "axios"},+ )+ )# requests / httpxfor match in _REQUESTS_RE.finditer(content):@@ -328,16 +349,18 @@ class HttpExtractor:path = _extract_path_from_url(url)norm_path = normalize_http_path(path)contract_id = f"http::{method}::{norm_path}"- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="http",- role="consumer",- file_path=rel_path,- symbol_name=f"requests:{method} {url}",- confidence=0.75,- service=None,- meta={"method": method, "path": norm_path, "client": "requests"},- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="http",+ role="consumer",+ file_path=rel_path,+ symbol_name=f"requests:{method} {url}",+ confidence=0.75,+ service=None,+ meta={"method": method, "path": norm_path, "client": "requests"},+ )+ )return contractsdiff --git a/packages/core/src/repowise/core/workspace/extractors/service_boundary.py b/packages/core/src/repowise/core/workspace/extractors/service_boundary.pyindex 3dbd4fd26..b260f43df 100644--- a/packages/core/src/repowise/core/workspace/extractors/service_boundary.py+++ b/packages/core/src/repowise/core/workspace/extractors/service_boundary.py@@ -12,33 +12,65 @@ import osfrom dataclasses import dataclass, fieldfrom pathlib import Path+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY+# ---------------------------------------------------------------------------# Constants# ----------------------------------------------------------------------------_SERVICE_MARKERS = frozenset({- "package.json",- "go.mod",- "Dockerfile",- "pom.xml",- "build.gradle",- "build.gradle.kts",- "Cargo.toml",- "pyproject.toml",- "requirements.txt",- "mix.exs",-})--_BLOCKED_DIRS = frozenset({- ".git", "node_modules", "__pycache__", ".venv", "venv",- "dist", "build", "target", "vendor", ".next", ".nuxt",- ".tox", ".mypy_cache", ".gradle", ".mvn", "out", "bin",-})--_SOURCE_EXTENSIONS = frozenset({- ".py", ".ts", ".tsx", ".js", ".jsx", ".java", ".go",- ".rs", ".rb", ".php", ".cs", ".kt", ".scala", ".ex", ".exs",-})+_SERVICE_MARKERS = frozenset(+ {+ "package.json",+ "go.mod",+ "Dockerfile",+ "pom.xml",+ "build.gradle",+ "build.gradle.kts",+ "Cargo.toml",+ "pyproject.toml",+ "requirements.txt",+ "mix.exs",+ }+)++_BLOCKED_DIRS = frozenset(+ {+ ".git",+ "node_modules",+ "__pycache__",+ ".venv",+ "venv",+ "dist",+ "build",+ "target",+ "vendor",+ ".next",+ ".nuxt",+ ".tox",+ ".mypy_cache",+ ".gradle",+ ".mvn",+ "out",+ "bin",+ }+)++_SOURCE_EXTENSIONS = _LANG_REGISTRY.extensions_for(+ [+ "python",+ "typescript",+ "javascript",+ "java",+ "go",+ "rust",+ "ruby",+ "php",+ "csharp",+ "kotlin",+ "scala",+ "elixir",+ ]+)# ---------------------------------------------------------------------------@@ -86,10 +118,7 @@ def detect_service_boundaries(repo_path: Path) -> list[ServiceBoundary]:for dirpath, dirnames, filenames in os.walk(repo_root):# Prune blocked dirs in-place- dirnames[:] = [- d for d in dirnames- if d not in _BLOCKED_DIRS and not d.startswith(".")- ]+ dirnames[:] = [d for d in dirnames if d not in _BLOCKED_DIRS and not d.startswith(".")]current = Path(dirpath)if current == repo_root:@@ -101,19 +130,20 @@ def detect_service_boundaries(repo_path: Path) -> list[ServiceBoundary]:continue# Require at least one source file in this dir (not recursively)- has_source = any(- Path(f).suffix.lower() in _SOURCE_EXTENSIONS- for f in filenames- )+ has_source = any(Path(f).suffix.lower() in _SOURCE_EXTENSIONS for f in filenames)if not has_source:# Check immediate subdirs for source filestry:- has_source = any(- Path(dirpath, d, f).suffix.lower() in _SOURCE_EXTENSIONS- for d in dirnames- for f in os.listdir(Path(dirpath, d))- if os.path.isfile(Path(dirpath, d, f))- ) if dirnames else False+ has_source = (+ any(+ Path(dirpath, d, f).suffix.lower() in _SOURCE_EXTENSIONS+ for d in dirnames+ for f in os.listdir(Path(dirpath, d))+ if os.path.isfile(Path(dirpath, d, f))+ )+ if dirnames+ else False+ )except (PermissionError, OSError):has_source = False@@ -130,12 +160,14 @@ def detect_service_boundaries(repo_path: Path) -> list[ServiceBoundary]:else:confidence = 0.75- boundaries.append(ServiceBoundary(- service_path=rel_path,- service_name=current.name,- markers=sorted(found_markers),- confidence=confidence,- ))+ boundaries.append(+ ServiceBoundary(+ service_path=rel_path,+ service_name=current.name,+ markers=sorted(found_markers),+ confidence=confidence,+ )+ )return boundariesdiff --git a/packages/core/src/repowise/core/workspace/extractors/topic_extractor.py b/packages/core/src/repowise/core/workspace/extractors/topic_extractor.pyindex 44338aa0a..fd2f61724 100644--- a/packages/core/src/repowise/core/workspace/extractors/topic_extractor.py+++ b/packages/core/src/repowise/core/workspace/extractors/topic_extractor.py@@ -13,6 +13,8 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import TYPE_CHECKING+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRY+if TYPE_CHECKING:from repowise.core.workspace.contracts import Contract@@ -22,17 +24,31 @@ _log = logging.getLogger("repowise.workspace.extractors.topic")# Constants# ----------------------------------------------------------------------------_BLOCKED_DIRS = frozenset({- ".git", "node_modules", "__pycache__", ".venv", "venv",- "dist", "build", "target", "vendor", ".next", ".nuxt",- ".tox", ".mypy_cache", ".gradle", ".mvn", "out", "bin",-})+_BLOCKED_DIRS = frozenset(+ {+ ".git",+ "node_modules",+ "__pycache__",+ ".venv",+ "venv",+ "dist",+ "build",+ "target",+ "vendor",+ ".next",+ ".nuxt",+ ".tox",+ ".mypy_cache",+ ".gradle",+ ".mvn",+ "out",+ "bin",+ }+)_MAX_FILE_SIZE = 512 * 1024-_EXTENSIONS = frozenset({- ".py", ".ts", ".tsx", ".js", ".jsx", ".java", ".go",-})+_EXTENSIONS = _LANG_REGISTRY.extensions_for(["python", "typescript", "javascript", "java", "go"])# ---------------------------------------------------------------------------@@ -56,44 +72,65 @@ _KAFKA_PATTERNS: list[_PatternDef] = [# Java: @KafkaListener(topics = "orders")_PatternDef(regex=re.compile(r"""@KafkaListener\s*\([^)]*topics?\s*=\s*['"]([^'"]+)['"]"""),- role="consumer", broker="kafka", confidence=0.8,- topic_group=1, label="@KafkaListener",+ role="consumer",+ broker="kafka",+ confidence=0.8,+ topic_group=1,+ label="@KafkaListener",),# Java: kafkaTemplate.send("orders", ...)_PatternDef(regex=re.compile(r"""kafkaTemplate\.send\s*\(\s*['"]([^'"]+)['"]"""),- role="provider", broker="kafka", confidence=0.8,- topic_group=1, label="kafkaTemplate.send",+ role="provider",+ broker="kafka",+ confidence=0.8,+ topic_group=1,+ label="kafkaTemplate.send",),# Node: producer.send({ topic: 'orders' })_PatternDef(regex=re.compile(r"""producer\.send\s*\(\s*\{\s*topic\s*:\s*['"]([^'"]+)['"]"""),- role="provider", broker="kafka", confidence=0.8,- topic_group=1, label="producer.send({topic})",+ role="provider",+ broker="kafka",+ confidence=0.8,+ topic_group=1,+ label="producer.send({topic})",),# Node: consumer.subscribe({ topic: 'orders' })_PatternDef(regex=re.compile(r"""consumer\.subscribe\s*\(\s*\{\s*topic\s*:\s*['"]([^'"]+)['"]"""),- role="consumer", broker="kafka", confidence=0.8,- topic_group=1, label="consumer.subscribe({topic})",+ role="consumer",+ broker="kafka",+ confidence=0.8,+ topic_group=1,+ label="consumer.subscribe({topic})",),# Python: KafkaConsumer('orders')_PatternDef(regex=re.compile(r"""KafkaConsumer\s*\(\s*['"]([^'"]+)['"]"""),- role="consumer", broker="kafka", confidence=0.7,- topic_group=1, label="KafkaConsumer",+ role="consumer",+ broker="kafka",+ confidence=0.7,+ topic_group=1,+ label="KafkaConsumer",),# Python: producer.produce('orders')_PatternDef(regex=re.compile(r"""producer\.produce\s*\(\s*['"]([^'"]+)['"]"""),- role="provider", broker="kafka", confidence=0.7,- topic_group=1, label="producer.produce",+ role="provider",+ broker="kafka",+ confidence=0.7,+ topic_group=1,+ label="producer.produce",),# Go: ConsumePartition("orders", ...)_PatternDef(regex=re.compile(r"""ConsumePartition\s*\(\s*['"]([^'"]+)['"]"""),- role="consumer", broker="kafka", confidence=0.7,- topic_group=1, label="ConsumePartition",+ role="consumer",+ broker="kafka",+ confidence=0.7,+ topic_group=1,+ label="ConsumePartition",),]@@ -103,44 +140,65 @@ _RABBITMQ_PATTERNS: list[_PatternDef] = [# Java: @RabbitListener(queues = "jobs")_PatternDef(regex=re.compile(r"""@RabbitListener\s*\([^)]*queues?\s*=\s*['"]([^'"]+)['"]"""),- role="consumer", broker="rabbitmq", confidence=0.8,- topic_group=1, label="@RabbitListener",+ role="consumer",+ broker="rabbitmq",+ confidence=0.8,+ topic_group=1,+ label="@RabbitListener",),# Java: rabbitTemplate.convertAndSend("exchange", ...)_PatternDef(regex=re.compile(r"""rabbitTemplate\.convertAndSend\s*\(\s*['"]([^'"]+)['"]"""),- role="provider", broker="rabbitmq", confidence=0.8,- topic_group=1, label="rabbitTemplate.convertAndSend",+ role="provider",+ broker="rabbitmq",+ confidence=0.8,+ topic_group=1,+ label="rabbitTemplate.convertAndSend",),# Node: channel.consume("queue", ...)_PatternDef(regex=re.compile(r"""channel\.consume\s*\(\s*['"]([^'"]+)['"]"""),- role="consumer", broker="rabbitmq", confidence=0.8,- topic_group=1, label="channel.consume",+ role="consumer",+ broker="rabbitmq",+ confidence=0.8,+ topic_group=1,+ label="channel.consume",),# Node: channel.publish("exchange", ...)_PatternDef(regex=re.compile(r"""channel\.publish\s*\(\s*['"]([^'"]+)['"]"""),- role="provider", broker="rabbitmq", confidence=0.8,- topic_group=1, label="channel.publish",+ role="provider",+ broker="rabbitmq",+ confidence=0.8,+ topic_group=1,+ label="channel.publish",),# Node: channel.sendToQueue("queue", ...)_PatternDef(regex=re.compile(r"""channel\.sendToQueue\s*\(\s*['"]([^'"]+)['"]"""),- role="provider", broker="rabbitmq", confidence=0.8,- topic_group=1, label="channel.sendToQueue",+ role="provider",+ broker="rabbitmq",+ confidence=0.8,+ topic_group=1,+ label="channel.sendToQueue",),# Python: channel.basic_consume(queue='jobs')_PatternDef(regex=re.compile(r"""channel\.basic_consume\s*\([^)]*queue\s*=\s*['"]([^'"]+)['"]"""),- role="consumer", broker="rabbitmq", confidence=0.7,- topic_group=1, label="basic_consume",+ role="consumer",+ broker="rabbitmq",+ confidence=0.7,+ topic_group=1,+ label="basic_consume",),# Python: channel.basic_publish(exchange='events')_PatternDef(regex=re.compile(r"""channel\.basic_publish\s*\([^)]*exchange\s*=\s*['"]([^'"]+)['"]"""),- role="provider", broker="rabbitmq", confidence=0.7,- topic_group=1, label="basic_publish",+ role="provider",+ broker="rabbitmq",+ confidence=0.7,+ topic_group=1,+ label="basic_publish",),]@@ -151,16 +209,26 @@ _NATS_PATTERNS: list[_PatternDef] = [# Requires a NATS-idiomatic variable name (nc, nats, conn, js, sub, client)# to avoid false-positives from RxJS, EventEmitter, custom publishers, etc._PatternDef(- regex=re.compile(r"""(?:nc|nats|conn|js|sub|client)\s*\.\s*(?:Subscribe|subscribe)\s*\(\s*['"]([^'"]+)['"]"""),- role="consumer", broker="nats", confidence=0.8,- topic_group=1, label="nc.Subscribe",+ regex=re.compile(+ r"""(?:nc|nats|conn|js|sub|client)\s*\.\s*(?:Subscribe|subscribe)\s*\(\s*['"]([^'"]+)['"]"""+ ),+ role="consumer",+ broker="nats",+ confidence=0.8,+ topic_group=1,+ label="nc.Subscribe",),# Go/Python/Node: nc.Publish("events") or nc.publish("events")# Requires a NATS-idiomatic variable name to avoid false-positives._PatternDef(- regex=re.compile(r"""(?:nc|nats|conn|js|sub|client)\s*\.\s*(?:Publish|publish)\s*\(\s*['"]([^'"]+)['"]"""),- role="provider", broker="nats", confidence=0.8,- topic_group=1, label="nc.Publish",+ regex=re.compile(+ r"""(?:nc|nats|conn|js|sub|client)\s*\.\s*(?:Publish|publish)\s*\(\s*['"]([^'"]+)['"]"""+ ),+ role="provider",+ broker="nats",+ confidence=0.8,+ topic_group=1,+ label="nc.Publish",),]@@ -183,10 +251,7 @@ class TopicExtractor:seen: set[tuple[str, str, str]] = set() # (file, contract_id, role) dedupfor dirpath, dirnames, filenames in os.walk(repo_root):- dirnames[:] = [- d for d in dirnames- if d not in _BLOCKED_DIRS and not d.startswith(".")- ]+ dirnames[:] = [d for d in dirnames if d not in _BLOCKED_DIRS and not d.startswith(".")]for fname in filenames:fpath = Path(dirpath) / fnamesuffix = fpath.suffix.lower()@@ -219,19 +284,21 @@ class TopicExtractor:continueseen.add(dedup_key)- contracts.append(Contract(- repo=repo_alias,- contract_id=contract_id,- contract_type="topic",- role=pdef.role,- file_path=rel_path,- symbol_name=f"{pdef.label}('{topic_name}')",- confidence=pdef.confidence,- service=None,- meta={- "topic": topic_name,- "broker": pdef.broker,- },- ))+ contracts.append(+ Contract(+ repo=repo_alias,+ contract_id=contract_id,+ contract_type="topic",+ role=pdef.role,+ file_path=rel_path,+ symbol_name=f"{pdef.label}('{topic_name}')",+ confidence=pdef.confidence,+ service=None,+ meta={+ "topic": topic_name,+ "broker": pdef.broker,+ },+ )+ )return contractsdiff --git a/packages/server/src/repowise/server/mcp_server/_helpers.py b/packages/server/src/repowise/server/mcp_server/_helpers.pyindex 458f9a6da..21e3e8afa 100644--- a/packages/server/src/repowise/server/mcp_server/_helpers.py+++ b/packages/server/src/repowise/server/mcp_server/_helpers.py@@ -11,6 +11,7 @@ from typing import Anyfrom sqlalchemy import selectfrom sqlalchemy.ext.asyncio import AsyncSession+from repowise.core.ingestion.languages.registry import REGISTRY as _LANG_REGISTRYfrom repowise.core.persistence.models import (Repository,)@@ -20,26 +21,7 @@ from repowise.server.mcp_server import _state# Constants# ----------------------------------------------------------------------------_CODE_EXTS = frozenset(- {- ".py",- ".ts",- ".js",- ".go",- ".rs",- ".java",- ".tsx",- ".jsx",- ".rb",- ".kt",- ".cpp",- ".c",- ".h",- ".cs",- ".swift",- ".scala",- }-)+_CODE_EXTS = _LANG_REGISTRY.all_code_extensions()# ---------------------------------------------------------------------------diff --git a/pyproject.toml b/pyproject.tomlindex 4f2c68875..61a85af7a 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -42,6 +42,12 @@ dependencies = ["tree-sitter-rust>=0.23,<1","tree-sitter-java>=0.23,<1","tree-sitter-cpp>=0.23,<1",+ "tree-sitter-kotlin>=1,<2",+ "tree-sitter-ruby>=0.23,<1",+ "tree-sitter-c-sharp>=0.23,<1",+ "tree-sitter-swift>=0.0.1",+ "tree-sitter-scala>=0.23,<1",+ "tree-sitter-php>=0.23,<1",# Dependency graph"networkx>=3.3,<4","scipy>=1.11,<2",diff --git a/tests/fixtures/sample_repo/csharp_pkg/Calculator.cs b/tests/fixtures/sample_repo/csharp_pkg/Calculator.csnew file mode 100644index 000000000..3d5ec3d5b--- /dev/null+++ b/tests/fixtures/sample_repo/csharp_pkg/Calculator.cs@@ -0,0 +1,21 @@+using System;+using Sample.Models;++namespace Sample+{+ /// <summary>Calculator for basic arithmetic.</summary>+ public class Calculator+ {+ public double Add(double x, double y)+ {+ return x + y;+ }++ public double Subtract(double x, double y)+ {+ return x - y;+ }++ private void Helper() { }+ }+}diff --git a/tests/fixtures/sample_repo/csharp_pkg/Models.cs b/tests/fixtures/sample_repo/csharp_pkg/Models.csnew file mode 100644index 000000000..92ceafc27--- /dev/null+++ b/tests/fixtures/sample_repo/csharp_pkg/Models.cs@@ -0,0 +1,23 @@+namespace Sample.Models+{+ public enum Operation+ {+ Add,+ Subtract,+ Multiply,+ Divide+ }++ public class CalculationRecord+ {+ public Operation Op { get; set; }+ public double X { get; set; }+ public double Y { get; set; }+ public double Result { get; set; }+ }++ public interface IComputable+ {+ double Compute();+ }+}diff --git a/tests/fixtures/sample_repo/kotlin_pkg/Calculator.kt b/tests/fixtures/sample_repo/kotlin_pkg/Calculator.ktnew file mode 100644index 000000000..c06d0383d--- /dev/null+++ b/tests/fixtures/sample_repo/kotlin_pkg/Calculator.kt@@ -0,0 +1,26 @@+package sample++import sample.models.Operation+import sample.models.CalculationRecord++class Calculator {+ private val history = mutableListOf<CalculationRecord>()++ fun add(x: Double, y: Double): Double {+ val result = x + y+ record(Operation.ADD, x, y, result)+ return result+ }++ fun subtract(x: Double, y: Double): Double {+ val result = x - y+ record(Operation.SUBTRACT, x, y, result)+ return result+ }++ private fun record(op: Operation, x: Double, y: Double, result: Double) {+ history.add(CalculationRecord(op, x, y, result))+ }++ fun getHistory(): List<CalculationRecord> = history+}diff --git a/tests/fixtures/sample_repo/kotlin_pkg/Models.kt b/tests/fixtures/sample_repo/kotlin_pkg/Models.ktnew file mode 100644index 000000000..7204b0d98--- /dev/null+++ b/tests/fixtures/sample_repo/kotlin_pkg/Models.kt@@ -0,0 +1,17 @@+package sample.models++/** Supported arithmetic operations. */+enum class Operation {+ ADD,+ SUBTRACT,+ MULTIPLY,+ DIVIDE+}++/** Record of a single calculation. */+data class CalculationRecord(+ val operation: Operation,+ val x: Double,+ val y: Double,+ val result: Double+)diff --git a/tests/fixtures/sample_repo/php_pkg/Calculator.php b/tests/fixtures/sample_repo/php_pkg/Calculator.phpnew file mode 100644index 000000000..d71a054c4--- /dev/null+++ b/tests/fixtures/sample_repo/php_pkg/Calculator.php@@ -0,0 +1,21 @@+<?php+namespace Sample;++use Sample\Models\Operation;+use Sample\Models\CalculationRecord;++/** Calculator for basic arithmetic. */+class Calculator extends BaseCalc implements Computable+{+ public function add(float $x, float $y): float+ {+ return $x + $y;+ }++ public function subtract(float $x, float $y): float+ {+ return $x - $y;+ }++ private function helper(): void {}+}diff --git a/tests/fixtures/sample_repo/php_pkg/Models.php b/tests/fixtures/sample_repo/php_pkg/Models.phpnew file mode 100644index 000000000..ee72854c8--- /dev/null+++ b/tests/fixtures/sample_repo/php_pkg/Models.php@@ -0,0 +1,25 @@+<?php+namespace Sample\Models;++/** Supported operations. */+enum Operation+{+ case Add;+ case Subtract;+}++/** A calculation record. */+class CalculationRecord+{+ public function __construct(+ public Operation $operation,+ public float $x,+ public float $y,+ public float $result,+ ) {}+}++interface Computable+{+ public function compute(): float;+}diff --git a/tests/fixtures/sample_repo/ruby_pkg/calculator.rb b/tests/fixtures/sample_repo/ruby_pkg/calculator.rbnew file mode 100644index 000000000..194667208--- /dev/null+++ b/tests/fixtures/sample_repo/ruby_pkg/calculator.rb@@ -0,0 +1,22 @@+# Calculator class for basic arithmetic+require_relative './models'++class Calculator < BaseCalculator+ def add(x, y)+ result = x + y+ record(x, y, result)+ result+ end++ def subtract(x, y)+ result = x - y+ record(x, y, result)+ result+ end++ private++ def record(x, y, result)+ @history << CalculationRecord.new(x, y, result)+ end+enddiff --git a/tests/fixtures/sample_repo/ruby_pkg/models.rb b/tests/fixtures/sample_repo/ruby_pkg/models.rbnew file mode 100644index 000000000..d01d19cb9--- /dev/null+++ b/tests/fixtures/sample_repo/ruby_pkg/models.rb@@ -0,0 +1,19 @@+# Data models for the calculator+module Models+ # A record of a single calculation+ class CalculationRecord+ attr_reader :x, :y, :result++ def initialize(x, y, result)+ @x = x+ @y = y+ @result = result+ end+ end++ # Supported operations+ class Operation+ ADD = :add+ SUBTRACT = :subtract+ end+enddiff --git a/tests/fixtures/sample_repo/scala_pkg/Calculator.scala b/tests/fixtures/sample_repo/scala_pkg/Calculator.scalanew file mode 100644index 000000000..2f6eb7c0d--- /dev/null+++ b/tests/fixtures/sample_repo/scala_pkg/Calculator.scala@@ -0,0 +1,19 @@+package sample++import sample.models.Operation+import sample.models.CalculationRecord++/** Calculator for basic arithmetic. */+class Calculator extends BaseCalc with Computable {+ def add(x: Double, y: Double): Double = x + y++ def subtract(x: Double, y: Double): Double = x - y++ private def helper(): Unit = {}++ def compute(): Double = 0.0+}++trait Computable {+ def compute(): Double+}diff --git a/tests/fixtures/sample_repo/scala_pkg/Models.scala b/tests/fixtures/sample_repo/scala_pkg/Models.scalanew file mode 100644index 000000000..6af0df3e0--- /dev/null+++ b/tests/fixtures/sample_repo/scala_pkg/Models.scala@@ -0,0 +1,17 @@+package sample.models++/** Supported operations. */+sealed trait Operation++object Operation {+ case object Add extends Operation+ case object Subtract extends Operation+}++/** Record of a calculation. */+case class CalculationRecord(+ operation: Operation,+ x: Double,+ y: Double,+ result: Double+)diff --git a/tests/fixtures/sample_repo/swift_pkg/Calculator.swift b/tests/fixtures/sample_repo/swift_pkg/Calculator.swiftnew file mode 100644index 000000000..89f593238--- /dev/null+++ b/tests/fixtures/sample_repo/swift_pkg/Calculator.swift@@ -0,0 +1,18 @@+import Foundation++/// Calculator for basic arithmetic.+class Calculator: Computable {+ func add(x: Double, y: Double) -> Double {+ return x + y+ }++ func subtract(x: Double, y: Double) -> Double {+ return x - y+ }++ private func helper() {}++ func compute() -> Double {+ return 0.0+ }+}diff --git a/tests/fixtures/sample_repo/swift_pkg/Models.swift b/tests/fixtures/sample_repo/swift_pkg/Models.swiftnew file mode 100644index 000000000..8340b276b--- /dev/null+++ b/tests/fixtures/sample_repo/swift_pkg/Models.swift@@ -0,0 +1,19 @@+import Foundation++protocol Computable {+ func compute() -> Double+}++enum Operation {+ case add+ case subtract+ case multiply+ case divide+}++struct CalculationRecord {+ var operation: Operation+ var x: Double+ var y: Double+ var result: Double+}diff --git a/tests/integration/test_ingest_sample_repo.py b/tests/integration/test_ingest_sample_repo.pyindex 939f9c4fe..76d6b9bfd 100644--- a/tests/integration/test_ingest_sample_repo.py+++ b/tests/integration/test_ingest_sample_repo.py@@ -317,7 +317,7 @@ class TestIngestSampleRepo:def test_heritage_all_have_valid_kind(self, ingestion_result) -> None:"""Every heritage relation must have a valid kind."""- valid_kinds = {"extends", "implements", "trait_impl", "mixin"}+ valid_kinds = {"extends", "implements", "trait_impl", "mixin", "derive"}for p in ingestion_result["parsed"]:for h in p.heritage:assert h.kind in valid_kinds, (diff --git a/tests/unit/ingestion/test_graph.py b/tests/unit/ingestion/test_graph.pyindex bc36795ad..b5025048c 100644--- a/tests/unit/ingestion/test_graph.py+++ b/tests/unit/ingestion/test_graph.py@@ -116,7 +116,8 @@ class TestAddFile:b.add_file(_parsed("a.py"))b.add_file(_parsed("b.py"))g = b.graph()- assert g.number_of_nodes() == 2+ # 2 file nodes + 2 synthetic __module__ symbol nodes+ assert g.number_of_nodes() == 4# ---------------------------------------------------------------------------@@ -150,11 +151,16 @@ class TestPythonImports:assert b.graph().has_edge("main.py", "src/calculator.py")def test_unresolvable_import_no_edge(self) -> None:- """Unresolvable import produces no edge (no crash)."""+ """Unresolvable import produces no import edge (no crash)."""b = GraphBuilder()b.add_file(_parsed("main.py", imports=[_imp("nonexistent_external_lib")]))b.build()- assert b.graph().number_of_edges() == 0+ # Only the defines edge for the synthetic __module__ symbol+ import_edges = [+ (u, v) for u, v, d in b.graph().edges(data=True)+ if d.get("edge_type") == "imports"+ ]+ assert len(import_edges) == 0def test_imported_names_on_edge(self) -> None:"""Imported names are stored on the edge."""@@ -233,7 +239,10 @@ class TestStemDisambiguation:b.add_file(_parsed(f))b.add_file(_parsed("main.py", imports=[_imp("widget")]))b.build()- edges = list(b.graph().out_edges("main.py"))+ edges = [+ (u, v) for u, v, d in b.graph().out_edges("main.py", data=True)+ if d.get("edge_type") == "imports"+ ]return edges[0][1] if edges else Nonetarget_a = build_with_order(files)@@ -271,8 +280,12 @@ class TestStemDisambiguation:b.add_file(_parsed("__init__.py"))b.add_file(_parsed("main.py", imports=[_imp("anything")]))b.build() # must not raise- # No edge expected — stem "anything" is unresolvable- assert b.graph().number_of_edges() == 0+ # No import edge — stem "anything" is unresolvable+ import_edges = [+ (u, v) for u, v, d in b.graph().edges(data=True)+ if d.get("edge_type") == "imports"+ ]+ assert len(import_edges) == 0def test_go_stem_collision_prefers_parent_match(self) -> None:"""Go: `import .../calculator` prefers calculator/calculator.go@@ -579,10 +592,12 @@ class TestPersist:async with aiosqlite.connect(db_path) as db:async with db.execute("SELECT * FROM graph_nodes") as cur:rows = await cur.fetchall()- assert len(rows) == 2+ # 2 file nodes + 2 synthetic __module__ symbol nodes+ assert len(rows) == 4async with db.execute("SELECT * FROM graph_edges") as cur:edges = await cur.fetchall()- assert len(edges) == 1+ # 1 import edge + 2 defines edges for __module__ symbols+ assert len(edges) == 3asyncio.run(run())@@ -693,8 +708,12 @@ class TestCppCompileCommandsResolution:b = GraphBuilder(repo_path=tmp_path)b.add_file(_cpp("src/main.cpp", imports=[_cinclude("nonexistent.hpp")]))b.build()- # No edge, no exception- assert b.graph().number_of_edges() == 0+ # No import edge, no exception+ import_edges = [+ (u, v) for u, v, d in b.graph().edges(data=True)+ if d.get("edge_type") == "imports"+ ]+ assert len(import_edges) == 0def test_compile_commands_in_build_subdir(self, tmp_path: Path) -> None:"""compile_commands.json under build/ subdirectory is also found."""diff --git a/tests/unit/ingestion/test_parser.py b/tests/unit/ingestion/test_parser.pyindex 8d1ffe7a9..3462b8d0b 100644--- a/tests/unit/ingestion/test_parser.py+++ b/tests/unit/ingestion/test_parser.py@@ -564,6 +564,130 @@ class TestCppParser:assert any("calculator.hpp" in p or "stdexcept" in p for p in module_paths)+# ---------------------------------------------------------------------------+# Kotlin+# ---------------------------------------------------------------------------++KOTLIN_SOURCE = b"""\+package sample++import sample.models.Operation++/** Calculator for basic arithmetic. */+class Calculator {+ fun add(x: Double, y: Double): Double {+ val result = x + y+ return result+ }++ private fun helper() {}+}++enum class Operation {+ ADD, SUBTRACT+}+"""+++class TestKotlinParser:+ def test_finds_class(self, parser: ASTParser) -> None:+ fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")+ result = parser.parse_file(fi, KOTLIN_SOURCE)+ classes = [s for s in result.symbols if s.kind == "class"]+ assert any(s.name == "Calculator" for s in classes)++ def test_finds_functions(self, parser: ASTParser) -> None:+ fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")+ result = parser.parse_file(fi, KOTLIN_SOURCE)+ # add is inside Calculator so it becomes a method; check both kinds+ fns = [s for s in result.symbols if s.kind in ("function", "method")]+ assert any(s.name == "add" for s in fns)++ def test_parses_imports(self, parser: ASTParser) -> None:+ fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")+ result = parser.parse_file(fi, KOTLIN_SOURCE)+ assert len(result.imports) >= 1+ modules = {imp.module_path for imp in result.imports}+ assert any("Operation" in m for m in modules)++ def test_no_parse_errors(self, parser: ASTParser) -> None:+ fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")+ result = parser.parse_file(fi, KOTLIN_SOURCE)+ assert result.parse_errors == []++ def test_private_visibility(self, parser: ASTParser) -> None:+ fi = _make_file_info("kotlin_pkg/Calculator.kt", "kotlin")+ result = parser.parse_file(fi, KOTLIN_SOURCE)+ helper = next((s for s in result.symbols if s.name == "helper"), None)+ assert helper is not None+ assert helper.visibility == "private"+++# ---------------------------------------------------------------------------+# Ruby+# ---------------------------------------------------------------------------++RUBY_SOURCE = b"""\+# Calculator module+require_relative './models'++class Calculator < BaseCalculator+ def add(x, y)+ result = x + y+ record(x, y, result)+ result+ end++ def subtract(x, y)+ x - y+ end++ def self.create+ Calculator.new+ end+end++module Operations+ def multiply(x, y)+ x * y+ end+end+"""+++class TestRubyParser:+ def test_finds_class(self, parser: ASTParser) -> None:+ fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")+ result = parser.parse_file(fi, RUBY_SOURCE)+ classes = [s for s in result.symbols if s.kind == "class"]+ assert any(s.name == "Calculator" for s in classes)++ def test_finds_module(self, parser: ASTParser) -> None:+ fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")+ result = parser.parse_file(fi, RUBY_SOURCE)+ modules = [s for s in result.symbols if s.kind == "module"]+ assert any(s.name == "Operations" for s in modules)++ def test_finds_methods(self, parser: ASTParser) -> None:+ fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")+ result = parser.parse_file(fi, RUBY_SOURCE)+ # add/subtract are inside Calculator so they become methods+ fns = [s for s in result.symbols if s.kind in ("function", "method")]+ names = {s.name for s in fns}+ assert "add" in names+ assert "subtract" in names++ def test_parses_imports(self, parser: ASTParser) -> None:+ fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")+ result = parser.parse_file(fi, RUBY_SOURCE)+ assert len(result.imports) >= 1++ def test_no_parse_errors(self, parser: ASTParser) -> None:+ fi = _make_file_info("ruby_pkg/calculator.rb", "ruby")+ result = parser.parse_file(fi, RUBY_SOURCE)+ assert result.parse_errors == []++# ---------------------------------------------------------------------------# Unsupported language (graceful fallback)# ---------------------------------------------------------------------------@@ -586,9 +710,314 @@ class TestUnsupportedLanguage:# ---------------------------------------------------------------------------+# ---------------------------------------------------------------------------+# C#+# ---------------------------------------------------------------------------++CSHARP_SOURCE = b"""\+using System;+using Sample.Models;++namespace Sample+{+ /// <summary>Calculator for basic arithmetic.</summary>+ public class Calculator+ {+ public double Add(double x, double y)+ {+ return x + y;+ }++ private void Helper() { }+ }++ public interface IComputable+ {+ double Compute();+ }++ public enum Operation { Add, Subtract }++ public struct Point+ {+ public double X;+ public double Y;+ }+}+"""+++class TestCSharpParser:+ def test_finds_class(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_SOURCE)+ classes = [s for s in result.symbols if s.kind == "class"]+ assert any(s.name == "Calculator" for s in classes)++ def test_finds_interface(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_SOURCE)+ interfaces = [s for s in result.symbols if s.kind == "interface"]+ assert any(s.name == "IComputable" for s in interfaces)++ def test_finds_enum(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_SOURCE)+ enums = [s for s in result.symbols if s.kind == "enum"]+ assert any(s.name == "Operation" for s in enums)++ def test_finds_struct(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_SOURCE)+ structs = [s for s in result.symbols if s.kind == "struct"]+ assert any(s.name == "Point" for s in structs)++ def test_finds_methods(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_SOURCE)+ methods = [s for s in result.symbols if s.kind == "method"]+ assert any(s.name == "Add" for s in methods)++ def test_parses_imports(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_SOURCE)+ assert len(result.imports) >= 2+ modules = {imp.module_path for imp in result.imports}+ assert "System" in modules++ def test_private_visibility(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_SOURCE)+ helper = next((s for s in result.symbols if s.name == "Helper"), None)+ assert helper is not None+ assert helper.visibility == "private"++ def test_no_parse_errors(self, parser: ASTParser) -> None:+ fi = _make_file_info("csharp_pkg/Calculator.cs", "csharp")+ result = parser.parse_file(fi, CSHARP_SOURCE)+ assert result.parse_errors == []+++# ---------------------------------------------------------------------------+# Swift+# ---------------------------------------------------------------------------++SWIFT_SOURCE = b"""\+import Foundation++/// Calculator for basic arithmetic.+class Calculator: Computable {+ func add(x: Double, y: Double) -> Double {+ return x + y+ }++ private func helper() {}+}++protocol Computable {+ func compute() -> Double+}++enum Operation {+ case add+ case subtract+}++struct Point {+ var x: Double+ var y: Double+}+"""+++class TestSwiftParser:+ def test_finds_class(self, parser: ASTParser) -> None:+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")+ result = parser.parse_file(fi, SWIFT_SOURCE)+ classes = [s for s in result.symbols if s.kind == "class"]+ assert any(s.name == "Calculator" for s in classes)++ def test_finds_protocol(self, parser: ASTParser) -> None:+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")+ result = parser.parse_file(fi, SWIFT_SOURCE)+ interfaces = [s for s in result.symbols if s.kind == "interface"]+ assert any(s.name == "Computable" for s in interfaces)++ def test_finds_functions(self, parser: ASTParser) -> None:+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")+ result = parser.parse_file(fi, SWIFT_SOURCE)+ # Functions inside a class are upgraded to "method"+ fns = [s for s in result.symbols if s.kind in ("function", "method")]+ assert any(s.name == "add" for s in fns)++ def test_parses_imports(self, parser: ASTParser) -> None:+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")+ result = parser.parse_file(fi, SWIFT_SOURCE)+ assert len(result.imports) >= 1+ modules = {imp.module_path for imp in result.imports}+ assert any("Foundation" in m for m in modules)++ def test_private_visibility(self, parser: ASTParser) -> None:+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")+ result = parser.parse_file(fi, SWIFT_SOURCE)+ helper = next((s for s in result.symbols if s.name == "helper"), None)+ assert helper is not None+ assert helper.visibility == "private"++ def test_no_parse_errors(self, parser: ASTParser) -> None:+ fi = _make_file_info("swift_pkg/Calculator.swift", "swift")+ result = parser.parse_file(fi, SWIFT_SOURCE)+ assert result.parse_errors == []+++# ---------------------------------------------------------------------------+# Scala+# ---------------------------------------------------------------------------++SCALA_SOURCE = b"""\+package sample++import sample.models.{Operation, CalculationRecord}++/** Calculator for basic arithmetic. */+class Calculator extends BaseCalc with Computable {+ def add(x: Double, y: Double): Double = x + y++ private def helper(): Unit = {}+}++trait Computable {+ def compute(): Double+}++object Singleton {+ val name = "calc"+}+"""+++class TestScalaParser:+ def test_finds_class(self, parser: ASTParser) -> None:+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")+ result = parser.parse_file(fi, SCALA_SOURCE)+ classes = [s for s in result.symbols if s.kind == "class"]+ assert any(s.name == "Calculator" for s in classes)++ def test_finds_trait(self, parser: ASTParser) -> None:+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")+ result = parser.parse_file(fi, SCALA_SOURCE)+ traits = [s for s in result.symbols if s.kind == "trait"]+ assert any(s.name == "Computable" for s in traits)++ def test_finds_object(self, parser: ASTParser) -> None:+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")+ result = parser.parse_file(fi, SCALA_SOURCE)+ objs = [s for s in result.symbols if s.name == "Singleton"]+ assert len(objs) >= 1++ def test_finds_functions(self, parser: ASTParser) -> None:+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")+ result = parser.parse_file(fi, SCALA_SOURCE)+ # def inside a class is promoted to "method"; top-level def stays "function"+ fns = [s for s in result.symbols if s.kind in ("function", "method")]+ assert any(s.name == "add" for s in fns)++ def test_parses_imports(self, parser: ASTParser) -> None:+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")+ result = parser.parse_file(fi, SCALA_SOURCE)+ assert len(result.imports) >= 1++ def test_no_parse_errors(self, parser: ASTParser) -> None:+ fi = _make_file_info("scala_pkg/Calculator.scala", "scala")+ result = parser.parse_file(fi, SCALA_SOURCE)+ assert result.parse_errors == []+++# ---------------------------------------------------------------------------+# PHP+# ---------------------------------------------------------------------------++PHP_SOURCE = b"""\+<?php+namespace Sample;++use Sample\\Models\\Operation;+use Sample\\Models\\CalculationRecord;++/** Calculator for basic arithmetic. */+class Calculator extends BaseCalc implements Computable+{+ public function add(float $x, float $y): float+ {+ return $x + $y;+ }++ private function helper(): void {}+}++interface Computable+{+ public function compute(): float;+}++enum Operation+{+ case Add;+ case Subtract;+}+"""+++class TestPhpParser:+ def test_finds_class(self, parser: ASTParser) -> None:+ fi = _make_file_info("php_pkg/Calculator.php", "php")+ result = parser.parse_file(fi, PHP_SOURCE)+ classes = [s for s in result.symbols if s.kind == "class"]+ assert any(s.name == "Calculator" for s in classes)++ def test_finds_interface(self, parser: ASTParser) -> None:+ fi = _make_file_info("php_pkg/Calculator.php", "php")+ result = parser.parse_file(fi, PHP_SOURCE)+ interfaces = [s for s in result.symbols if s.kind == "interface"]+ assert any(s.name == "Computable" for s in interfaces)++ def test_finds_enum(self, parser: ASTParser) -> None:+ fi = _make_file_info("php_pkg/Calculator.php", "php")+ result = parser.parse_file(fi, PHP_SOURCE)+ enums = [s for s in result.symbols if s.kind == "enum"]+ assert any(s.name == "Operation" for s in enums)++ def test_finds_methods(self, parser: ASTParser) -> None:+ fi = _make_file_info("php_pkg/Calculator.php", "php")+ result = parser.parse_file(fi, PHP_SOURCE)+ methods = [s for s in result.symbols if s.kind == "method"]+ assert any(s.name == "add" for s in methods)++ def test_parses_imports(self, parser: ASTParser) -> None:+ fi = _make_file_info("php_pkg/Calculator.php", "php")+ result = parser.parse_file(fi, PHP_SOURCE)+ assert len(result.imports) >= 1++ def test_private_visibility(self, parser: ASTParser) -> None:+ fi = _make_file_info("php_pkg/Calculator.php", "php")+ result = parser.parse_file(fi, PHP_SOURCE)+ helper = next((s for s in result.symbols if s.name == "helper"), None)+ assert helper is not None+ assert helper.visibility == "private"++ def test_no_parse_errors(self, parser: ASTParser) -> None:+ fi = _make_file_info("php_pkg/Calculator.php", "php")+ result = parser.parse_file(fi, PHP_SOURCE)+ assert result.parse_errors == []++class TestLanguageConfigs:def test_all_supported_languages_have_config(self) -> None:- expected = {"python", "typescript", "javascript", "go", "rust", "java", "cpp", "c"}+ expected = {+ "python", "typescript", "javascript", "go", "rust",+ "java", "cpp", "c", "kotlin", "ruby", "csharp", "swift",+ "scala", "php",+ }for lang in expected:assert lang in LANGUAGE_CONFIGS, f"Missing config for {lang}"diff --git a/tests/unit/test_dead_code.py b/tests/unit/test_dead_code.pyindex c8a3532a4..7ce707b74 100644--- a/tests/unit/test_dead_code.py+++ b/tests/unit/test_dead_code.py@@ -32,14 +32,29 @@ def _build_graph() -> nx.DiGraph:"""Create a DiGraph with the given node attributes and edges.- ``nodes`` maps node-id to its attribute dict.+ ``nodes`` maps node-id to its attribute dict. If a node has a+ ``symbols`` list, each entry is promoted to a proper symbol node+ connected to the file via a ``defines`` edge (matching the real+ GraphBuilder layout).``edges`` is a list of (src, dst) pairs; edge data can besupplied as a 3-tuple (src, dst, data_dict)."""g = nx.DiGraph()for name, attrs in nodes.items():attrs.setdefault("language", "python")+ # Extract symbols before adding the file node+ sym_list = attrs.pop("symbols", [])g.add_node(name, **attrs)+ # Create symbol nodes + defines edges (mirrors GraphBuilder.add_file)+ for sym in sym_list:+ sym_id = f"{name}::{sym['name']}"+ g.add_node(+ sym_id,+ node_type="symbol",+ file_path=name,+ **sym,+ )+ g.add_edge(name, sym_id, edge_type="defines")for edge in edges or []:if len(edge) == 3:g.add_edge(edge[0], edge[1], **(edge[2]))diff --git a/uv.lock b/uv.lockindex d48412f0b..e4bb592df 100644--- a/uv.lock+++ b/uv.lock@@ -3010,7 +3010,7 @@ wheels = [[[package]]name = "repowise"-version = "0.2.3"+version = "0.3.0"source = { editable = "." }dependencies = [{ name = "aiosqlite" },@@ -3038,12 +3038,18 @@ dependencies = [{ name = "structlog" },{ name = "tenacity" },{ name = "tree-sitter" },+ { name = "tree-sitter-c-sharp" },{ name = "tree-sitter-cpp" },{ name = "tree-sitter-go" },{ name = "tree-sitter-java" },{ name = "tree-sitter-javascript" },+ { name = "tree-sitter-kotlin" },+ { name = "tree-sitter-php" },{ name = "tree-sitter-python" },+ { name = "tree-sitter-ruby" },{ name = "tree-sitter-rust" },+ { name = "tree-sitter-scala" },+ { name = "tree-sitter-swift" },{ name = "tree-sitter-typescript" },{ name = "uvicorn", extra = ["standard"] },{ name = "watchdog" },@@ -3120,12 +3126,18 @@ requires-dist = [{ name = "tenacity", specifier = ">=9,<10" },{ name = "time-machine", marker = "extra == 'dev'", specifier = ">=2.14,<3" },{ name = "tree-sitter", specifier = ">=0.23,<1" },+ { name = "tree-sitter-c-sharp", specifier = ">=0.23,<1" },{ name = "tree-sitter-cpp", specifier = ">=0.23,<1" },{ name = "tree-sitter-go", specifier = ">=0.23,<1" },{ name = "tree-sitter-java", specifier = ">=0.23,<1" },{ name = "tree-sitter-javascript", specifier = ">=0.23,<1" },+ { name = "tree-sitter-kotlin", specifier = ">=1,<2" },+ { name = "tree-sitter-php", specifier = ">=0.23,<1" },{ name = "tree-sitter-python", specifier = ">=0.23,<1" },+ { name = "tree-sitter-ruby", specifier = ">=0.23,<1" },{ name = "tree-sitter-rust", specifier = ">=0.23,<1" },+ { name = "tree-sitter-scala", specifier = ">=0.23,<1" },+ { name = "tree-sitter-swift", specifier = ">=0.0.1" },{ name = "tree-sitter-typescript", specifier = ">=0.23,<1" },{ name = "types-networkx", marker = "extra == 'dev'", specifier = ">=3.3,<4" },{ name = "uvicorn", extras = ["standard"], specifier = ">=0.32,<1" },@@ -3888,6 +3900,21 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/a6/6e/e64621037357acb83d912276ffd30a859ef117f9c680f2e3cb955f47c680/tree_sitter-0.25.2-cp314-cp314-win_arm64.whl", hash = "sha256:b8d4429954a3beb3e844e2872610d2a4800ba4eb42bb1990c6a4b1949b18459f", size = 117470, upload-time = "2025-09-25T17:37:58.431Z" },]+[[package]]+name = "tree-sitter-c-sharp"+version = "0.23.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/22/85/a61c782afbb706a47d990eaee6977e7c2bd013771c5bf5c81c617684f286/tree_sitter_c_sharp-0.23.1.tar.gz", hash = "sha256:322e2cfd3a547a840375276b2aea3335fa6458aeac082f6c60fec3f745c967eb", size = 1317728, upload-time = "2024-11-11T05:25:32.535Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/58/04/f6c2df4c53a588ccd88d50851155945cff8cd887bd70c175e00aaade7edf/tree_sitter_c_sharp-0.23.1-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:2b612a6e5bd17bb7fa2aab4bb6fc1fba45c94f09cb034ab332e45603b86e32fd", size = 372235, upload-time = "2024-11-11T05:25:19.424Z" },+ { url = "https://files.pythonhosted.org/packages/99/10/1aa9486f1e28fc22810fa92cbdc54e1051e7f5536a5e5b5e9695f609b31e/tree_sitter_c_sharp-0.23.1-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:1a8b98f62bc53efcd4d971151950c9b9cd5cbe3bacdb0cd69fdccac63350d83e", size = 419046, upload-time = "2024-11-11T05:25:20.679Z" },+ { url = "https://files.pythonhosted.org/packages/0f/21/13df29f8fcb9ba9f209b7b413a4764b673dfd58989a0dd67e9c7e19e9c2e/tree_sitter_c_sharp-0.23.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:986e93d845a438ec3c4416401aa98e6a6f6631d644bbbc2e43fcb915c51d255d", size = 415999, upload-time = "2024-11-11T05:25:22.359Z" },+ { url = "https://files.pythonhosted.org/packages/ca/72/fc6846795bcdae2f8aa94cc8b1d1af33d634e08be63e294ff0d6794b1efc/tree_sitter_c_sharp-0.23.1-cp39-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a8024e466b2f5611c6dc90321f232d8584893c7fb88b75e4a831992f877616d2", size = 402830, upload-time = "2024-11-11T05:25:24.198Z" },+ { url = "https://files.pythonhosted.org/packages/fe/3a/b6028c5890ce6653807d5fa88c72232c027c6ceb480dbeb3b186d60e5971/tree_sitter_c_sharp-0.23.1-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:7f9bf876866835492281d336b9e1f9626ab668737f74e914c31d285261507da7", size = 397880, upload-time = "2024-11-11T05:25:25.937Z" },+ { url = "https://files.pythonhosted.org/packages/47/d2/4facaa34b40f8104d8751746d0e1cd2ddf0beb9f1404b736b97f372bd1f3/tree_sitter_c_sharp-0.23.1-cp39-abi3-win_amd64.whl", hash = "sha256:ae9a9e859e8f44e2b07578d44f9a220d3fa25b688966708af6aa55d42abeebb3", size = 377562, upload-time = "2024-11-11T05:25:27.539Z" },+ { url = "https://files.pythonhosted.org/packages/d8/88/3cf6bd9959d94d1fec1e6a9c530c5f08ff4115a474f62aedb5fedb0f7241/tree_sitter_c_sharp-0.23.1-cp39-abi3-win_arm64.whl", hash = "sha256:c81548347a93347be4f48cb63ec7d60ef4b0efa91313330e69641e49aa5a08c5", size = 375157, upload-time = "2024-11-11T05:25:30.839Z" },+]+[[package]]name = "tree-sitter-cpp"version = "0.23.4"@@ -3950,6 +3977,35 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/2e/1f/f9eba1038b7d4394410f3c0a6ec2122b590cd7acb03f196e52fa57ebbe72/tree_sitter_javascript-0.25.0-cp310-abi3-win_arm64.whl", hash = "sha256:622a69d677aa7f6ee2931d8c77c981a33f0ebb6d275aa9d43d3397c879a9bb0b", size = 61668, upload-time = "2025-09-01T07:13:43.803Z" },]+[[package]]+name = "tree-sitter-kotlin"+version = "1.1.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/58/bb/bdab3665eeca21246130eec79c76e42456cfa72d59606266ecdbf37f9a96/tree_sitter_kotlin-1.1.0.tar.gz", hash = "sha256:322a35bdae75e25ae64dae6027be609c5422fab282084117816c4ebcda6168da", size = 1095728, upload-time = "2025-01-09T19:02:18.492Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/2c/a5/ce5a2ba7b97db8d90c89516674f5c46e2d41503e00dd743ba7aad4661097/tree_sitter_kotlin-1.1.0-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:6cca5ef06d090e8494ac1d9f0aac71ed32207d412766b5df7da00d94334181a2", size = 312883, upload-time = "2025-01-09T19:02:02.931Z" },+ { url = "https://files.pythonhosted.org/packages/7d/20/66105b6e94d062440955d374e64d030c3173cf4f592f6a6a3c426b3c94d0/tree_sitter_kotlin-1.1.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:910b41a580dae00d319e555075f3886a41386d1067931b14c7de504eeae3ae2a", size = 337016, upload-time = "2025-01-09T19:02:04.174Z" },+ { url = "https://files.pythonhosted.org/packages/f7/4c/e1ef38fe412fa9851403fc75a653f2b69bbe1e11e2e7faf219631ebe7e4a/tree_sitter_kotlin-1.1.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:906e5444ebb01db439cb3ad65913598a4ea957b0e068aa973265926a17eb00e0", size = 359927, upload-time = "2025-01-09T19:02:06.312Z" },+ { url = "https://files.pythonhosted.org/packages/65/bd/0f3aac45eb88b6b3173ac9c23bc41d8865943cbbe1caaafc001cd1b73c90/tree_sitter_kotlin-1.1.0-cp39-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:9a92afe24b634cf914c5812af0f5c53184b1c18bdf6ee5505c83afac81f6bf6c", size = 339269, upload-time = "2025-01-09T19:02:08.644Z" },+ { url = "https://files.pythonhosted.org/packages/08/dc/4944abf3a8bc630262e93e0857bd7044d521995c1f6af50650e4fe1fdde0/tree_sitter_kotlin-1.1.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:5960034a5c5bcc7ccb21dc7a29e4267ac4f0ef37884f39d75695eac7f004deff", size = 328921, upload-time = "2025-01-09T19:02:10.346Z" },+ { url = "https://files.pythonhosted.org/packages/24/c9/5cca0a44db41224f7f10992450af17ff432c1a336852efb312246d5705e5/tree_sitter_kotlin-1.1.0-cp39-abi3-win_amd64.whl", hash = "sha256:d4d3f330f515ba8b91da04a5335eb9ff3ce071c7b7855958912f2560f6e14976", size = 315933, upload-time = "2025-01-09T19:02:12.637Z" },+ { url = "https://files.pythonhosted.org/packages/fb/b9/12fa97f63d2b7517c6f5d16938f0c5bfe84d925c652c75ff1c5e29bf6a44/tree_sitter_kotlin-1.1.0-cp39-abi3-win_arm64.whl", hash = "sha256:e030f127a7d07952907adb9070248bd42fb86dc76fd92744727551b50e131ee7", size = 310414, upload-time = "2025-01-09T19:02:16.23Z" },+]++[[package]]+name = "tree-sitter-php"+version = "0.24.1"+source = { registry = "https://pypi.org/simple" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/a4/c8/1a499038cb4036bea1d560ffbc807a6fb940261aa22296bd49a62ed8bcba/tree_sitter_php-0.24.1-cp310-abi3-macosx_10_9_x86_64.whl", hash = "sha256:d56e2dcf025450f84a2cdbf4b18a09e6cb88b92e9e6858e63de3d4133ab2e43e", size = 219550, upload-time = "2025-08-16T22:14:30.212Z" },+ { url = "https://files.pythonhosted.org/packages/ab/5e/b52f2599acb29f6899470f7137d3d491c752b88df3950fb7408aea57ddca/tree_sitter_php-0.24.1-cp310-abi3-macosx_11_0_arm64.whl", hash = "sha256:29759c67d4c27a68c227ed82c0b7e4699617b1bd23757d50c081f81a12b4f80d", size = 229632, upload-time = "2025-08-16T22:14:31.85Z" },+ { url = "https://files.pythonhosted.org/packages/6b/58/ca290da45380bd6ba7c6b0b98cc5fc30325c32c7f14f0c93196a451b19c4/tree_sitter_php-0.24.1-cp310-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:94b89832ac09f078eed2acd88598838bc51012224cbcebb916dbb6a37e74357e", size = 325351, upload-time = "2025-08-16T22:14:33Z" },+ { url = "https://files.pythonhosted.org/packages/9a/c6/fd863a7a779d0ab67688939eba0e08bff7b1ffe731288d3d3610df21217b/tree_sitter_php-0.24.1-cp310-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:7a1404a30f2972498ace040b0029738b8dac45d0a12932ccb8b605eb94bafbe4", size = 313021, upload-time = "2025-08-16T22:14:34.394Z" },+ { url = "https://files.pythonhosted.org/packages/48/ed/aace12f30c4f5474a9ad0e9da85c060174e3764342c9860974bb0feb02fc/tree_sitter_php-0.24.1-cp310-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:3e96f61462a960c78e5389c7ba6c16c25e66b465c763b8e63ad66423326c2fa7", size = 305905, upload-time = "2025-08-16T22:14:35.846Z" },+ { url = "https://files.pythonhosted.org/packages/4e/c4/6c690c33b1ae9cae9505c0a2896f046fda174d72c46bdafce6aab3b2f2e7/tree_sitter_php-0.24.1-cp310-abi3-win_amd64.whl", hash = "sha256:1a1b65b72a8410d421f914ee13d38fd546a94d01cb834f69b27c78ba7589a5b5", size = 208014, upload-time = "2025-08-16T22:14:37.206Z" },+ { url = "https://files.pythonhosted.org/packages/7b/69/54c670d725c092b89e76ca6984582b6a768b128ac1859ed48141b124da1d/tree_sitter_php-0.24.1-cp310-abi3-win_arm64.whl", hash = "sha256:56a70c5ef1bddb15f220a479b2f2edf3042c764b6c443921fbd7ca9174d664e3", size = 206033, upload-time = "2025-08-16T22:14:38.632Z" },+]+[[package]]name = "tree-sitter-python"version = "0.25.0"@@ -3966,6 +4022,21 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/07/19/4b5569d9b1ebebb5907d11554a96ef3fa09364a30fcfabeff587495b512f/tree_sitter_python-0.25.0-cp310-abi3-win_arm64.whl", hash = "sha256:0fbf6a3774ad7e89ee891851204c2e2c47e12b63a5edbe2e9156997731c128bb", size = 74169, upload-time = "2025-09-11T06:47:56.747Z" },]+[[package]]+name = "tree-sitter-ruby"+version = "0.23.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/09/5b/6d24be4fde4743481bd8e3fd24b434870cb6612238c8544b71fe129ed850/tree_sitter_ruby-0.23.1.tar.gz", hash = "sha256:886ed200bfd1f3ca7628bf1c9fefd42421bbdba70c627363abda67f662caa21e", size = 489602, upload-time = "2024-11-11T04:51:30.328Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/23/2e/2717b9451c712b60f833827a696baf29d8e50a0f7dccbf22a8d7006cc19e/tree_sitter_ruby-0.23.1-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:39f391322d2210843f07081182dbf00f8f69cfbfa4687b9575cac6d324bae443", size = 177959, upload-time = "2024-11-11T04:51:19.958Z" },+ { url = "https://files.pythonhosted.org/packages/e7/38/c41ecf7692b8ecccd26861d3293a88150a4a52fc081abe60f837030d7315/tree_sitter_ruby-0.23.1-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:aa4ee7433bd42fac22e2dad4a3c0f332292ecf482e610316828c711a0bb7f794", size = 195069, upload-time = "2024-11-11T04:51:21.82Z" },+ { url = "https://files.pythonhosted.org/packages/d8/01/14ef2d5107e6f42b64a400c3bbc3dd3b8fd24c3cef5306004ae03668f231/tree_sitter_ruby-0.23.1-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62b36813a56006b7569db7868f6b762caa3f4e419bd0f8cf9ccbb4abb1b6254c", size = 226761, upload-time = "2024-11-11T04:51:23.021Z" },+ { url = "https://files.pythonhosted.org/packages/23/dd/1171b5dd25da10f768732a20fb62d2e3ae66e3b42329351f2ce5bf723abb/tree_sitter_ruby-0.23.1-cp39-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f7bcd93972b4ca2803856d4fe0fbd04123ff29c4592bbb9f12a27528bd252341", size = 214427, upload-time = "2024-11-11T04:51:24.854Z" },+ { url = "https://files.pythonhosted.org/packages/60/bc/de76c877a90fd8a62cd60f496d7832efddc1b18a148593d9aa9b4a9ce5e0/tree_sitter_ruby-0.23.1-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:66c65d6c2a629783ca4ab2bab539bd6f271ce6f77cacb62845831e11665b5bd3", size = 210409, upload-time = "2024-11-11T04:51:26.093Z" },+ { url = "https://files.pythonhosted.org/packages/dd/4a/f5bcca350b84cdf75a53e918b8efa06c46ed650d99d3ef22195e9d8020cc/tree_sitter_ruby-0.23.1-cp39-abi3-win_amd64.whl", hash = "sha256:02e2c19ebefe29226c14aa63e11e291d990f5b5c20a99940ab6e7eda44e744e5", size = 179843, upload-time = "2024-11-11T04:51:27.265Z" },+ { url = "https://files.pythonhosted.org/packages/71/5c/a2e068ad4b2c4ba9b774a88b24149168d3bcd94f58b964e49dcabfe5fd24/tree_sitter_ruby-0.23.1-cp39-abi3-win_arm64.whl", hash = "sha256:ed042007e89f2cceeb1cbdd8b0caa68af1e2ce54c7eb2053ace760f90657ac9f", size = 178025, upload-time = "2024-11-11T04:51:29.051Z" },+]+[[package]]name = "tree-sitter-rust"version = "0.24.0"@@ -3981,6 +4052,36 @@ wheels = [{ url = "https://files.pythonhosted.org/packages/c8/33/70b320d24cd127d6ca427d2bef1279830f0786a1f2cde160f59b4fb80728/tree_sitter_rust-0.24.0-cp39-abi3-win_arm64.whl", hash = "sha256:7a0538eaf4063b443c6cd80a47df19249f65e27dbdf129396a9193749912d0c0", size = 128583, upload-time = "2025-04-01T21:06:02.58Z" },]+[[package]]+name = "tree-sitter-scala"+version = "0.24.0"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/70/56/aa5e5c6de49bae3de1d7270e3e38a2a1e08fee0a1ed24dc68a73ab650dfa/tree_sitter_scala-0.24.0.tar.gz", hash = "sha256:9d01b24bf6de3d1e60250ccda3ee12d388f85a16b5e96d5b640f69b8e222a358", size = 1132120, upload-time = "2025-06-08T18:16:37.058Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/82/eb/df8c7b88f0042847c8c48c45aea451665fdbb158695dc3c4a000f11eaa6b/tree_sitter_scala-0.24.0-cp39-abi3-macosx_10_9_x86_64.whl", hash = "sha256:db4563205cb1b113b0926c95ca01a1823a9bca5b34e8b59f30127391996fe22d", size = 485915, upload-time = "2025-06-08T18:16:28.003Z" },+ { url = "https://files.pythonhosted.org/packages/a5/0f/0de4762c9efefc04be4d9d2c622848bdad00cb55191c30ecc169c3c6bbe1/tree_sitter_scala-0.24.0-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:0cd8cec453d63eee51b0b933d6b0ff6d5aeed2742b56c9d1e99e4aab1e1b0839", size = 516315, upload-time = "2025-06-08T18:16:29.23Z" },+ { url = "https://files.pythonhosted.org/packages/cd/4c/25d06b83baf1d4d104ab4d47fa003ed312f5422d6dc19f6336ac6c704938/tree_sitter_scala-0.24.0-cp39-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:55d298756b993ac09c140e82bc822e68f430bb654f0e06e4e8d41b9750a94c91", size = 544227, upload-time = "2025-06-08T18:16:30.411Z" },+ { url = "https://files.pythonhosted.org/packages/3f/22/21a75e5cf376e21209b83f8adb993a72668e14f9596d14d13980de837255/tree_sitter_scala-0.24.0-cp39-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f0139fb3af638b106b2400cb30a364e71a0f17a044402068ba6686c919476a95", size = 544124, upload-time = "2025-06-08T18:16:31.911Z" },+ { url = "https://files.pythonhosted.org/packages/82/d0/45ddd0420cc9c08b21a7f62cbb662cbd5020cf0ef22d0ccebf07cf20f190/tree_sitter_scala-0.24.0-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:03da3b1a574d67aea41de1297eed0b36373636558ecfb7de70024cd4ef892d33", size = 592991, upload-time = "2025-06-08T18:16:33.501Z" },+ { url = "https://files.pythonhosted.org/packages/16/17/549c50360734cc2be73572f7a5055f0c703c6c63502161e3ee4dd7395e64/tree_sitter_scala-0.24.0-cp39-abi3-win_amd64.whl", hash = "sha256:a300c6e18fbaaf7d645bd66e598c9577ca3f9a34d0976db0ee7259dc4ed145bb", size = 475343, upload-time = "2025-06-08T18:16:34.596Z" },+ { url = "https://files.pythonhosted.org/packages/79/08/2f2d3895a387b3b8c04e6d9050b4436aaac0103fc31dc2354cd162e0d217/tree_sitter_scala-0.24.0-cp39-abi3-win_arm64.whl", hash = "sha256:5123eef2d5ef55e47943f958ad78605e20d1eec54926cd3296d8c6fc006b2ed7", size = 479012, upload-time = "2025-06-08T18:16:35.714Z" },+]++[[package]]+name = "tree-sitter-swift"+version = "0.0.1"+source = { registry = "https://pypi.org/simple" }+sdist = { url = "https://files.pythonhosted.org/packages/37/f7/35337caea29e24bb2f55d0499db53bcb879ff0eb2011e1fa567d5edab4b7/tree_sitter_swift-0.0.1.tar.gz", hash = "sha256:d43b0baf413ba4b049f92eadc074805cb6403655c905d3af24f12fce1c9f561b", size = 914654, upload-time = "2025-06-30T05:49:24.642Z" }+wheels = [+ { url = "https://files.pythonhosted.org/packages/f0/f2/2e24418b486303b3ce5c6f5eef8eaa9ca2800151c02bb91e8b1da1650601/tree_sitter_swift-0.0.1-cp38-abi3-macosx_10_9_x86_64.whl", hash = "sha256:45d8d61c3dc9b72ec721ed93e5920d24f87bd6350298bc7c4edc261066cda745", size = 326139, upload-time = "2025-06-30T05:49:16.878Z" },+ { url = "https://files.pythonhosted.org/packages/87/e0/811e80c9f68d49dbec2131b98fe3ba61d3e8d22f175885a9dd272bf5873c/tree_sitter_swift-0.0.1-cp38-abi3-macosx_11_0_arm64.whl", hash = "sha256:c669e830cfeec55d326c79478e25465e1b61207fdb9d5459533fd5f735051d20", size = 347863, upload-time = "2025-06-30T05:49:18.26Z" },+ { url = "https://files.pythonhosted.org/packages/6a/f0/6abf3a4524286d6f1397b60715be56f241cd5a3f62c842ad19513c7f3044/tree_sitter_swift-0.0.1-cp38-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3caac02783238e9c72349bc4a8db11be258666d5ae1856ac54c46ca6086ecfc9", size = 426609, upload-time = "2025-06-30T05:49:19.426Z" },+ { url = "https://files.pythonhosted.org/packages/f7/0c/d77ed1d313c4b2360fd7ffa558be796875f400b7eb09efc3373700ffef34/tree_sitter_swift-0.0.1-cp38-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d009e46d9800cf5ca3c585163d04c70660d1383f350dad93d08bf00735d2714b", size = 376564, upload-time = "2025-06-30T05:49:20.623Z" },+ { url = "https://files.pythonhosted.org/packages/46/06/fbe2d9f0de0df3e8515b54d88ef63deaad865d70a8789d80e2cdc87c7452/tree_sitter_swift-0.0.1-cp38-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:f61776dbf4bcb3fd9a852c69a3f61d08abaad4dd22272bf04272f7ed26aa6d75", size = 353064, upload-time = "2025-06-30T05:49:21.554Z" },+ { url = "https://files.pythonhosted.org/packages/5e/b6/3b3a13d28e8ca2cd3a8c48fe2e94beb57314075f5a7881df0f1fc5e3d50e/tree_sitter_swift-0.0.1-cp38-abi3-win_amd64.whl", hash = "sha256:4ca542091e411b2236c862a38e1c1b34323c909f011c122c10747e6010e13693", size = 334094, upload-time = "2025-06-30T05:49:22.803Z" },+ { url = "https://files.pythonhosted.org/packages/ee/d3/3dd83cc13e55282f25d44a19069dd31f19131e14b5619cd52a870151d4bb/tree_sitter_swift-0.0.1-cp38-abi3-win_arm64.whl", hash = "sha256:ce3add5c7156e2e5329e675e7ac6a3389cb1e9ebff18c9248538e54fc738390d", size = 329505, upload-time = "2025-06-30T05:49:23.714Z" },+]+[[package]]name = "tree-sitter-typescript"version = "0.23.2"diff --git a/website/concepts.md b/website/concepts.mdindex 36a45379a..3593cb3b8 100644--- a/website/concepts.md+++ b/website/concepts.md@@ -65,7 +65,7 @@ From this, repowise builds a **dependency graph** using NetworkX. Nodes are file**Why it matters for you:** The dependency graph powers risk analysis, cascade detection, and architecture diagrams. When you ask "what does this module affect?", the answer comes from this layer.-**Supported languages:** Python, TypeScript, JavaScript, Go, Rust, Java, C, C++, Kotlin, Ruby. More are added regularly.+**Supported languages:** Python, TypeScript, JavaScript, Go, Rust, Java, C, C++, Kotlin, Ruby, C#, Swift, Scala, PHP. 14 languages with full AST support.---diff --git a/website/index.md b/website/index.mdindex 5cc2f7804..1534f8a3f 100644--- a/website/index.md+++ b/website/index.md@@ -26,7 +26,7 @@ repowise generates and maintains a structured wiki for any codebase. It tracks c| **Decision intelligence** | Captures *why* code is structured the way it is || **MCP server** | 10 tools for AI assistants (Claude Code, Cursor, Windsurf, Cline) || **Web dashboard** | Browse wiki, search, and explore architecture diagrams |-| **Multi-language** | Python, TypeScript, JavaScript, Go, Rust, Java, C/C++, Kotlin, Ruby |+| **Multi-language** | Python, TypeScript, JavaScript, Go, Rust, Java, C/C++, Kotlin, Ruby, C#, Swift, Scala, PHP |---