Skip to content

Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.

v0.4: Pipeline quality improvements, snippet tool optimization

Martin Vogel1ff78eae2d39
diff --git a/internal/httplink/httplink.go b/internal/httplink/httplink.go
index 9a2358b45..b4eb4fd15 100644
--- a/internal/httplink/httplink.go
+++ b/internal/httplink/httplink.go
@@ -313,7 +313,31 @@ func (l *Linker) linkHandlerToRoute(handlerNode *store.Node, routeID int64, rout
}
}
+// isTestNode returns true if the node is from a test file.
+// Checks the is_test property set during pipeline pass 1, with a file path heuristic fallback.
+func isTestNode(n *store.Node) bool {
+ if isTest, ok := n.Properties["is_test"].(bool); ok && isTest {
+ return true
+ }
+ // Fallback: common test path patterns
+ fp := filepath.ToSlash(n.FilePath)
+ return containsTestSegment(fp, "test") ||
+ containsTestSegment(fp, "tests") ||
+ containsTestSegment(fp, "__tests__") ||
+ strings.Contains(fp, "_test.") ||
+ strings.Contains(fp, ".test.") ||
+ strings.Contains(fp, ".spec.")
+}
+
+// containsTestSegment checks if a path contains a directory segment named seg.
+// Matches both "seg/..." (at start) and ".../seg/..." (mid-path).
+func containsTestSegment(fp, seg string) bool {
+ return strings.HasPrefix(fp, seg+"/") || strings.Contains(fp, "/"+seg+"/")
+}
+
// discoverRoutes finds route handler registrations from Function nodes.
+//
+//nolint:gocognit // WHY: inherent complexity from multi-framework route discovery
func (l *Linker) discoverRoutes(rootPath string) []RouteHandler {
var routes []RouteHandler
@@ -334,6 +358,11 @@ func (l *Linker) discoverRoutes(rootPath string) []RouteHandler {
phpFilesWithFuncs := map[string]bool{}
for _, f := range funcs {
+ // Skip test files — test fixtures should not produce Route nodes
+ if isTestNode(f) {
+ continue
+ }
+
// Python: check decorators property
routes = append(routes, extractPythonRoutes(f)...)
@@ -371,6 +400,11 @@ func (l *Linker) discoverRoutes(rootPath string) []RouteHandler {
}
for _, m := range modules {
+ // Skip test files
+ if isTestNode(m) {
+ continue
+ }
+
isPHP := strings.HasSuffix(m.FilePath, ".php")
isJSTS := strings.HasSuffix(m.FilePath, ".js") ||
strings.HasSuffix(m.FilePath, ".ts") ||
diff --git a/internal/httplink/httplink_test.go b/internal/httplink/httplink_test.go
index 4eaf2e89a..5d6dbf93a 100644
--- a/internal/httplink/httplink_test.go
+++ b/internal/httplink/httplink_test.go
@@ -1441,3 +1441,30 @@ Route::get('/api/orders/{id}', [OrderController::class, 'show']);
}
}
}
+
+func TestIsTestNodeFiltering(t *testing.T) {
+ tests := []struct {
+ filePath string
+ isTest bool
+ expected bool
+ }{
+ {"src/routes/api.js", false, false},
+ {"test/app.get.js", false, true},
+ {"__tests__/routes.test.ts", false, true},
+ {"src/routes/api.js", true, true},
+ {"lib/router/index.js", false, false},
+ {"tests/fixtures/server.js", false, true},
+ {"app/controllers/orders_controller.rb", false, false},
+ }
+
+ for _, tt := range tests {
+ n := &store.Node{
+ FilePath: tt.filePath,
+ Properties: map[string]any{"is_test": tt.isTest},
+ }
+ got := isTestNode(n)
+ if got != tt.expected {
+ t.Errorf("isTestNode(%q, is_test=%v) = %v, want %v", tt.filePath, tt.isTest, got, tt.expected)
+ }
+ }
+}
diff --git a/internal/lang/elixir.go b/internal/lang/elixir.go
index 0f3e0ca2a..3bcaee9c7 100644
--- a/internal/lang/elixir.go
+++ b/internal/lang/elixir.go
@@ -12,7 +12,7 @@ func init() {
},
ClassNodeTypes: []string{}, // handled by custom extraction (defmodule)
ModuleNodeTypes: []string{"source"},
- CallNodeTypes: []string{"call", "dot"},
+ CallNodeTypes: []string{"call", "dot", "binary_operator"},
ImportNodeTypes: []string{"call"},
BranchingNodeTypes: []string{
diff --git a/internal/lang/ocaml.go b/internal/lang/ocaml.go
index cccb2e0e9..3fb663067 100644
--- a/internal/lang/ocaml.go
+++ b/internal/lang/ocaml.go
@@ -13,7 +13,7 @@ func init() {
"module_definition", // module M = struct ... end
},
ModuleNodeTypes: []string{"compilation_unit"},
- CallNodeTypes: []string{"application", "infix_expression"},
+ CallNodeTypes: []string{"application_expression", "infix_expression"},
ImportNodeTypes: []string{"open_module"},
BranchingNodeTypes: []string{
diff --git a/internal/lang/perl.go b/internal/lang/perl.go
index f750f11a1..16642413c 100644
--- a/internal/lang/perl.go
+++ b/internal/lang/perl.go
@@ -10,7 +10,7 @@ func init() {
ClassNodeTypes: []string{},
FieldNodeTypes: []string{},
ModuleNodeTypes: []string{"source_file"},
- CallNodeTypes: []string{"ambiguous_function_call_expression", "function_call_expression"},
+ CallNodeTypes: []string{"ambiguous_function_call_expression", "function_call_expression", "func1op_call_expression"},
ImportNodeTypes: []string{"use_statement", "require_statement"},
BranchingNodeTypes: []string{
"if_statement", "unless_statement", "for_statement",
diff --git a/internal/lang/sql.go b/internal/lang/sql.go
index 07177ccd7..906db0877 100644
--- a/internal/lang/sql.go
+++ b/internal/lang/sql.go
@@ -10,7 +10,7 @@ func init() {
},
ClassNodeTypes: []string{},
FieldNodeTypes: []string{"column_definition"},
- CallNodeTypes: []string{"function_call"},
+ CallNodeTypes: []string{"function_call", "invocation"},
ImportNodeTypes: []string{},
VariableNodeTypes: []string{
"create_table",
diff --git a/internal/pipeline/astdump_test.go b/internal/pipeline/astdump_test.go
index c5dad91f9..3952c6787 100644
--- a/internal/pipeline/astdump_test.go
+++ b/internal/pipeline/astdump_test.go
@@ -301,9 +301,107 @@ var astDumpCases = []struct {
{"sql_func_call", lang.SQL, "SELECT count(*), upper(name) FROM users;\n"},
{"sql_view", lang.SQL, "CREATE VIEW active_users AS SELECT * FROM users WHERE active = true;\n"},
+ // === C# call AST diagnostics ===
+ {"csharp_member_call", lang.CSharp, "class A {\n\tvoid F() {\n\t\t_context.SaveChangesAsync(token);\n\t\tentity.AddDomainEvent(new Event());\n\t\tvar x = _identityService.GetUserNameAsync(userId);\n\t}\n}\n"},
+ {"csharp_static_call", lang.CSharp, "class A {\n\tvoid F() {\n\t\tConsole.WriteLine(\"hello\");\n\t\tstring.IsNullOrEmpty(s);\n\t}\n}\n"},
+ {"csharp_simple_call", lang.CSharp, "class A {\n\tvoid F() {\n\t\tDoWork();\n\t\tawait SaveAsync();\n\t}\n}\n"},
+ {"csharp_await_call", lang.CSharp, "class A {\n\tasync Task F() {\n\t\tawait _context.SaveChangesAsync(token);\n\t\tvar result = await next();\n\t}\n}\n"},
+ {"csharp_new_object", lang.CSharp, "class A {\n\tvoid F() {\n\t\tvar e = new TodoItem();\n\t\tvar list = new List<string>();\n\t}\n}\n"},
+
+ // === Ruby call AST diagnostics ===
+ {"ruby_method_call", lang.Ruby, "class A\n def f\n name.to_s\n @items.each { |i| puts i }\n response.status = 200\n end\nend\n"},
+ {"ruby_bare_call", lang.Ruby, "class A\n def f\n puts 'hello'\n greet('world')\n render json: data\n end\nend\n"},
+ {"ruby_chain_call", lang.Ruby, "class A\n def f\n users.where(active: true).order(:name).limit(10)\n end\nend\n"},
+
// === New languages: Dockerfile ===
{"dockerfile_from", lang.Dockerfile, "FROM golang:1.22-alpine AS builder\nWORKDIR /app\nCOPY . .\nRUN go build -o main .\n"},
{"dockerfile_env", lang.Dockerfile, "ENV APP_PORT=8080\nARG VERSION=latest\nEXPOSE 8080\n"},
+
+ // =====================================================================
+ // v0.5 Documentation Cases — Complex patterns for extraction planning
+ // =====================================================================
+
+ // === Framework Patterns: Express/Gin/Chi routes ===
+ {"js_express_route", lang.JavaScript, "app.get('/users/:id', async (req, res) => {\n const user = await db.findUser(req.params.id);\n res.json(user);\n});\n"},
+ {"js_express_middleware", lang.JavaScript, "app.use('/api', authMiddleware, rateLimit({ max: 100 }));\n"},
+ {"ts_express_typed_route", lang.TypeScript, "router.post('/orders', validate(OrderSchema), async (req: Request, res: Response) => {\n const order = await orderService.create(req.body);\n res.status(201).json(order);\n});\n"},
+ {"go_chi_route", lang.Go, "package main\nfunc routes(r chi.Router) {\n\tr.Get(\"/users/{id}\", getUser)\n\tr.Post(\"/users\", createUser)\n\tr.Route(\"/admin\", func(r chi.Router) {\n\t\tr.Use(adminOnly)\n\t\tr.Get(\"/stats\", getStats)\n\t})\n}\n"},
+
+ // === Framework Patterns: Spring/Django/Laravel annotations ===
+ {"java_spring_controller", lang.Java, "@RestController\n@RequestMapping(\"/api/users\")\nclass UserController {\n\t@Autowired\n\tprivate UserService userService;\n\t@GetMapping(\"/{id}\")\n\tpublic User getUser(@PathVariable Long id) {\n\t\treturn userService.findById(id);\n\t}\n}\n"},
+ {"java_spring_service", lang.Java, "@Service\nclass UserService {\n\t@Transactional\n\tpublic User createUser(CreateUserRequest req) {\n\t\tUser user = new User(req.getName());\n\t\treturn repository.save(user);\n\t}\n}\n"},
+ {"php_laravel_route", lang.PHP, "<?php\nRoute::middleware('auth')->group(function () {\n\tRoute::get('/dashboard', [DashboardController::class, 'index']);\n\tRoute::resource('posts', PostController::class);\n});\n"},
+
+ // === Framework Patterns: Ruby Sinatra/Rails DSL ===
+ {"ruby_sinatra_route", lang.Ruby, "class App < Sinatra::Base\n get '/users/:id' do\n user = User.find(params[:id])\n json user\n end\n\n post '/users' do\n user = User.create(params)\n status 201\n json user\n end\nend\n"},
+ {"ruby_rails_model", lang.Ruby, "class User < ApplicationRecord\n has_many :posts, dependent: :destroy\n belongs_to :organization\n validates :email, presence: true, uniqueness: true\n scope :active, -> { where(active: true) }\nend\n"},
+
+ // === Framework Patterns: Elixir Phoenix ===
+ {"elixir_phoenix_router", lang.Elixir, "defmodule MyAppWeb.Router do\n use MyAppWeb, :router\n pipeline :api do\n plug :accepts, [\"json\"]\n end\n scope \"/api\", MyAppWeb do\n pipe_through :api\n resources \"/users\", UserController\n end\nend\n"},
+
+ // === Async Patterns ===
+ {"ts_async_await", lang.TypeScript, "async function fetchData(): Promise<User[]> {\n const response = await fetch('/api/users');\n if (!response.ok) throw new Error('Failed');\n return await response.json();\n}\n"},
+ {"rust_async_await", lang.Rust, "async fn fetch_user(id: u64) -> Result<User, Error> {\n\tlet resp = client.get(format!(\"/users/{}\", id)).send().await?;\n\tlet user: User = resp.json().await?;\n\tOk(user)\n}\n"},
+ {"python_async_gather", lang.Python, "async def fetch_all(ids):\n tasks = [fetch_user(id) for id in ids]\n results = await asyncio.gather(*tasks)\n return results\n"},
+ {"kotlin_coroutine", lang.Kotlin, "suspend fun fetchUsers(): List<User> {\n\treturn withContext(Dispatchers.IO) {\n\t\tval response = api.getUsers()\n\t\tresponse.body() ?: emptyList()\n\t}\n}\n"},
+ {"go_goroutine_channel", lang.Go, "package main\nfunc process(ctx context.Context, items []Item) error {\n\terrCh := make(chan error, len(items))\n\tfor _, item := range items {\n\t\tgo func(it Item) {\n\t\t\terrCh <- handle(ctx, it)\n\t\t}(item)\n\t}\n\tfor range items {\n\t\tif err := <-errCh; err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n"},
+
+ // === Error Handling Patterns ===
+ {"ts_try_catch_finally", lang.TypeScript, "async function safeFetch(url: string): Promise<Data | null> {\n try {\n const res = await fetch(url);\n return await res.json();\n } catch (err) {\n logger.error('fetch failed', { url, err });\n return null;\n } finally {\n metrics.recordFetch(url);\n }\n}\n"},
+ {"rust_question_mark_chain", lang.Rust, "fn process(path: &str) -> Result<Config, Error> {\n\tlet data = std::fs::read_to_string(path)?;\n\tlet config: Config = serde_json::from_str(&data)?;\n\tconfig.validate()?;\n\tOk(config)\n}\n"},
+ {"go_error_wrap", lang.Go, "package main\nimport \"fmt\"\nfunc loadConfig(path string) (*Config, error) {\n\tdata, err := os.ReadFile(path)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"read config: %w\", err)\n\t}\n\tvar cfg Config\n\tif err := json.Unmarshal(data, &cfg); err != nil {\n\t\treturn nil, fmt.Errorf(\"parse config: %w\", err)\n\t}\n\treturn &cfg, nil\n}\n"},
+ {"python_exception_chain", lang.Python, "def process(data):\n try:\n result = validate(data)\n except ValidationError as e:\n raise ProcessingError(f'invalid: {e}') from e\n except TimeoutError:\n raise RetryableError('timeout') from None\n"},
+ {"java_multi_catch", lang.Java, "class A {\n\tvoid process() {\n\t\ttry {\n\t\t\triskyOperation();\n\t\t} catch (IOException | SQLException e) {\n\t\t\tlogger.error(\"Operation failed\", e);\n\t\t\tthrow new ServiceException(e);\n\t\t} finally {\n\t\t\tcleanup();\n\t\t}\n\t}\n}\n"},
+ {"elixir_with_error", lang.Elixir, "defmodule A do\n def process(params) do\n with {:ok, user} <- find_user(params.id),\n {:ok, order} <- create_order(user, params),\n :ok <- send_notification(user, order) do\n {:ok, order}\n else\n {:error, :not_found} -> {:error, \"user not found\"}\n {:error, reason} -> {:error, reason}\n end\n end\nend\n"},
+
+ // === Generic/Template Patterns ===
+ {"ts_generic_class", lang.TypeScript, "class Repository<T extends Entity> {\n constructor(private readonly db: Database) {}\n async findById(id: string): Promise<T | null> {\n return this.db.collection<T>().findOne({ id });\n }\n}\n"},
+ {"java_generic_method", lang.Java, "class A {\n\t<T extends Comparable<T>> List<T> sort(List<T> items) {\n\t\treturn items.stream().sorted().collect(Collectors.toList());\n\t}\n}\n"},
+ {"rust_generic_impl", lang.Rust, "impl<T: Clone + Send + 'static> From<Vec<T>> for Collection<T> {\n\tfn from(items: Vec<T>) -> Self {\n\t\tSelf { items, len: items.len() }\n\t}\n}\n"},
+ {"cpp_template_class", lang.CPP, "template<typename T, typename Alloc = std::allocator<T>>\nclass Vector {\npublic:\n\tvoid push_back(const T& value) { data_.push_back(value); }\n\tT& operator[](size_t index) { return data_[index]; }\nprivate:\n\tstd::vector<T, Alloc> data_;\n};\n"},
+ {"scala_type_bounds", lang.Scala, "object A {\n\tdef process[T <: Serializable : Ordering](items: List[T]): List[T] = {\n\t\titems.sorted.distinct\n\t}\n}\n"},
+
+ // === Destructuring Patterns ===
+ {"js_object_destructure", lang.JavaScript, "const { name, age, address: { city } } = getUserInfo();\nconst [first, ...rest] = getItems();\n"},
+ {"ts_function_destructure", lang.TypeScript, "function processUser({ id, name, roles = [] }: UserInput): Result {\n return { id, displayName: name, isAdmin: roles.includes('admin') };\n}\n"},
+ {"python_unpack", lang.Python, "first, *middle, last = get_items()\n(x, y), z = get_coords()\nname, age = user_info.values()\n"},
+ {"rust_pattern_match", lang.Rust, "fn handle(msg: Message) {\n\tmatch msg {\n\t\tMessage::Quit => println!(\"quit\"),\n\t\tMessage::Move { x, y } => move_to(x, y),\n\t\tMessage::Write(text) => println!(\"{}\", text),\n\t\tMessage::Color(r, g, b) => set_color(r, g, b),\n\t}\n}\n"},
+ {"kotlin_destructure", lang.Kotlin, "fun process(pair: Pair<String, Int>) {\n\tval (name, age) = pair\n\tval (first, second, third) = Triple(1, 2, 3)\n}\n"},
+
+ // === Metaprogramming/Dynamic Patterns ===
+ {"python_decorator_stack", lang.Python, "@app.route('/users', methods=['GET'])\n@login_required\n@cache(timeout=300)\ndef list_users():\n return User.query.all()\n"},
+ {"ruby_method_missing", lang.Ruby, "class DynamicProxy\n def method_missing(name, *args, &block)\n if target.respond_to?(name)\n target.send(name, *args, &block)\n else\n super\n end\n end\nend\n"},
+ {"python_dunder_methods", lang.Python, "class Vector:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n def __add__(self, other):\n return Vector(self.x + other.x, self.y + other.y)\n def __repr__(self):\n return f'Vector({self.x}, {self.y})'\n"},
+ {"ts_mapped_types", lang.TypeScript, "type Readonly<T> = { readonly [P in keyof T]: T[P] };\ntype Optional<T> = { [P in keyof T]?: T[P] };\ntype Pick<T, K extends keyof T> = { [P in K]: T[P] };\n"},
+
+ // === Pipe/Composition Patterns ===
+ {"elixir_pipe_complex", lang.Elixir, "defmodule A do\n def process(data) do\n data\n |> Enum.filter(&(&1.active))\n |> Enum.map(&transform/1)\n |> Enum.sort_by(& &1.priority)\n |> Enum.take(10)\n end\nend\n"},
+ {"haskell_composition", lang.Haskell, "processAll = map (show . succ . abs)\n"},
+ {"ocaml_pipe_complex", lang.OCaml, "let process items =\n items\n |> List.filter (fun x -> x > 0)\n |> List.map (fun x -> x * 2)\n |> List.sort compare\n"},
+
+ // === Interface/Trait Implementation Patterns ===
+ {"rust_trait_impl", lang.Rust, "trait Handler {\n\tfn handle(&self, req: &Request) -> Response;\n}\nstruct ApiHandler { db: Database }\nimpl Handler for ApiHandler {\n\tfn handle(&self, req: &Request) -> Response {\n\t\tself.db.query(req.path())\n\t}\n}\n"},
+ {"go_interface_impl", lang.Go, "package main\ntype Handler interface {\n\tHandle(ctx context.Context, req *Request) (*Response, error)\n}\ntype APIHandler struct{ db *DB }\nfunc (h *APIHandler) Handle(ctx context.Context, req *Request) (*Response, error) {\n\treturn h.db.Query(ctx, req.Path)\n}\n"},
+ {"csharp_interface_impl", lang.CSharp, "interface IHandler {\n\tTask<Response> HandleAsync(Request req);\n}\nclass ApiHandler : IHandler {\n\tprivate readonly IDb _db;\n\tpublic async Task<Response> HandleAsync(Request req) {\n\t\treturn await _db.QueryAsync(req.Path);\n\t}\n}\n"},
+ {"kotlin_interface_impl", lang.Kotlin, "interface Handler {\n\tsuspend fun handle(req: Request): Response\n}\nclass ApiHandler(private val db: Database) : Handler {\n\toverride suspend fun handle(req: Request): Response {\n\t\treturn db.query(req.path)\n\t}\n}\n"},
+
+ // === Closure/Lambda Patterns ===
+ {"go_closure_capture", lang.Go, "package main\nfunc makeCounter() func() int {\n\tcount := 0\n\treturn func() int {\n\t\tcount++\n\t\treturn count\n\t}\n}\n"},
+ {"rust_closure_move", lang.Rust, "fn spawn_task(data: Vec<u8>) {\n\ttokio::spawn(async move {\n\t\tprocess(&data).await;\n\t\tprintln!(\"done\");\n\t});\n}\n"},
+ {"java_lambda_stream", lang.Java, "class A {\n\tList<String> process(List<User> users) {\n\t\treturn users.stream()\n\t\t\t.filter(u -> u.isActive())\n\t\t\t.map(User::getName)\n\t\t\t.sorted()\n\t\t\t.collect(Collectors.toList());\n\t}\n}\n"},
+
+ // === Erlang OTP Patterns ===
+ {"erlang_gen_server", lang.Erlang, "-module(counter).\n-behaviour(gen_server).\n-export([start_link/0, init/1, handle_call/3]).\nstart_link() -> gen_server:start_link(?MODULE, 0, []).\ninit(Count) -> {ok, Count}.\nhandle_call(increment, _From, Count) -> {reply, Count + 1, Count + 1}.\n"},
+ {"erlang_supervisor", lang.Erlang, "-module(my_sup).\n-behaviour(supervisor).\n-export([start_link/0, init/1]).\nstart_link() -> supervisor:start_link({local, ?MODULE}, ?MODULE, []).\ninit([]) -> {ok, {{one_for_one, 5, 10}, [{worker, {my_worker, start_link, []}, permanent, 5000, worker, [my_worker]}]}}.\n"},
+
+ // === Haskell Type Classes ===
+ {"haskell_typeclass_def", lang.Haskell, "class Container f where\n empty :: f a\n insert :: a -> f a -> f a\n member :: Eq a => a -> f a -> Bool\n"},
+ {"haskell_instance_impl", lang.Haskell, "instance Show Color where\n show Red = \"red\"\n show Green = \"green\"\n show Blue = \"blue\"\n"},
+
+ // === Complex OOP Patterns ===
+ {"csharp_generic_constraint", lang.CSharp, "class Repository<T> where T : class, IEntity, new() {\n\tpublic T FindById(int id) {\n\t\treturn _context.Set<T>().Find(id);\n\t}\n}\n"},
+ {"scala_sealed_trait", lang.Scala, "sealed trait Shape\ncase class Circle(radius: Double) extends Shape\ncase class Rectangle(w: Double, h: Double) extends Shape\nobject Shape {\n\tdef area(s: Shape): Double = s match {\n\t\tcase Circle(r) => math.Pi * r * r\n\t\tcase Rectangle(w, h) => w * h\n\t}\n}\n"},
+ {"php_trait_usage", lang.PHP, "<?php\ntrait Timestampable {\n\tpublic function touch(): void {\n\t\t$this->updatedAt = new DateTime();\n\t}\n}\nclass Post implements JsonSerializable {\n\tuse Timestampable;\n\tpublic function jsonSerialize(): mixed {\n\t\treturn ['title' => $this->title];\n\t}\n}\n"},
}
func TestDumpAST(t *testing.T) {
diff --git a/internal/pipeline/decorates.go b/internal/pipeline/decorates.go
index 9fb000866..6e3d49f13 100644
--- a/internal/pipeline/decorates.go
+++ b/internal/pipeline/decorates.go
@@ -53,11 +53,11 @@ func (p *Pipeline) processNodeDecorators(n *store.Node) int {
continue
}
- targetQN := p.registry.Resolve(funcName, moduleQN, importMap)
- if targetQN == "" {
+ targetResult := p.registry.Resolve(funcName, moduleQN, importMap)
+ if targetResult.QualifiedName == "" {
continue
}
- targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetQN)
+ targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetResult.QualifiedName)
if targetNode == nil {
continue
}
diff --git a/internal/pipeline/enrichment.go b/internal/pipeline/enrichment.go
index c78ff488b..924313cb5 100644
--- a/internal/pipeline/enrichment.go
+++ b/internal/pipeline/enrichment.go
@@ -129,6 +129,19 @@ func extractParamTypeGroovy(node *tree_sitter.Node, source []byte, addType func(
return false
}
+func extractParamTypeOCaml(node *tree_sitter.Node, source []byte, addType func(string)) bool {
+ if node.Kind() != "parameter" {
+ return true
+ }
+ // OCaml: parameter → typed_pattern → type field
+ if tp := findChildByKind(node, "typed_pattern"); tp != nil {
+ if typeNode := tp.ChildByFieldName("type"); typeNode != nil {
+ addType(cleanTypeName(parser.NodeText(typeNode, source)))
+ }
+ }
+ return false
+}
+
// noParamTypes is used for languages without parameter type annotations.
func noParamTypes(_ *tree_sitter.Node, _ []byte, _ func(string)) bool {
return false
@@ -153,7 +166,7 @@ var paramTypeExtractors = map[lang.Language]paramTypeExtractorFn{
lang.Dart: extractParamTypeDart,
lang.Groovy: extractParamTypeGroovy,
lang.Swift: extractParamTypeField([]string{"parameter"}),
- lang.OCaml: extractParamTypeField([]string{"parameter"}),
+ lang.OCaml: extractParamTypeOCaml,
lang.Haskell: noParamTypes,
lang.Ruby: noParamTypes,
lang.Perl: noParamTypes,
@@ -362,6 +375,7 @@ func extractPythonBases(node *tree_sitter.Node, source []byte) []string {
return bases
}
+//nolint:gocognit,nestif // WHY: inherent complexity from Java AST hierarchy traversal
func extractJavaBases(node *tree_sitter.Node, source []byte) []string {
var bases []string
if superNode := node.ChildByFieldName("superclass"); superNode != nil {
@@ -373,13 +387,27 @@ func extractJavaBases(node *tree_sitter.Node, source []byte) []string {
}
}
if implNode := node.ChildByFieldName("interfaces"); implNode != nil {
+ // interfaces field contains a type_list with individual type_identifier children
+ // Walk into type_list to get each interface name separately
for i := uint(0); i < implNode.NamedChildCount(); i++ {
child := implNode.NamedChild(i)
if child == nil {
continue
}
- if name := cleanTypeName(parser.NodeText(child, source)); name != "" {
- bases = append(bases, name)
+ if child.Kind() == "type_list" {
+ for j := uint(0); j < child.NamedChildCount(); j++ {
+ typeChild := child.NamedChild(j)
+ if typeChild == nil {
+ continue
+ }
+ if name := cleanTypeName(parser.NodeText(typeChild, source)); name != "" {
+ bases = append(bases, name)
+ }
+ }
+ } else {
+ if name := cleanTypeName(parser.NodeText(child, source)); name != "" {
+ bases = append(bases, name)
+ }
}
}
}
@@ -836,6 +864,17 @@ func extractRustAttributes(node *tree_sitter.Node, source []byte) []string {
func extractSwiftAttributes(node *tree_sitter.Node, source []byte) []string {
var decorators []string
+ // Swift attributes live inside a "modifiers" child node
+ mods := findChildByKind(node, "modifiers")
+ if mods != nil {
+ for i := uint(0); i < mods.ChildCount(); i++ {
+ child := mods.Child(i)
+ if child != nil && child.Kind() == "attribute" {
+ decorators = append(decorators, parser.NodeText(child, source))
+ }
+ }
+ }
+ // Also check direct children (some node types may have attributes directly)
for i := uint(0); i < node.ChildCount(); i++ {
child := node.Child(i)
if child != nil && child.Kind() == "attribute" {
@@ -920,7 +959,13 @@ func isBuiltinType(name string) bool {
"number", "bigint", "symbol", "undefined", "null",
"char", "short", "long", "i8", "i16", "i32", "i64",
"u8", "u16", "u32", "u64", "f32", "f64", "usize", "isize",
- "self", "Self", "cls", "type":
+ "self", "Self", "cls", "type",
+ // Uppercase variants (Kotlin, Swift, Scala, Dart)
+ "Int", "Int8", "Int16", "Int32", "Int64",
+ "UInt", "UInt8", "UInt16", "UInt32", "UInt64",
+ "Float", "Double", "String", "Bool", "Boolean",
+ "Byte", "Short", "Long", "Char", "Unit", "Void",
+ "Any", "Nothing", "Dynamic":
return true
}
return false
diff --git a/internal/pipeline/extraction_test.go b/internal/pipeline/extraction_test.go
new file mode 100644
index 000000000..47c65f3fc
--- /dev/null
+++ b/internal/pipeline/extraction_test.go
@@ -0,0 +1,1681 @@
+package pipeline
+
+import (
+ "reflect"
+ "testing"
+
+ tree_sitter "github.com/tree-sitter/go-tree-sitter"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/lang"
+ "github.com/DeusData/codebase-memory-mcp/internal/parser"
+)
+
+// ============================================================================
+// TestCalleeExtraction — assertion-based callee extraction test suite
+//
+// Documents the exact output of extractCalleeName() for every call pattern
+// per language. All assertions reflect optimal (correct) behavior.
+// ============================================================================
+
+var calleeExtractionCases = []struct {
+ name string
+ lang lang.Language
+ code string
+ wantCallees []string
+}{
+ // === Go (16 cases) ===
+ {"go_simple_call", lang.Go, `package main; func f() { fmt.Println("hello") }`,
+ []string{"fmt.Println"}},
+ {"go_method_call", lang.Go, `package main; func f(s *Server) { s.handler.ServeHTTP(w, r) }`,
+ []string{"s.handler.ServeHTTP"}},
+ {"go_goroutine_call", lang.Go, `package main; func f() { go process(ctx) }`,
+ []string{"process"}},
+ {"go_defer_call", lang.Go, `package main; func f(conn net.Conn) { defer conn.Close() }`,
+ []string{"conn.Close"}},
+ {"go_multi_call", lang.Go, `package main; func f() { a(); b(); c() }`,
+ []string{"a", "b", "c"}},
+ {"go_nested_call", lang.Go, `package main; func f() { fmt.Println(strconv.Itoa(42)) }`,
+ []string{"fmt.Println", "strconv.Itoa"}},
+ {"go_type_assert_call", lang.Go, `package main; func f(r io.Reader) { r.(io.Closer).Close() }`,
+ []string{"r.(io.Closer).Close"}},
+ {"go_iife", lang.Go, "package main; func f() { func() { fmt.Println(\"hi\") }() }",
+ []string{"fmt.Println"}},
+ {"go_append_call", lang.Go, `package main; func f(s []int) []int { return append(s, 1, 2) }`,
+ []string{"append"}},
+ {"go_make_call", lang.Go, `package main; func f() { ch := make(chan int, 10); _ = ch }`,
+ []string{"make"}},
+ {"go_error_wrap", lang.Go, "package main\nimport \"fmt\"\nfunc f(err error) error { return fmt.Errorf(\"wrap: %w\", err) }\n",
+ []string{"fmt.Errorf"}},
+ {"go_multi_return_call", lang.Go, `package main; func f(s string) { val, _ := strconv.Atoi(s); _ = val }`,
+ []string{"strconv.Atoi"}},
+ {"go_closure_return", lang.Go, `package main; func f() func() { return func() { process(42) } }`,
+ []string{"process"}},
+ {"go_interface_call", lang.Go, `package main; func f(w io.Writer) { w.Write(data) }`,
+ []string{"w.Write"}},
+ {"go_type_switch_call", lang.Go, "package main\nfunc f(v interface{}) { switch v.(type) { case int: handle(v) } }\n",
+ []string{"handle"}},
+ {"go_select_call", lang.Go, "package main\nfunc f(ch chan int) { select { case v := <-ch: process(v) } }\n",
+ []string{"process"}},
+
+ // === Python (16 cases) ===
+ {"py_simple_call", lang.Python, "print('hello')\n",
+ []string{"print"}},
+ {"py_method_call", lang.Python, "self.db.execute(query)\n",
+ []string{"self.db.execute"}},
+ {"py_class_instantiation", lang.Python, "user = User('Alice')\n",
+ []string{"User"}},
+ {"py_chain_call", lang.Python, "queryset.filter(active=True).order_by('name').first()\n",
+ []string{"queryset.filter(active=True).order_by('name').first", "queryset.filter(active=True).order_by", "queryset.filter"}},
+ {"py_decorator_factory", lang.Python, "@app.route('/api')\ndef handler(): pass\n",
+ []string{"app.route"}},
+ {"py_super_call", lang.Python, "class A(B):\n def __init__(self):\n super().__init__()\n",
+ []string{"super().__init__", "super"}},
+ {"py_comprehension_call", lang.Python, "result = [f(x) for x in items]\n",
+ []string{"f"}},
+ {"py_lambda_call", lang.Python, "fn = lambda x: process(x)\n",
+ []string{"process"}},
+ {"py_with_statement", lang.Python, "with open('file.txt') as f:\n data = f.read()\n",
+ []string{"open", "f.read"}},
+ {"py_nested_calls", lang.Python, "json.dumps(sorted(data.items()))\n",
+ []string{"json.dumps", "sorted", "data.items"}},
+ {"py_dict_comprehension", lang.Python, "result = {k: transform(v) for k, v in pairs.items()}\n",
+ []string{"transform", "pairs.items"}},
+ {"py_starred_call", lang.Python, "process(*args, **kwargs)\n",
+ []string{"process"}},
+ {"py_double_with", lang.Python, "with open('a') as f1, open('b') as f2:\n pass\n",
+ []string{"open", "open"}},
+ {"py_global_sorted", lang.Python, "result = sorted(data, key=lambda x: getattr(x, 'score'))\n",
+ []string{"sorted", "getattr"}},
+ {"py_ternary_calls", lang.Python, "x = f(a) if check(a) else g(b)\n",
+ []string{"f", "check", "g"}},
+ {"py_assert_call", lang.Python, "assert validate(data), format_error(data)\n",
+ []string{"validate", "format_error"}},
+
+ // === JavaScript (15 cases) ===
+ {"js_simple_call", lang.JavaScript, "doWork(args);\n",
+ []string{"doWork"}},
+ {"js_member_call", lang.JavaScript, "obj.method(args);\n",
+ []string{"obj.method"}},
+ {"js_callback_call", lang.JavaScript, "app.get('/path', handler);\n",
+ []string{"app.get"}},
+ {"js_this_call", lang.JavaScript, "this.handleRequest(req);\n",
+ []string{"this.handleRequest"}},
+ {"js_chain_call", lang.JavaScript, "arr.filter(fn).map(fn2).join(',');\n",
+ []string{"arr.filter(fn).map(fn2).join", "arr.filter(fn).map", "arr.filter"}},
+ {"js_new_not_call", lang.JavaScript, "const user = new User('Alice');\n",
+ nil},
+ {"js_iife", lang.JavaScript, "(function() { doWork(); })();\n",
+ []string{"doWork"}},
+ {"js_optional_chain", lang.JavaScript, "user?.getName();\n",
+ []string{"user?.getName"}},
+ {"js_computed_call", lang.JavaScript, "handlers[event](data);\n",
+ nil},
+ {"js_spread_call", lang.JavaScript, "Math.max(...numbers);\n",
+ []string{"Math.max"}},
+ {"js_destructure_call", lang.JavaScript, "const { data } = fetchData();\n",
+ []string{"fetchData"}},
+ {"js_arrow_chain", lang.JavaScript, "const process = (x) => transform(filter(x));\n",
+ []string{"transform", "filter"}},
+ {"js_template_literal", lang.JavaScript, "const msg = `Hello ${getName()}`;\n",
+ []string{"getName"}},
+ {"js_typeof_call", lang.JavaScript, "if (typeof getValue() === 'string') {}\n",
+ []string{"getValue"}},
+ {"js_comma_calls", lang.JavaScript, "a(), b(), c();\n",
+ []string{"a", "b", "c"}},
+
+ // === TypeScript (12 cases) ===
+ {"ts_generic_call", lang.TypeScript, "parseResponse<User>(data);\n",
+ []string{"parseResponse"}},
+ {"ts_await_call", lang.TypeScript, "const result = await fetch(url);\n",
+ []string{"fetch"}},
+ {"ts_method_call", lang.TypeScript, "const user: User = service.getUser(id);\n",
+ []string{"service.getUser"}},
+ {"ts_non_null_call", lang.TypeScript, "value!.toString();\n",
+ []string{"value!.toString"}},
+ {"ts_satisfies_call", lang.TypeScript, "const config = getConfig() satisfies Config;\n",
+ []string{"getConfig"}},
+ {"ts_ternary_calls", lang.TypeScript, "const x = isValid(data) ? process(data) : handleError(data);\n",
+ []string{"isValid", "process", "handleError"}},
+ {"ts_decorator_call", lang.TypeScript, "@Injectable()\nclass Service {}\n",
+ []string{"Injectable"}},
+ {"ts_index_call", lang.TypeScript, "const fn = handlers['click']; fn(event);\n",
+ []string{"fn"}},
+ {"ts_type_guard", lang.TypeScript, "function isUser(x: any): x is User { return check(x); }\n",
+ []string{"check"}},
+ {"ts_as_cast_call", lang.TypeScript, "const n = (getValue() as number).toFixed(2);\n",
+ []string{"(getValue() as number).toFixed", "getValue"}},
+ {"ts_namespace_call", lang.TypeScript, "namespace NS { export function greet() { log('hi'); } }\n",
+ []string{"log"}},
+ {"ts_nested_generic", lang.TypeScript, "const items = Array.from<string>(getIterable());\n",
+ []string{"Array.from", "getIterable"}},
+
+ // === TSX (9 cases) ===
+ {"tsx_hook_call", lang.TSX, "const [state, setState] = useState(0);\n",
+ []string{"useState"}},
+ {"tsx_create_element", lang.TSX, "React.createElement('div', null, 'hello');\n",
+ []string{"React.createElement"}},
+ {"tsx_event_ref_not_call", lang.TSX, "const el = <Button onClick={handleClick} />;\n",
+ nil},
+ {"tsx_inline_callback", lang.TSX, "const el = <Button onClick={() => doWork()} />;\n",
+ []string{"doWork"}},
+ {"tsx_use_effect", lang.TSX, "useEffect(() => { fetchData(); }, [id]);\n",
+ []string{"useEffect", "fetchData"}},
+ {"tsx_custom_hook", lang.TSX, "const data = useQuery('users', fetchUsers);\n",
+ []string{"useQuery"}},
+ {"tsx_memo_call", lang.TSX, "const Comp = React.memo(InnerComp);\n",
+ []string{"React.memo"}},
+ {"tsx_use_callback", lang.TSX, "const fn = useCallback(() => process(data), [data]);\n",
+ []string{"useCallback", "process"}},
+ {"tsx_conditional_render", lang.TSX, "const el = isLoading ? null : render(data);\n",
+ []string{"render"}},
+
+ // === Java (14 cases) ===
+ {"java_instance_call", lang.Java, "class A { void f() { repository.findById(id); } }",
+ []string{"findById"}},
+ {"java_static_call", lang.Java, "class A { void f() { Collections.unmodifiableList(list); } }",
+ []string{"unmodifiableList"}},
+ {"java_chain_call", lang.Java, "class A { void f() { builder.setName(n).setAge(a).build(); } }",
+ []string{"build", "setAge", "setName"}},
+ {"java_new_not_call", lang.Java, "class A { void f() { User u = new User(); } }",
+ nil},
+ {"java_super_call", lang.Java, "class A extends B { A() { super(); } }",
+ nil},
+ {"java_lambda_call", lang.Java, "class A { void f() { items.forEach(System.out::println); } }",
+ []string{"forEach"}},
+ {"java_nested_calls", lang.Java, "class A { void f() { log.info(String.valueOf(count)); } }",
+ []string{"info", "valueOf"}},
+ {"java_generic_call", lang.Java, `class A { void f() { Optional.<String>of("hello"); } }`,
+ []string{"of"}},
+ {"java_annotation_not_call", lang.Java, "@RequestMapping(\"/api\")\nclass A {}",
+ nil},
+ {"java_varargs_call", lang.Java, "class A { void f() { Arrays.asList(1, 2, 3); } }",
+ []string{"asList"}},
+ {"java_stream_chain", lang.Java, "class A { void f() { list.stream().filter(x -> x.isActive()).count(); } }",
+ []string{"count", "filter", "stream", "isActive"}},
+ {"java_throw_call", lang.Java, "class A { void f() { throw new RuntimeException(getMessage()); } }",
+ []string{"getMessage"}},
+ {"java_ternary_call", lang.Java, "class A { void f(boolean b) { b ? doA() : doB(); } }",
+ []string{"doA", "doB"}},
+ {"java_enhanced_for_call", lang.Java, "class A { void f() { for (var item : getItems()) { process(item); } } }",
+ []string{"getItems", "process"}},
+
+ // === C# (16 cases) ===
+ {"csharp_member_call", lang.CSharp, "class A { void F() { _context.SaveChangesAsync(token); } }",
+ []string{"_context.SaveChangesAsync"}},
+ {"csharp_static_call", lang.CSharp, `class A { void F() { Console.WriteLine("hello"); } }`,
+ []string{"Console.WriteLine"}},
+ {"csharp_simple_call", lang.CSharp, "class A { void F() { DoWork(); } }",
+ []string{"DoWork"}},
+ {"csharp_await_call", lang.CSharp, "class A { async Task F() { await SaveAsync(); } }",
+ []string{"SaveAsync"}},
+ {"csharp_await_member_call", lang.CSharp, "class A { async Task F() { await _ctx.SaveChangesAsync(t); } }",
+ []string{"_ctx.SaveChangesAsync"}},
+ {"csharp_linq_chain", lang.CSharp, "class A { void F() { items.Where(x => x.Active).Select(x => x.Name); } }",
+ []string{"items.Where(x => x.Active).Select", "items.Where"}},
+ {"csharp_null_conditional", lang.CSharp, "class A { void F() { obj?.Method(); } }",
+ nil},
+ {"csharp_generic_call", lang.CSharp, "class A { void F() { _mediator.Send<Result>(cmd); } }",
+ []string{"_mediator.Send<Result>"}},
+ {"csharp_expression_body", lang.CSharp, "class A { int Add(int a, int b) => Math.Max(a, b); }",
+ []string{"Math.Max"}},
+ {"csharp_interpolation_call", lang.CSharp, `class A { void F() { var s = $"{GetName()}"; } }`,
+ []string{"GetName"}},
+ {"csharp_delegate_call", lang.CSharp, "class A { void F(Action cb) { cb(); } }",
+ []string{"cb"}},
+ {"csharp_pattern_call", lang.CSharp, `class A { void F() { if (obj is string s) Console.WriteLine(s); } }`,
+ []string{"Console.WriteLine"}},
+ {"csharp_params_call", lang.CSharp, "class A { void F() { Format(\"{0}\", GetValue()); } }",
+ []string{"Format", "GetValue"}},
+ {"csharp_throw_call", lang.CSharp, "class A { void F() { throw new Exception(GetMessage()); } }",
+ []string{"GetMessage"}},
+ {"csharp_ternary_call", lang.CSharp, "class A { void F(bool b) { var r = b ? GetA() : GetB(); } }",
+ []string{"GetA", "GetB"}},
+ {"csharp_for_call", lang.CSharp, "class A { void F() { for (int i = 0; i < GetCount(); i++) { Process(i); } } }",
+ []string{"GetCount", "Process"}},
+
+ // === Rust (14 cases) ===
+ {"rust_self_call", lang.Rust, "impl S { fn f(&self) { self.handle(&req); } }",
+ []string{"self.handle"}},
+ {"rust_static_call", lang.Rust, "fn f() { Vec::new(); }",
+ []string{"Vec::new"}},
+ {"rust_macro_call", lang.Rust, `fn f() { println!("hello {}", name); }`,
+ []string{"println!"}},
+ {"rust_chain_call", lang.Rust, "fn f() { items.iter().filter(|x| x.active).collect::<Vec<_>>(); }",
+ []string{"items.iter().filter", "items.iter"}},
+ {"rust_turbofish", lang.Rust, `fn f() { parse::<i32>("42"); }`,
+ nil},
+ {"rust_closure_call", lang.Rust, "fn f() { let add = |a, b| a + b; add(1, 2); }",
+ []string{"add"}},
+ {"rust_trait_call", lang.Rust, "fn f(d: &dyn Display) { d.fmt(&mut buf); }",
+ []string{"d.fmt"}},
+ {"rust_nested_calls", lang.Rust, "fn f() { Ok(serde_json::from_str(&data)); }",
+ []string{"Ok", "serde_json::from_str"}},
+ {"rust_await_call", lang.Rust, "async fn f() { let resp = client.get(url).send().await; }",
+ []string{"client.get(url).send", "client.get"}},
+ {"rust_question_call", lang.Rust, "fn f() -> Result<()> { let data = read_file(path)?; Ok(()) }",
+ []string{"read_file", "Ok"}},
+ {"rust_vec_macro", lang.Rust, "fn f() { let v = vec![1, 2, 3]; }",
+ []string{"vec!"}},
+ {"rust_format_macro", lang.Rust, `fn f() { let s = format!("{} {}", a, b); }`,
+ []string{"format!"}},
+ {"rust_match_arm_call", lang.Rust, "fn f(r: Result<i32, &str>) { match r { Ok(v) => process(v), Err(e) => handle(e) }; }",
+ []string{"process", "handle"}},
+ {"rust_scoped_macro", lang.Rust, "fn f() { log::info!(\"starting\"); }",
+ []string{"log::info!"}},
+
+ // === C++ (13 cases) ===
+ {"cpp_simple_call", lang.CPP, `void f() { printf("hello"); }`,
+ []string{"printf"}},
+ {"cpp_method_call", lang.CPP, "void f(std::string s) { s.substr(0, 5); }",
+ []string{"s.substr"}},
+ {"cpp_namespace_call", lang.CPP, "void f() { std::sort(v.begin(), v.end()); }",
+ []string{"std::sort", "v.begin", "v.end"}},
+ {"cpp_new_call", lang.CPP, "void f() { auto p = new Point(1, 2); }",
+ nil},
+ {"cpp_delete_call", lang.CPP, "void f(int* p) { delete p; }",
+ nil},
+ {"cpp_binary_op", lang.CPP, "void f(int a, int b) { int c = a + b; }",
+ nil},
+ {"cpp_subscript", lang.CPP, "void f(int* m) { int v = m[42]; }",
+ nil},
+ {"cpp_template_call", lang.CPP, "void f() { auto p = std::make_shared<Config>(args); }",
+ []string{"std::make_shared<Config>"}},
+ {"cpp_unary_op", lang.CPP, "void f(int& x) { ++x; }",
+ nil},
+ {"cpp_lambda_call", lang.CPP, "void f() { auto fn = [](int x){ return x*2; }; fn(5); }",
+ []string{"fn"}},
+ {"cpp_unique_ptr", lang.CPP, "void f() { auto p = std::make_unique<Foo>(1, 2); }",
+ []string{"std::make_unique<Foo>"}},
+ {"cpp_stl_algorithm", lang.CPP, "void f() { std::transform(v.begin(), v.end(), out.begin(), func); }",
+ []string{"std::transform", "v.begin", "v.end", "out.begin"}},
+ {"cpp_nested_call", lang.CPP, "void f() { log(std::to_string(getValue())); }",
+ []string{"log", "std::to_string", "getValue"}},
+
+ // === C (8 cases) ===
+ {"c_simple_call", lang.C, `void f() { printf("hello %s", name); }`,
+ []string{"printf"}},
+ {"c_func_ptr_call", lang.C, "void f(void (*callback)(int)) { callback(42); }",
+ []string{"callback"}},
+ {"c_struct_member_call", lang.C, "void f(struct ctx *c) { c->handler(c, req); }",
+ []string{"c->handler"}},
+ {"c_nested_calls", lang.C, "void f() { free(strdup(s)); }",
+ []string{"free", "strdup"}},
+ {"c_macro_call", lang.C, "void f() { assert(x > 0); }",
+ []string{"assert"}},
+ {"c_variadic_call", lang.C, "void f() { va_start(ap, fmt); }",
+ []string{"va_start"}},
+ {"c_stdlib_call", lang.C, "void f() { int n = atoi(getenv(\"PORT\")); }",
+ []string{"atoi", "getenv"}},
+ {"c_multi_call", lang.C, "void f() { open(); read(); close(); }",
+ []string{"open", "read", "close"}},
+
+ // === PHP (13 cases) ===
+ {"php_bare_call", lang.PHP, "<?php\narray_map($fn, $items);\n",
+ []string{"array_map"}},
+ {"php_member_call", lang.PHP, "<?php\n$this->repository->find($id);\n",
+ []string{"find"}},
+ {"php_static_call", lang.PHP, "<?php\nResponse::json($data);\n",
+ []string{"json"}},
+ {"php_nullsafe_call", lang.PHP, "<?php\n$user?->getName();\n",
+ []string{"getName"}},
+ {"php_new_not_call", lang.PHP, "<?php\n$u = new User(['name' => 'John']);\n",
+ nil},
+ {"php_chain_call", lang.PHP, "<?php\n$query->where('active', true)->orderBy('name')->get();\n",
+ []string{"get", "orderBy", "where"}},
+ {"php_arrow_call", lang.PHP, "<?php\n$filtered = array_filter($items, fn($x) => $x > 0);\n",
+ []string{"array_filter"}},
+ {"php_callable_call", lang.PHP, "<?php\ncall_user_func([$obj, 'method'], $arg);\n",
+ []string{"call_user_func"}},
+ {"php_nested_calls", lang.PHP, "<?php\njson_encode(array_values($data));\n",
+ []string{"json_encode", "array_values"}},
+ {"php_string_call", lang.PHP, "<?php\n$fn = 'strlen'; $fn('hello');\n",
+ []string{"$fn"}},
+ {"php_closure_call", lang.PHP, "<?php\n$fn = function($x) { return process($x); }; $fn(1);\n",
+ []string{"process", "$fn"}},
+ {"php_str_replace", lang.PHP, "<?php\nstr_replace('a', 'b', $str);\n",
+ []string{"str_replace"}},
+ {"php_ternary_call", lang.PHP, "<?php\n$r = isValid($x) ? getA($x) : getB($x);\n",
+ []string{"isValid", "getA", "getB"}},
+
+ // === Ruby (13 cases) ===
+ {"ruby_receiver_call", lang.Ruby, "class A\n def f\n name.to_s\n end\nend\n",
+ []string{"name.to_s"}},
+ {"ruby_bare_call", lang.Ruby, "class A\n def f\n puts 'hello'\n end\nend\n",
+ []string{"puts"}},
+ {"ruby_chain_call", lang.Ruby, "class A\n def f\n users.where(active: true).order(:name).limit(10)\n end\nend\n",
+ []string{"users.where(active: true).order(:name).limit", "users.where(active: true).order", "users.where"}},
+ {"ruby_block_call", lang.Ruby, "class A\n def f\n @items.each { |i| puts i }\n end\nend\n",
+ []string{"@items.each", "puts"}},
+ {"ruby_class_method", lang.Ruby, "User.find(42)\n",
+ []string{"User.find"}},
+ {"ruby_command_call", lang.Ruby, "class A\n def f\n obj.send :method_name, arg\n end\nend\n",
+ []string{"obj.send"}},
+ {"ruby_super_call", lang.Ruby, "class A < B\n def save\n super\n end\nend\n",
+ nil},
+ {"ruby_yield_call", lang.Ruby, "def each\n yield item\nend\n",
+ nil},
+ {"ruby_self_call", lang.Ruby, "class A\n def f\n self.validate\n end\nend\n",
+ []string{"self.validate"}},
+ {"ruby_dsl_call", lang.Ruby, "get '/users' do\n 'hello'\nend\n",
+ []string{"get"}},
+ {"ruby_tap_call", lang.Ruby, "class A\n def f\n @items.tap { |d| log(d) }\n end\nend\n",
+ []string{"@items.tap", "log"}},
+ {"ruby_map_call", lang.Ruby, "class A\n def f\n items.map { |i| transform(i) }\n end\nend\n",
+ []string{"items.map", "transform"}},
+ {"ruby_require_call", lang.Ruby, "require 'json'\n",
+ []string{"require"}},
+
+ // === Kotlin (11 cases) ===
+ {"kotlin_simple_call", lang.Kotlin, "fun f() { println(\"hello\") }\n",
+ []string{"println"}},
+ {"kotlin_extension_call", lang.Kotlin, "fun f() { items.filter { it.active } }\n",
+ []string{"items.filter", "items", "it"}},
+ {"kotlin_nav_expr", lang.Kotlin, "fun f(user: User) { user.name.length }\n",
+ []string{"user.name", "user"}},
+ {"kotlin_companion_call", lang.Kotlin, "fun f() { User.create(data) }\n",
+ []string{"User.create", "User"}},
+ {"kotlin_lambda_receiver", lang.Kotlin, "fun f() { buildString { append(\"hello\") } }\n",
+ []string{"buildString", "append"}},
+ {"kotlin_infix_call", lang.Kotlin, "fun f() { 1 shl 2 }\n",
+ nil},
+ {"kotlin_scope_call", lang.Kotlin, "fun f(user: User) { user.let { it.name } }\n",
+ []string{"user.let", "user", "it"}},
+ {"kotlin_constructor_call", lang.Kotlin, "fun f() { val u = User(\"Alice\") }\n",
+ []string{"User"}},
+ {"kotlin_apply_call", lang.Kotlin, "fun f() { User().apply { name = \"Bob\" } }\n",
+ []string{"User().apply", "User"}},
+ {"kotlin_multi_call", lang.Kotlin, "fun f() { a(); b(); c() }\n",
+ []string{"a", "b", "c"}},
+ {"kotlin_map_call", lang.Kotlin, "fun f() { items.map { transform(it) } }\n",
+ []string{"items.map", "items", "transform"}},
+
+ // === Scala (11 cases) ===
+ {"scala_dot_call", lang.Scala, "object A { def f() = service.process(data) }\n",
+ []string{"service.process"}},
+ {"scala_infix_call", lang.Scala, "object A { def f() = items map (_.name) }\n",
+ []string{"map", "_.name"}},
+ {"scala_generic_call", lang.Scala, "object A { def f() = Option[String](\"hello\") }\n",
+ []string{"Option"}},
+ {"scala_field_call", lang.Scala, "object A { def f() = list.head }\n",
+ []string{"list.head"}},
+ {"scala_match_call", lang.Scala, "object A { def f(x: Any) = x match { case s: String => s.toUpperCase } }\n",
+ []string{"s.toUpperCase"}},
+ {"scala_for_call", lang.Scala, "object A { def f() = for { x <- getItems() } yield process(x) }\n",
+ []string{"getItems", "process"}},
+ {"scala_apply_call", lang.Scala, "object A { def f() = Map(\"a\" -> 1, \"b\" -> 2) }\n",
+ []string{"Map", "->", "->"}},
+ {"scala_chain_call", lang.Scala, "object A { def f() = items.filter(_.active).map(_.name).mkString }\n",
+ []string{"items.filter(_.active).map(_.name).mkString", "items.filter(_.active).map", "items.filter", "_.active", "_.name"}},
+ {"scala_flatmap_call", lang.Scala, "object A { def f() = list.flatMap(_.items) }\n",
+ []string{"list.flatMap", "_.items"}},
+ {"scala_companion_call", lang.Scala, "object A { def f() = User(\"Alice\") }\n",
+ []string{"User"}},
+ {"scala_multi_call", lang.Scala, "object A { def f() = { a(); b(); c() } }\n",
+ []string{"a", "b", "c"}},
+
+ // === Haskell (11 cases) ===
+ {"haskell_apply", lang.Haskell, "f = map show [1,2,3]\n",
+ []string{"map", "map"}},
+ {"haskell_infix_op", lang.Haskell, "f = xs <> ys\n",
+ []string{"<>"}},
+ {"haskell_dollar", lang.Haskell, "f = print $ show 42\n",
+ []string{"$", "show"}},
+ {"haskell_do_bind", lang.Haskell, "f = do\n result <- readFile path\n return result\n",
+ []string{"readFile", "return"}},
+ {"haskell_where_call", lang.Haskell, "f x = g (h x)\n where g = show\n h = succ\n",
+ []string{"g", "h"}},
+ {"haskell_typeclass_call", lang.Haskell, "f x = show x ++ \" is \" ++ show (succ x)\n",
+ []string{"++", "show", "++", "show", "succ"}},
+ {"haskell_backtick", lang.Haskell, "f = xs `mappend` ys\n",
+ []string{"`mappend`"}},
+ {"haskell_nested_apply", lang.Haskell, "f = map (filter even) lists\n",
+ []string{"map", "map", "filter"}},
+ {"haskell_guard_call", lang.Haskell, "f x\n | check x = process x\n | otherwise = default_val x\n",
+ []string{"check", "process", "default_val"}},
+ {"haskell_composition", lang.Haskell, "f = (show . succ) 42\n",
+ []string{"(show . succ)", "."}},
+ {"haskell_bind_op", lang.Haskell, "f = readFile path >>= processContent\n",
+ []string{">>=", "readFile"}},
+
+ // === OCaml (11 cases) ===
+ {"ocaml_apply", lang.OCaml, "let f = List.map show items\n",
+ []string{"List.map"}},
+ {"ocaml_pipe", lang.OCaml, "let f x = x |> List.filter pred |> List.map show\n",
+ []string{"List.map", "List.filter", "List.filter", "List.map"}},
+ {"ocaml_reverse_pipe", lang.OCaml, "let f = print_string @@ string_of_int 42\n",
+ []string{"print_string", "string_of_int"}},
+ {"ocaml_module_call", lang.OCaml, "let f () = Printf.printf \"%s\" name\n",
+ []string{"Printf.printf"}},
+ {"ocaml_let_call", lang.OCaml, "let f x = let y = g x in h y\n",
+ []string{"g", "h"}},
+ {"ocaml_match_call", lang.OCaml, "let f x = match classify x with\n | A -> handle_a x\n | B -> handle_b x\n",
+ []string{"classify", "handle_a", "handle_b"}},
+ {"ocaml_nested_apply", lang.OCaml, "let f = List.map (fun x -> succ (abs x)) items\n",
+ []string{"List.map", "succ", "abs"}},
+ {"ocaml_functor", lang.OCaml, "module M = Set.Make(String)\n",
+ nil},
+ {"ocaml_option_map", lang.OCaml, "let f x = Option.map succ x\n",
+ []string{"Option.map"}},
+ {"ocaml_if_call", lang.OCaml, "let f x = if check x then process x else handle x\n",
+ []string{"check", "process", "handle"}},
+ {"ocaml_multi_pipe", lang.OCaml, "let f x = x |> validate |> transform |> save\n",
+ []string{"save", "transform", "validate"}},
+
+ // === Elixir (11 cases) ===
+ {"elixir_pipe_chain", lang.Elixir, "defmodule A do\n def f(data) do\n data |> validate() |> transform() |> save()\n end\nend\n",
+ []string{"save", "transform", "validate"}},
+ {"elixir_direct_call", lang.Elixir, "defmodule A do\n def f do\n IO.puts(\"hello\")\n end\nend\n",
+ []string{"IO.puts"}},
+ {"elixir_genserver_call", lang.Elixir, "defmodule A do\n def f(pid) do\n GenServer.call(pid, :request)\n end\nend\n",
+ []string{"GenServer.call"}},
+ {"elixir_dot_call", lang.Elixir, "defmodule A do\n def f(mod) do\n mod.function(arg)\n end\nend\n",
+ []string{"mod.function"}},
+ {"elixir_kernel_call", lang.Elixir, "defmodule A do\n def f do\n length([1,2,3])\n end\nend\n",
+ []string{"length"}},
+ {"elixir_non_pipe_binop", lang.Elixir, "defmodule A do\n def f do\n x = 1 + 2\n end\nend\n",
+ nil},
+ {"elixir_capture", lang.Elixir, "defmodule A do\n def f do\n Enum.map([1,2], &to_string/1)\n end\nend\n",
+ []string{"Enum.map"}},
+ {"elixir_with_call", lang.Elixir, "defmodule A do\n def f do\n with {:ok, a} <- fetch_a(), {:ok, b} <- fetch_b(a), do: {a, b}\n end\nend\n",
+ []string{"fetch_a", "fetch_b"}},
+ {"elixir_enum_call", lang.Elixir, "defmodule A do\n def f(list) do\n Enum.filter(list, fn x -> x > 0 end)\n end\nend\n",
+ []string{"Enum.filter"}},
+ {"elixir_spawn_call", lang.Elixir, "defmodule A do\n def f do\n spawn(fn -> process(data) end)\n end\nend\n",
+ []string{"spawn", "process"}},
+ {"elixir_multi_call", lang.Elixir, "defmodule A do\n def f do\n a = compute(1)\n b = transform(a)\n save(b)\n end\nend\n",
+ []string{"compute", "transform", "save"}},
+
+ // === Erlang (9 cases) ===
+ {"erlang_remote_call", lang.Erlang, "-module(m).\nf() -> io:format(\"hello\").\n",
+ []string{"format"}},
+ {"erlang_local_call", lang.Erlang, "-module(m).\nf() -> greet(\"World\").\ngreet(N) -> N.\n",
+ []string{"greet"}},
+ {"erlang_gen_server_call", lang.Erlang, "-module(m).\nf(Pid) -> gen_server:call(Pid, req).\n",
+ []string{"call"}},
+ {"erlang_nested_remote", lang.Erlang, "-module(m).\nf(L) -> lists:map(fun erlang:abs/1, L).\n",
+ []string{"map"}},
+ {"erlang_spawn_call", lang.Erlang, "-module(m).\nf() -> spawn(fun() -> ok end).\n",
+ []string{"spawn"}},
+ {"erlang_multi_call", lang.Erlang, "-module(m).\nf() -> a(), b(), c().\na() -> ok.\nb() -> ok.\nc() -> ok.\n",
+ []string{"a", "b", "c"}},
+ {"erlang_lists_call", lang.Erlang, "-module(m).\nf(L) -> lists:filter(fun(X) -> X > 0 end, L).\n",
+ []string{"filter"}},
+ {"erlang_string_call", lang.Erlang, "-module(m).\nf(S) -> string:tokens(S, \",\").\n",
+ []string{"tokens"}},
+ {"erlang_nested_local", lang.Erlang, "-module(m).\nf(X) -> g(h(X)).\ng(X) -> X.\nh(X) -> X.\n",
+ []string{"g", "h"}},
+
+ // === Lua (9 cases) ===
+ {"lua_module_call", lang.Lua, "M.process(data)\n",
+ []string{"M.process"}},
+ {"lua_colon_call", lang.Lua, "obj:method(arg)\n",
+ []string{"obj:method"}},
+ {"lua_table_call", lang.Lua, "handlers[event](data)\n",
+ []string{"handlers[event]"}},
+ {"lua_nested_call", lang.Lua, "print(tostring(42))\n",
+ []string{"print", "tostring"}},
+ {"lua_require_call", lang.Lua, "local json = require('cjson')\n",
+ []string{"require"}},
+ {"lua_iife_call", lang.Lua, "(function() print('hi') end)()\n",
+ []string{"(function() print('hi') end)", "print"}},
+ {"lua_pcall", lang.Lua, "local ok, err = pcall(func)\n",
+ []string{"pcall"}},
+ {"lua_string_method", lang.Lua, "s:upper()\n",
+ []string{"s:upper"}},
+ {"lua_select_call", lang.Lua, "select('#', ...)\n",
+ []string{"select"}},
+
+ // === Bash (7 cases) ===
+ {"bash_command_call", lang.Bash, "greet 'world'\n",
+ []string{"greet"}},
+ {"bash_command_sub", lang.Bash, "result=$(process_data \"$input\")\n",
+ []string{"process_data"}},
+ {"bash_pipe_chain", lang.Bash, "cat file | grep pattern | sort\n",
+ []string{"cat", "grep", "sort"}},
+ {"bash_func_call", lang.Bash, "greet() { echo hi; }\ngreet\n",
+ []string{"echo", "greet"}},
+ {"bash_subshell", lang.Bash, "( cd /tmp && ls )\n",
+ []string{"cd", "ls"}},
+ {"bash_process_args", lang.Bash, "process \"$1\" \"$2\"\n",
+ []string{"process"}},
+ {"bash_conditional", lang.Bash, "if check_status; then handle_ok; else handle_err; fi\n",
+ []string{"check_status", "handle_ok", "handle_err"}},
+
+ // === Zig (8 cases) ===
+ {"zig_method_call", lang.Zig, "fn f(alloc: std.mem.Allocator) void { _ = alloc.alloc(u8, 1024); }\n",
+ []string{"alloc.alloc"}},
+ {"zig_builtin_call", lang.Zig, "fn f(x: i64) i32 { return @intCast(x); }\n",
+ []string{"@intCast"}},
+ {"zig_try_call", lang.Zig, "fn f(file: std.fs.File) !void { _ = try file.read(buf); }\n",
+ []string{"file.read"}},
+ {"zig_nested_call", lang.Zig, "fn f() void { std.debug.print(\"{}\", .{value}); }\n",
+ []string{"std.debug.print"}},
+ {"zig_comptime_call", lang.Zig, "fn f() type { return @TypeOf(value); }\n",
+ []string{"@TypeOf"}},
+ {"zig_std_mem_call", lang.Zig, "fn f() void { _ = std.mem.eql(u8, a, b); }\n",
+ []string{"std.mem.eql"}},
+ {"zig_error_call", lang.Zig, "fn f() !void { _ = try allocate(size); }\n",
+ []string{"allocate"}},
+ {"zig_multi_builtin", lang.Zig, "fn f(x: anytype) void { _ = @TypeOf(x); _ = @intCast(x); }\n",
+ []string{"@TypeOf", "@intCast"}},
+
+ // === ObjectiveC (6 cases) ===
+ {"objc_c_call", lang.ObjectiveC, "void f() { printf(\"hello\"); }\n",
+ []string{"printf"}},
+ {"objc_nslog", lang.ObjectiveC, "void f() { NSLog(@\"hello\"); }\n",
+ []string{"NSLog"}},
+ {"objc_nested_c_call", lang.ObjectiveC, "void f() { free(malloc(100)); }\n",
+ []string{"free", "malloc"}},
+ {"objc_dispatch", lang.ObjectiveC, "void f() { dispatch_async(queue, block); }\n",
+ []string{"dispatch_async"}},
+ // message_expression: method field extraction
+ {"objc_message_send", lang.ObjectiveC, "void f() { [obj method]; }\n",
+ []string{"obj.method"}},
+ {"objc_multi_c_call", lang.ObjectiveC, "void f() { a(); b(); c(); }\n",
+ []string{"a", "b", "c"}},
+
+ // === Swift (6 cases) ===
+ {"swift_simple_call", lang.Swift, "func f() { greet(\"hello\") }\n",
+ []string{"greet"}},
+ {"swift_member_call", lang.Swift, "func f(arr: [Int]) { arr.contains(42) }\n",
+ []string{"arr.contains"}},
+ {"swift_nested_call", lang.Swift, "func f() { print(String(42)) }\n",
+ []string{"print", "String"}},
+ {"swift_multi_call", lang.Swift, "func f() { a(); b(); c() }\n",
+ []string{"a", "b", "c"}},
+ {"swift_static_call", lang.Swift, "func f() { UIView.animate(withDuration: 1.0) {} }\n",
+ []string{"UIView.animate"}},
+ {"swift_guard_call", lang.Swift, "func f() { guard let v = getValue() else { return } }\n",
+ []string{"getValue"}},
+
+ // === Dart (6 cases) ===
+ // Dart uses "selector" CallNodeType — callee extracted from preceding sibling
+ {"dart_simple_call", lang.Dart, "void f() { print('hello'); }\n",
+ []string{"print"}},
+ {"dart_method_call", lang.Dart, "void f(List<int> list) { list.add(1); }\n",
+ []string{"list.add"}},
+ {"dart_nested_call", lang.Dart, "void f() { print(getValue()); }\n",
+ []string{"print", "getValue"}},
+ {"dart_chain_call", lang.Dart, "void f() { items.where((e) => e > 0).toList(); }\n",
+ []string{"items.where", "toList"}},
+ {"dart_static_call", lang.Dart, "void f() { DateTime.now(); }\n",
+ []string{"DateTime.now"}},
+ {"dart_async_call", lang.Dart, "Future<void> f() async { await fetchData(); }\n",
+ []string{"fetchData"}},
+
+ // === Perl (5 cases) ===
+ {"perl_simple_call", lang.Perl, "print \"hello\\n\";\n",
+ []string{"print"}},
+ {"perl_function_call", lang.Perl, "chomp($line);\n",
+ []string{"chomp"}},
+ {"perl_nested_call", lang.Perl, "print length($str);\n",
+ []string{"print", "length"}},
+ {"perl_multi_call", lang.Perl, "open(my $fh, '<', $file); read($fh, $buf, 100); close($fh);\n",
+ []string{"open", "read", "close"}},
+ {"perl_module_call", lang.Perl, "use File::Basename; my $dir = dirname($path);\n",
+ []string{"dirname"}},
+
+ // === Groovy (5 cases) ===
+ {"groovy_simple_call", lang.Groovy, "def f() { println('hello') }\n",
+ []string{"println"}},
+ {"groovy_method_call", lang.Groovy, "def f() { list.add(42) }\n",
+ []string{"list.add"}},
+ {"groovy_multi_call", lang.Groovy, "def f() { a(); b(); c() }\n",
+ []string{"a", "b", "c"}},
+ {"groovy_nested_call", lang.Groovy, "def f() { println(getValue()) }\n",
+ []string{"println", "getValue"}},
+ {"groovy_closure_call", lang.Groovy, "def f() { items.each { process(it) } }\n",
+ []string{"items.each", "process"}},
+
+ // === R (4 cases) ===
+ {"r_simple_call", lang.R, "f <- function() { print('hello') }\n",
+ []string{"print"}},
+ {"r_nested_call", lang.R, "f <- function(x) { paste(toupper(x), collapse='') }\n",
+ []string{"paste", "toupper"}},
+ {"r_pipe_call", lang.R, "f <- function(df) { filter(df, x > 0) }\n",
+ []string{"filter"}},
+ {"r_multi_call", lang.R, "f <- function() { a(); b(); c() }\n",
+ []string{"a", "b", "c"}},
+
+ // === HCL (3 cases) ===
+ // HCL function_call → first child identifier
+ {"hcl_file_call", lang.HCL, "resource \"null\" \"x\" {\n value = file(\"path\")\n}\n",
+ []string{"file"}},
+ {"hcl_merge_call", lang.HCL, "locals {\n config = merge(var.defaults, var.overrides)\n}\n",
+ []string{"merge"}},
+ {"hcl_nested_call", lang.HCL, "resource \"null\" \"x\" {\n value = jsonencode(tomap({a = 1}))\n}\n",
+ []string{"jsonencode", "tomap"}},
+
+ // === SQL (3 cases) ===
+ // SQL invocation → object_reference → identifier[name]
+ {"sql_count_call", lang.SQL, "SELECT COUNT(*) FROM users;\n",
+ []string{"COUNT"}},
+ {"sql_nested_call", lang.SQL, "SELECT COALESCE(NULLIF(name, ''), 'default') FROM t;\n",
+ []string{"COALESCE", "NULLIF"}},
+ {"sql_aggregate_call", lang.SQL, "SELECT MAX(salary) FROM employees;\n",
+ []string{"MAX"}},
+}
+
+func TestCalleeExtraction(t *testing.T) {
+ for _, tt := range calleeExtractionCases {
+ t.Run(tt.name, func(t *testing.T) {
+ tree, src := parseSource(t, tt.lang, tt.code)
+ defer tree.Close()
+ spec := lang.ForLanguage(tt.lang)
+ if spec == nil {
+ t.Fatalf("no spec for %s", tt.lang)
+ }
+ callNodeTypes := toSet(spec.CallNodeTypes)
+ var callees []string
+ parser.Walk(tree.RootNode(), func(node *tree_sitter.Node) bool {
+ if callNodeTypes[node.Kind()] {
+ name := extractCalleeName(node, src, tt.lang)
+ if name != "" {
+ callees = append(callees, name)
+ }
+ }
+ return true
+ })
+ if tt.wantCallees == nil {
+ if len(callees) != 0 {
+ dump := dumpNode(tree.RootNode(), src, 0)
+ t.Errorf("callees = %v, want nil\nAST:\n%s", callees, dump)
+ }
+ return
+ }
+ if !reflect.DeepEqual(callees, tt.wantCallees) {
+ dump := dumpNode(tree.RootNode(), src, 0)
+ t.Errorf("callees = %q, want %q\nAST:\n%s", callees, tt.wantCallees, dump)
+ }
+ })
+ }
+}
+
+// ============================================================================
+// TestOOPExtraction — assertion-based OOP extraction test suite
+//
+// Tests extractBaseClasses() and extractImplementsClause() for class declarations
+// across languages.
+// ============================================================================
+
+var oopExtractionCases = []struct {
+ name string
+ lang lang.Language
+ code string
+ wantBases []string
+ wantImplements []string
+}{
+ // === Python (5 cases) ===
+ {"py_single_base", lang.Python, "class A(B): pass\n",
+ []string{"B"}, nil},
+ {"py_multiple_bases", lang.Python, "class A(B, C): pass\n",
+ []string{"B", "C"}, nil},
+ {"py_abc_base", lang.Python, "class A(ABC): pass\n",
+ []string{"ABC"}, nil},
+ {"py_no_base", lang.Python, "class A: pass\n",
+ nil, nil},
+ {"py_metaclass", lang.Python, "class A(B, metaclass=Meta): pass\n",
+ []string{"B"}, nil},
+
+ // === JavaScript (5 cases) ===
+ {"js_class_extends", lang.JavaScript, "class Child extends Parent {}\n",
+ []string{"Parent"}, nil},
+ {"js_class_no_extends", lang.JavaScript, "class A {}\n",
+ nil, nil},
+ {"js_class_expression", lang.JavaScript, "const A = class extends B {};\n",
+ []string{"B"}, nil},
+ {"js_class_expression_no_base", lang.JavaScript, "const A = class {};\n",
+ nil, nil},
+ {"js_class_with_body", lang.JavaScript, "class A extends B { constructor() { super(); } }\n",
+ []string{"B"}, nil},
+
+ // === TypeScript (6 cases) ===
+ {"ts_implements", lang.TypeScript, "class A implements IService {}\n",
+ []string{"IService"}, []string{"IService"}},
+ {"ts_extends_implements", lang.TypeScript, "class A extends B implements IC, ID {}\n",
+ []string{"B", "IC", "ID"}, []string{"IC", "ID"}},
+ {"ts_abstract_class", lang.TypeScript, "abstract class Base implements IA {}\n",
+ []string{"IA"}, []string{"IA"}},
+ {"ts_interface_extends", lang.TypeScript, "interface IA extends IB {}\n",
+ nil, nil},
+ {"ts_class_no_heritage", lang.TypeScript, "class Plain {}\n",
+ nil, nil},
+ {"ts_generic_extends", lang.TypeScript, "class A extends Base<string> {}\n",
+ []string{"Base"}, nil},
+
+ // === TSX (3 cases) ===
+ {"tsx_implements", lang.TSX, "class App implements IComponent {}\n",
+ []string{"IComponent"}, []string{"IComponent"}},
+ {"tsx_extends", lang.TSX, "class App extends React.Component {}\n",
+ []string{"React.Component"}, nil},
+ {"tsx_no_heritage", lang.TSX, "class App {}\n",
+ nil, nil},
+
+ // === Java (7 cases) ===
+ {"java_implements", lang.Java, "class A implements Serializable {}\n",
+ []string{"Serializable"}, []string{"Serializable"}},
+ {"java_multi_implements", lang.Java, "class A implements IA, IB {}\n",
+ []string{"IA", "IB"}, []string{"IA", "IB"}},
+ {"java_extends_implements", lang.Java, "class A extends B implements IC {}\n",
+ []string{"B", "IC"}, []string{"IC"}},
+ {"java_generic_implements", lang.Java, "class A implements List<String> {}\n",
+ []string{"List"}, []string{"List"}},
+ {"java_record_implements", lang.Java, "record Point(int x, int y) implements Printable {}\n",
+ []string{"Printable"}, []string{"Printable"}},
+ {"java_enum", lang.Java, "enum Color { RED, GREEN, BLUE }\n",
+ nil, nil},
+ {"java_interface_extends", lang.Java, "interface IA extends IB {}\n",
+ nil, nil},
+
+ // === C# (7 cases) ===
+ {"csharp_single_interface", lang.CSharp, "class A : IService {}\n",
+ []string{"IService"}, []string{"IService"}},
+ {"csharp_multi_interface", lang.CSharp, "class A : IService, IDisposable {}\n",
+ []string{"IService", "IDisposable"}, []string{"IService", "IDisposable"}},
+ {"csharp_base_plus_interface", lang.CSharp, "class A : BaseClass, IService {}\n",
+ []string{"BaseClass", "IService"}, []string{"BaseClass", "IService"}},
+ {"csharp_struct_implements", lang.CSharp, "struct S : IEquatable<S> {}\n",
+ []string{"IEquatable"}, []string{"IEquatable", "S"}},
+ {"csharp_interface_extends", lang.CSharp, "interface IA : IB {}\n",
+ []string{"IB"}, []string{"IB"}},
+ {"csharp_no_base", lang.CSharp, "class Plain {}\n",
+ nil, nil},
+ {"csharp_record", lang.CSharp, "record User(string Name) : Entity;\n",
+ nil, nil}, // record_declaration not in ClassNodeTypes
+
+ // === Kotlin (6 cases) ===
+ {"kotlin_interface", lang.Kotlin, "class A : IA {}\n",
+ []string{"IA"}, []string{"IA"}},
+ {"kotlin_multi_delegation", lang.Kotlin, "class A : IA, IB {}\n",
+ []string{"IA", "IB"}, []string{"IA", "IB"}},
+ {"kotlin_data_class", lang.Kotlin, "data class User(val name: String) : Entity()\n",
+ []string{"Entity"}, []string{"Entity"}},
+ {"kotlin_object", lang.Kotlin, "object Singleton : IA, IB {}\n",
+ []string{"IA", "IB"}, []string{"IA", "IB"}},
+ {"kotlin_no_base", lang.Kotlin, "class Plain {}\n",
+ nil, nil},
+ {"kotlin_sealed", lang.Kotlin, "sealed class Result : Outcome {}\n",
+ []string{"Outcome"}, []string{"Outcome"}},
+
+ // === Scala (6 cases) ===
+ {"scala_extends_with_trait", lang.Scala, "class A extends B with C {}\n",
+ []string{"B", "C"}, []string{"B", "C"}},
+ {"scala_multi_traits", lang.Scala, "class A extends B with C with D {}\n",
+ []string{"B", "C", "D"}, []string{"B", "C", "D"}},
+ {"scala_object_extends", lang.Scala, "object A extends B {}\n",
+ []string{"B"}, []string{"B"}},
+ {"scala_case_class", lang.Scala, "case class Point(x: Int) extends Printable {}\n",
+ []string{"Printable"}, []string{"Printable"}},
+ {"scala_trait_extends", lang.Scala, "trait A extends B {}\n",
+ []string{"B"}, []string{"B"}},
+ {"scala_no_base", lang.Scala, "class Plain {}\n",
+ nil, nil},
+
+ // === PHP (6 cases) ===
+ {"php_implements", lang.PHP, "<?php\nclass A implements JsonSerializable {}\n",
+ nil, []string{"JsonSerializable"}},
+ {"php_multi_implements", lang.PHP, "<?php\nclass A implements IA, IB {}\n",
+ nil, []string{"IA", "IB"}},
+ {"php_extends_implements", lang.PHP, "<?php\nclass A extends B implements IC {}\n",
+ []string{"B"}, []string{"IC"}},
+ {"php_trait_decl", lang.PHP, "<?php\ntrait Loggable {}\n",
+ nil, nil},
+ {"php_interface_decl", lang.PHP, "<?php\ninterface Printable {}\n",
+ nil, nil},
+ {"php_extends_only", lang.PHP, "<?php\nclass A extends B {}\n",
+ []string{"B"}, nil},
+
+ // === Ruby (5 cases) ===
+ {"ruby_class_extends", lang.Ruby, "class Dog < Animal\nend\n",
+ []string{"Animal"}, nil},
+ {"ruby_include", lang.Ruby, "class A\n include Comparable\nend\n",
+ nil, nil},
+ {"ruby_extend", lang.Ruby, "class A\n extend ClassMethods\nend\n",
+ nil, nil},
+ {"ruby_multi_include", lang.Ruby, "class A\n include IA\n include IB\nend\n",
+ nil, nil},
+ {"ruby_scoped_include", lang.Ruby, "class A\n include Concerns::Validatable\nend\n",
+ nil, nil},
+
+ // === Rust (4 cases) ===
+ {"rust_no_trait_impl", lang.Rust, "impl Point { fn new() -> Self { Point{} } }\n",
+ nil, nil},
+ {"rust_struct_only", lang.Rust, "struct Point { x: i32, y: i32 }\n",
+ nil, nil},
+ {"rust_trait_decl", lang.Rust, "trait Display { fn fmt(&self); }\n",
+ nil, nil},
+ {"rust_enum", lang.Rust, "enum Color { Red, Green, Blue }\n",
+ nil, nil},
+
+ // === C++ (4 cases) ===
+ {"cpp_class_extends", lang.CPP, "class Child : public Parent {};\n",
+ []string{"Parent"}, nil},
+ {"cpp_multi_extends", lang.CPP, "class Child : public Base, public Mixin {};\n",
+ []string{"Base", "Mixin"}, nil},
+ {"cpp_struct_no_base", lang.CPP, "struct Point { int x; int y; };\n",
+ nil, nil},
+ {"cpp_abstract_class", lang.CPP, "class Widget : public QWidget {};\n",
+ []string{"QWidget"}, nil},
+
+ // === C (4 cases) ===
+ {"c_struct_no_base", lang.C, "struct Point { int x; int y; };\n",
+ nil, nil},
+ {"c_enum", lang.C, "enum Color { RED, GREEN, BLUE };\n",
+ nil, nil},
+ {"c_union", lang.C, "union Data { int i; float f; };\n",
+ nil, nil},
+ {"c_typedef_struct", lang.C, "typedef struct { int x; } Point;\n",
+ nil, nil},
+
+ // === Go (4 cases) ===
+ {"go_type_spec", lang.Go, "package main\ntype Config struct { Name string }\n",
+ nil, nil},
+ {"go_interface", lang.Go, "package main\ntype Reader interface { Read(p []byte) (int, error) }\n",
+ nil, nil},
+ {"go_type_alias", lang.Go, "package main\ntype MyString = string\n",
+ nil, nil},
+ {"go_embedded_struct", lang.Go, "package main\ntype Server struct { Config }\n",
+ nil, nil},
+
+ // === Zig (3 cases) ===
+ {"zig_struct", lang.Zig, "const Point = struct { x: i32, y: i32 };\n",
+ nil, nil},
+ {"zig_enum", lang.Zig, "const Color = enum { red, green, blue };\n",
+ nil, nil},
+ {"zig_union", lang.Zig, "const Value = union(enum) { int: i32, float: f64 };\n",
+ nil, nil},
+
+ // === Haskell (3 cases) ===
+ {"haskell_data", lang.Haskell, "data Color = Red | Green | Blue\n",
+ nil, nil},
+ {"haskell_newtype", lang.Haskell, "newtype Name = Name String\n",
+ nil, nil},
+ {"haskell_class", lang.Haskell, "class Printable a where\n display :: a -> String\n",
+ nil, nil},
+
+ // === OCaml (3 cases) ===
+ {"ocaml_type_def", lang.OCaml, "type color = Red | Green | Blue\n",
+ nil, nil},
+ {"ocaml_record", lang.OCaml, "type point = { x: float; y: float }\n",
+ nil, nil},
+ {"ocaml_class", lang.OCaml, "class point x y = object\n method get_x = x\nend\n",
+ nil, nil},
+
+ // === ObjectiveC (3 cases) ===
+ {"objc_interface", lang.ObjectiveC, "@interface Dog : Animal\n@end\n",
+ []string{"Animal"}, nil},
+ {"objc_no_base", lang.ObjectiveC, "@interface Simple\n@end\n",
+ nil, nil},
+ {"objc_protocol", lang.ObjectiveC, "@protocol Printable\n- (void)print;\n@end\n",
+ nil, nil},
+
+ // === Swift (5 cases) ===
+ {"swift_class_extends", lang.Swift, "class Dog: Animal {}\n",
+ []string{"Animal"}, nil},
+ {"swift_multi_protocol", lang.Swift, "class A: Equatable, Hashable {}\n",
+ []string{"Equatable", "Hashable"}, nil},
+ {"swift_struct", lang.Swift, "struct Point {}\n",
+ nil, nil},
+ {"swift_protocol", lang.Swift, "protocol Printable {}\n",
+ nil, nil},
+ {"swift_enum", lang.Swift, "enum Color: String { case red, green }\n",
+ []string{"String"}, nil},
+
+ // === Dart (4 cases) ===
+ {"dart_extends", lang.Dart, "class Dog extends Animal {}\n",
+ []string{"Animal"}, nil},
+ {"dart_implements", lang.Dart, "class A implements Printable {}\n",
+ []string{"Printable"}, []string{"Printable"}}, // Dart: both extractors find it
+ {"dart_mixin", lang.Dart, "mixin Loggable {}\n",
+ nil, nil},
+ {"dart_no_base", lang.Dart, "class Plain {}\n",
+ nil, nil},
+
+ // === Groovy (3 cases) ===
+ {"groovy_extends", lang.Groovy, "class Dog extends Animal {}\n",
+ []string{"Animal"}, nil},
+ {"groovy_no_base", lang.Groovy, "class Plain {}\n",
+ nil, nil},
+ {"groovy_with_body", lang.Groovy, "class A extends B { void f() {} }\n",
+ []string{"B"}, nil},
+
+ // === HCL (2 cases) ===
+ {"hcl_resource_block", lang.HCL, "resource \"google_cloud_run_service\" \"api\" {\n name = \"api\"\n}\n",
+ nil, nil},
+ {"hcl_variable_block", lang.HCL, "variable \"region\" {\n default = \"us-east1\"\n}\n",
+ nil, nil},
+}
+
+func TestOOPExtraction(t *testing.T) {
+ for _, tt := range oopExtractionCases {
+ t.Run(tt.name, func(t *testing.T) {
+ tree, src := parseSource(t, tt.lang, tt.code)
+ defer tree.Close()
+ spec := lang.ForLanguage(tt.lang)
+ if spec == nil {
+ t.Fatalf("no spec for %s", tt.lang)
+ }
+ classNodeTypes := toSet(spec.ClassNodeTypes)
+
+ var allBases []string
+ var allImplements []string
+
+ parser.Walk(tree.RootNode(), func(node *tree_sitter.Node) bool {
+ if !classNodeTypes[node.Kind()] && !isClassDeclaration(node.Kind(), tt.lang) {
+ return true
+ }
+
+ bases := extractBaseClasses(node, src, tt.lang)
+ allBases = append(allBases, bases...)
+
+ impls := extractImplementsClause(node, src, tt.lang)
+ allImplements = append(allImplements, impls...)
+
+ return true
+ })
+
+ // Normalize nil vs empty
+ if len(allBases) == 0 {
+ allBases = nil
+ }
+ if len(allImplements) == 0 {
+ allImplements = nil
+ }
+
+ if !reflect.DeepEqual(allBases, tt.wantBases) {
+ dump := dumpNode(tree.RootNode(), src, 0)
+ t.Errorf("bases = %v, want %v\nAST:\n%s", allBases, tt.wantBases, dump)
+ }
+ if !reflect.DeepEqual(allImplements, tt.wantImplements) {
+ dump := dumpNode(tree.RootNode(), src, 0)
+ t.Errorf("implements = %v, want %v\nAST:\n%s", allImplements, tt.wantImplements, dump)
+ }
+ })
+ }
+}
+
+// ============================================================================
+// Helpers — extractDecoratorsFromCode, extractParamTypesFromCode,
+// extractComplexityFromCode
+// ============================================================================
+
+// extractDecoratorsFromCode parses code and returns a map of funcName → decorator strings.
+func extractDecoratorsFromCode(t *testing.T, language lang.Language, code string) map[string][]string {
+ t.Helper()
+ tree, src := parseSource(t, language, code)
+ defer tree.Close()
+ spec := lang.ForLanguage(language)
+ if spec == nil {
+ t.Fatalf("no spec for %s", language)
+ }
+ funcTypes := toSet(spec.FunctionNodeTypes)
+ classTypes := toSet(spec.ClassNodeTypes)
+ result := make(map[string][]string)
+ parser.Walk(tree.RootNode(), func(node *tree_sitter.Node) bool {
+ isFuncOrClass := funcTypes[node.Kind()] || classTypes[node.Kind()] || isClassDeclaration(node.Kind(), language)
+ if !isFuncOrClass {
+ return true
+ }
+ nameNode := resolveFuncNameNode(node, language)
+ if nameNode == nil {
+ // Fallback for class nodes that use "name" field directly
+ nameNode = node.ChildByFieldName("name")
+ }
+ if nameNode == nil {
+ return true
+ }
+ nodeName := parser.NodeText(nameNode, src)
+ decs := extractAllDecorators(node, src, language, spec)
+ if len(decs) > 0 {
+ result[nodeName] = decs
+ }
+ return true
+ })
+ return result
+}
+
+// extractParamTypesFromCode parses code and returns a map of funcName → param type strings.
+//
+//nolint:gocognit // WHY: test helper with inherent complexity from multi-language AST extraction
+func extractParamTypesFromCode(t *testing.T, language lang.Language, code string) map[string][]string {
+ t.Helper()
+ tree, src := parseSource(t, language, code)
+ defer tree.Close()
+ spec := lang.ForLanguage(language)
+ if spec == nil {
+ t.Fatalf("no spec for %s", language)
+ }
+ funcTypes := toSet(spec.FunctionNodeTypes)
+ result := make(map[string][]string)
+ parser.Walk(tree.RootNode(), func(node *tree_sitter.Node) bool {
+ if !funcTypes[node.Kind()] {
+ return true
+ }
+ nameNode := resolveFuncNameNode(node, language)
+ if nameNode == nil {
+ return true
+ }
+ nodeName := parser.NodeText(nameNode, src)
+ paramsNode := node.ChildByFieldName("parameters")
+ if paramsNode == nil {
+ paramsNode = findChildByKind(node, "parameters")
+ }
+ if paramsNode == nil {
+ paramsNode = findChildByKind(node, "formal_parameters")
+ }
+ if paramsNode == nil {
+ paramsNode = findChildByKind(node, "parameter_list")
+ }
+ // Kotlin: function_value_parameters
+ if paramsNode == nil {
+ paramsNode = findChildByKind(node, "function_value_parameters")
+ }
+ // Dart: formal_parameter_list (on function_signature inside method_signature)
+ if paramsNode == nil {
+ paramsNode = findChildByKind(node, "formal_parameter_list")
+ }
+ // Dart method_signature: dig into function_signature for params
+ if paramsNode == nil && node.Kind() == "method_signature" {
+ if fs := findChildByKind(node, "function_signature"); fs != nil {
+ paramsNode = findChildByKind(fs, "formal_parameter_list")
+ }
+ }
+ // C/C++: params inside function_declarator
+ if paramsNode == nil {
+ if declNode := node.ChildByFieldName("declarator"); declNode != nil {
+ paramsNode = declNode.ChildByFieldName("parameters")
+ if paramsNode == nil {
+ paramsNode = findChildByKind(declNode, "parameter_list")
+ }
+ }
+ }
+ // OCaml: params are on let_binding child, not value_definition
+ if paramsNode == nil && node.Kind() == "value_definition" {
+ if lb := findChildByKind(node, "let_binding"); lb != nil {
+ // OCaml params are direct children of let_binding — use it as param container
+ paramsNode = lb
+ }
+ }
+ // Swift: params are direct children of function_declaration (no wrapper node)
+ if paramsNode == nil && language == lang.Swift {
+ paramsNode = node
+ }
+ if paramsNode != nil {
+ types := extractParamTypes(paramsNode, src, language)
+ if len(types) > 0 {
+ result[nodeName] = types
+ }
+ }
+ return true
+ })
+ return result
+}
+
+// extractComplexityFromCode parses code and returns a map of funcName → complexity count.
+func extractComplexityFromCode(t *testing.T, language lang.Language, code string) map[string]int {
+ t.Helper()
+ tree, src := parseSource(t, language, code)
+ defer tree.Close()
+ spec := lang.ForLanguage(language)
+ if spec == nil {
+ t.Fatalf("no spec for %s", language)
+ }
+ funcTypes := toSet(spec.FunctionNodeTypes)
+ result := make(map[string]int)
+ parser.Walk(tree.RootNode(), func(node *tree_sitter.Node) bool {
+ if !funcTypes[node.Kind()] {
+ return true
+ }
+ nameNode := resolveFuncNameNode(node, language)
+ if nameNode == nil {
+ return true
+ }
+ nodeName := parser.NodeText(nameNode, src)
+ result[nodeName] = countBranchingNodes(node, spec.BranchingNodeTypes)
+ return true
+ })
+ return result
+}
+
+// ============================================================================
+// TestDecoratorExtraction — decorator/annotation extraction across languages
+// ============================================================================
+
+var decoratorExtractionCases = []struct {
+ name string
+ lang lang.Language
+ code string
+ funcName string
+ wantDecorators []string
+}{
+ // === Python (6 cases) ===
+ {"py_single_decorator", lang.Python, "@app.route('/api')\ndef handler(): pass\n",
+ "handler", []string{"@app.route('/api')"}},
+ {"py_multi_decorator", lang.Python, "@login_required\n@cache(timeout=300)\ndef view(): pass\n",
+ "view", []string{"@login_required", "@cache(timeout=300)"}},
+ {"py_no_decorator", lang.Python, "def plain(): pass\n",
+ "plain", nil},
+ {"py_property_decorator", lang.Python, "class A:\n @property\n def name(self): return self._name\n",
+ "name", []string{"@property"}},
+ {"py_class_decorator", lang.Python, "@dataclass\nclass Config:\n name: str\n",
+ "Config", []string{"@dataclass"}},
+ {"py_staticmethod", lang.Python, "class A:\n @staticmethod\n def create(): return A()\n",
+ "create", []string{"@staticmethod"}},
+
+ // === Java (5 cases) ===
+ {"java_override", lang.Java, "class A {\n @Override\n public void run() {}\n}\n",
+ "run", []string{"@Override"}},
+ {"java_multi_annotation", lang.Java, "class A {\n @SuppressWarnings(\"unchecked\")\n @Deprecated\n public void old() {}\n}\n",
+ "old", []string{"@SuppressWarnings(\"unchecked\")", "@Deprecated"}},
+ {"java_no_annotation", lang.Java, "class A {\n public void plain() {}\n}\n",
+ "plain", nil},
+ {"java_nullable", lang.Java, "class A {\n @Nullable\n public String get() { return null; }\n}\n",
+ "get", []string{"@Nullable"}},
+ {"java_class_annotation", lang.Java, "@Entity\nclass User {}\n",
+ "User", []string{"@Entity"}},
+
+ // === TypeScript (4 cases) ===
+ {"ts_class_decorator", lang.TypeScript, "@Component({selector: 'app'})\nclass AppComponent {}\n",
+ "AppComponent", []string{"@Component({selector: 'app'})"}},
+ {"ts_injectable", lang.TypeScript, "@Injectable()\nclass Service {}\n",
+ "Service", []string{"@Injectable()"}},
+ {"ts_no_decorator", lang.TypeScript, "class Plain {}\n",
+ "Plain", nil},
+ {"ts_multi_decorator", lang.TypeScript, "@Sealed\n@Serializable\nclass Model {}\n",
+ "Model", []string{"@Sealed", "@Serializable"}},
+
+ // === TSX (2 cases) ===
+ {"tsx_class_decorator", lang.TSX, "@observer\nclass App {}\n",
+ "App", []string{"@observer"}},
+ {"tsx_no_decorator", lang.TSX, "class Plain {}\n",
+ "Plain", nil},
+
+ // === C# (5 cases) ===
+ {"csharp_attribute", lang.CSharp, "class A {\n [HttpGet]\n public void Get() {}\n}\n",
+ "Get", []string{"HttpGet"}},
+ {"csharp_multi_attr", lang.CSharp, "class A {\n [HttpPost]\n [Authorize]\n public void Create() {}\n}\n",
+ "Create", []string{"HttpPost", "Authorize"}},
+ {"csharp_no_attr", lang.CSharp, "class A {\n public void Plain() {}\n}\n",
+ "Plain", nil},
+ {"csharp_class_attr", lang.CSharp, "[Serializable]\nclass Config {}\n",
+ "Config", []string{"Serializable"}},
+ {"csharp_route_attr", lang.CSharp, "class A {\n [Route(\"/api\")]\n public void Index() {}\n}\n",
+ "Index", []string{"Route(\"/api\")"}},
+
+ // === Kotlin (5 cases) ===
+ {"kotlin_annotation", lang.Kotlin, "@JvmStatic\nfun main() {}\n",
+ "main", []string{"@JvmStatic"}},
+ {"kotlin_multi", lang.Kotlin, "@JvmStatic\n@Deprecated(\"use new\")\nfun old() {}\n",
+ "old", []string{"@JvmStatic", "@Deprecated(\"use new\")"}},
+ {"kotlin_no_annotation", lang.Kotlin, "fun plain() {}\n",
+ "plain", nil},
+ {"kotlin_suppress", lang.Kotlin, "@Suppress(\"UNCHECKED_CAST\")\nfun cast() {}\n",
+ "cast", []string{"@Suppress(\"UNCHECKED_CAST\")"}},
+ {"kotlin_class_annotation", lang.Kotlin, "@Serializable\nclass Config {}\n",
+ "Config", []string{"@Serializable"}},
+
+ // === Rust (5 cases) ===
+ {"rust_derive", lang.Rust, "#[derive(Debug)]\nstruct Point { x: i32 }\n",
+ "Point", []string{"derive(Debug)"}},
+ {"rust_test_attr", lang.Rust, "#[test]\nfn test_it() {}\n",
+ "test_it", []string{"test"}},
+ {"rust_no_attr", lang.Rust, "fn plain() {}\n",
+ "plain", nil},
+ {"rust_cfg_attr", lang.Rust, "#[cfg(test)]\nfn test_only() {}\n",
+ "test_only", []string{"cfg(test)"}},
+ {"rust_multi_derive", lang.Rust, "#[derive(Debug, Clone, Serialize)]\nstruct Data { value: i32 }\n",
+ "Data", []string{"derive(Debug, Clone, Serialize)"}},
+
+ // === PHP (4 cases) ===
+ {"php_attribute", lang.PHP, "<?php\n#[Route('/api')]\nfunction handler() {}\n",
+ "handler", []string{"Route('/api')"}},
+ {"php_multi_attr", lang.PHP, "<?php\n#[Route('/api')]\n#[Method('GET')]\nfunction getAll() {}\n",
+ "getAll", []string{"Route('/api')", "Method('GET')"}},
+ {"php_no_attr", lang.PHP, "<?php\nfunction plain() {}\n",
+ "plain", nil},
+ {"php_class_attr", lang.PHP, "<?php\n#[Entity]\nclass User {}\n",
+ "User", []string{"Entity"}}, // PHP attributes extracted from preceding siblings
+
+ // === Swift (4 cases) ===
+ // Swift: attributes inside modifiers child
+ {"swift_available", lang.Swift, "@available(iOS 15, *)\nfunc newFeature() {}\n",
+ "newFeature", []string{"@available(iOS 15, *)"}},
+ {"swift_objc", lang.Swift, "@objc\nfunc bridgedMethod() {}\n",
+ "bridgedMethod", []string{"@objc"}},
+ {"swift_no_attr", lang.Swift, "func plain() {}\n",
+ "plain", nil},
+ {"swift_discardable", lang.Swift, "@discardableResult\nfunc compute() -> Int { return 42 }\n",
+ "compute", []string{"@discardableResult"}},
+
+ // === Groovy (3 cases) ===
+ // Groovy: annotations as direct children of function_definition
+ {"groovy_compile_static", lang.Groovy, "@CompileStatic\ndef process() {}\n",
+ "process", []string{"@CompileStatic"}},
+ {"groovy_no_annotation", lang.Groovy, "def plain() {}\n",
+ "plain", nil},
+ {"groovy_override", lang.Groovy, "@Override\ndef toString() {}\n",
+ "toString", []string{"@Override"}},
+
+ // === Dart (3 cases) ===
+ // Dart: annotations as preceding siblings
+ {"dart_override", lang.Dart, "class A {\n @override\n String toString() => '';\n}\n",
+ "toString", []string{"@override"}},
+ {"dart_deprecated", lang.Dart, "class A {\n @deprecated\n void old() {}\n}\n",
+ "old", []string{"@deprecated"}},
+ {"dart_no_annotation", lang.Dart, "class A {\n void plain() {}\n}\n",
+ "plain", nil},
+}
+
+func TestDecoratorExtraction(t *testing.T) {
+ for _, tt := range decoratorExtractionCases {
+ t.Run(tt.name, func(t *testing.T) {
+ result := extractDecoratorsFromCode(t, tt.lang, tt.code)
+ got := result[tt.funcName]
+ if tt.wantDecorators == nil {
+ if len(got) != 0 {
+ t.Errorf("decorators[%s] = %v, want nil", tt.funcName, got)
+ }
+ return
+ }
+ if !reflect.DeepEqual(got, tt.wantDecorators) {
+ t.Errorf("decorators[%s] = %v, want %v", tt.funcName, got, tt.wantDecorators)
+ }
+ })
+ }
+}
+
+// ============================================================================
+// TestParamTypeExtraction — parameter type extraction across languages
+// ============================================================================
+
+var paramTypeExtractionCases = []struct {
+ name string
+ lang lang.Language
+ code string
+ funcName string
+ wantParamTypes []string
+}{
+ // === Go (4 cases) ===
+ {"go_typed_params", lang.Go, "package main\nfunc Process(cfg *Config, name string) error { return nil }\n",
+ "Process", []string{"Config"}},
+ {"go_no_custom_types", lang.Go, "package main\nfunc Add(a, b int) int { return a + b }\n",
+ "Add", nil},
+ {"go_multi_custom", lang.Go, "package main\nfunc Handle(req *Request, resp *Response) {}\n",
+ "Handle", []string{"Request", "Response"}},
+ {"go_interface_param", lang.Go, "package main\nfunc Read(r Reader) {}\n",
+ "Read", []string{"Reader"}},
+
+ // === Python (3 cases) ===
+ {"py_typed_params", lang.Python, "def process(cfg: Config, name: str) -> bool:\n pass\n",
+ "process", []string{"Config"}},
+ {"py_multi_custom", lang.Python, "def handle(req: Request, resp: Response) -> None:\n pass\n",
+ "handle", []string{"Request", "Response"}},
+ {"py_no_types", lang.Python, "def plain(a, b):\n pass\n",
+ "plain", nil},
+
+ // === TypeScript (4 cases) ===
+ {"ts_typed_params", lang.TypeScript, "function process(cfg: Config, name: string): boolean { return true; }\n",
+ "process", []string{"Config"}},
+ {"ts_multi_custom", lang.TypeScript, "function handle(req: Request, resp: Response): void {}\n",
+ "handle", []string{"Request", "Response"}},
+ {"ts_optional_param", lang.TypeScript, "function f(name?: UserName): void {}\n",
+ "f", []string{"UserName"}},
+ {"ts_no_custom", lang.TypeScript, "function add(a: number, b: number): number { return a + b; }\n",
+ "add", nil},
+
+ // === TSX (2 cases) ===
+ {"tsx_typed_params", lang.TSX, "function App(props: AppProps): JSX.Element { return null; }\n",
+ "App", []string{"AppProps"}}, // return type not extracted as param
+ {"tsx_no_custom", lang.TSX, "function add(a: number, b: number): number { return a + b; }\n",
+ "add", nil},
+
+ // === Java (3 cases) ===
+ {"java_typed_params", lang.Java, "class A {\n void process(Config cfg, String name) {}\n}\n",
+ "process", []string{"Config"}},
+ {"java_multi_custom", lang.Java, "class A {\n void handle(Request req, Response resp) {}\n}\n",
+ "handle", []string{"Request", "Response"}},
+ {"java_no_custom", lang.Java, "class A {\n void add(int a, int b) {}\n}\n",
+ "add", nil},
+
+ // === Rust (3 cases) ===
+ {"rust_typed_params", lang.Rust, "fn process(cfg: Config, name: &str) -> bool { true }\n",
+ "process", []string{"Config"}},
+ {"rust_multi_custom", lang.Rust, "fn handle(req: Request, resp: Response) {}\n",
+ "handle", []string{"Request", "Response"}},
+ {"rust_no_custom", lang.Rust, "fn add(a: i32, b: i32) -> i32 { a + b }\n",
+ "add", nil},
+
+ // === C# (3 cases) ===
+ {"csharp_typed_params", lang.CSharp, "class A {\n void Process(Config cfg, string name) {}\n}\n",
+ "Process", []string{"Config"}},
+ {"csharp_multi_custom", lang.CSharp, "class A {\n void Handle(Request req, Response resp) {}\n}\n",
+ "Handle", []string{"Request", "Response"}},
+ {"csharp_no_custom", lang.CSharp, "class A {\n void Add(int a, int b) {}\n}\n",
+ "Add", nil},
+
+ // === C++ (2 cases) ===
+ // C/C++ params inside function_declarator — found by helper's declarator fallback
+ {"cpp_typed_params", lang.CPP, "void process(Config cfg, std::string name) {}\n",
+ "process", []string{"Config", "std::string"}},
+ {"cpp_no_params", lang.CPP, "void empty() {}\n",
+ "empty", nil},
+
+ // === C (2 cases) ===
+ // C params inside function_declarator — Config extracted, char filtered as builtin
+ {"c_typed_params", lang.C, "void process(Config* cfg, const char* name) {}\n",
+ "process", []string{"Config"}},
+ {"c_no_params", lang.C, "void empty() {}\n",
+ "empty", nil},
+
+ // === PHP (3 cases) ===
+ {"php_typed_params", lang.PHP, "<?php\nfunction process(Config $cfg, string $name): bool {}\n",
+ "process", []string{"Config"}},
+ {"php_no_custom", lang.PHP, "<?php\nfunction add(int $a, int $b): int { return $a + $b; }\n",
+ "add", nil},
+ {"php_variadic", lang.PHP, "<?php\nfunction collect(Item ...$items): void {}\n",
+ "collect", []string{"Item"}},
+
+ // === Kotlin (3 cases) ===
+ // Kotlin: function_value_parameters wrapper, String/Int filtered as builtin
+ {"kotlin_typed_params", lang.Kotlin, "fun process(cfg: Config, name: String) {}\n",
+ "process", []string{"Config"}},
+ {"kotlin_multi_custom", lang.Kotlin, "fun handle(req: Request, resp: Response) {}\n",
+ "handle", []string{"Request", "Response"}},
+ {"kotlin_no_custom", lang.Kotlin, "fun add(a: Int, b: Int): Int = a + b\n",
+ "add", nil},
+
+ // === Scala (3 cases) ===
+ // Scala: String/Int/Boolean/Unit filtered as builtin
+ {"scala_typed_params", lang.Scala, "def process(cfg: Config, name: String): Boolean = true\n",
+ "process", []string{"Config"}},
+ {"scala_multi_custom", lang.Scala, "def handle(req: Request, resp: Response): Unit = {}\n",
+ "handle", []string{"Request", "Response"}},
+ {"scala_no_custom", lang.Scala, "def add(a: Int, b: Int): Int = a + b\n",
+ "add", nil},
+
+ // === Zig (3 cases) ===
+ {"zig_typed_params", lang.Zig, "fn process(cfg: Config, name: []const u8) bool { return true; }\n",
+ "process", []string{"Config", "const u8"}},
+ {"zig_no_custom", lang.Zig, "fn add(a: i32, b: i32) i32 { return a + b; }\n",
+ "add", nil},
+ {"zig_allocator_param", lang.Zig, "fn init(alloc: Allocator) Self { return .{}; }\n",
+ "init", []string{"Allocator"}}, // Self is return type, not param
+
+ // === Swift (2 cases) ===
+ // Swift: params as direct children, String/Int/Bool filtered as builtin
+ {"swift_typed_params", lang.Swift, "func process(cfg: Config, name: String) -> Bool { return true }\n",
+ "process", []string{"Config"}},
+ {"swift_no_custom", lang.Swift, "func add(a: Int, b: Int) -> Int { return a + b }\n",
+ "add", nil},
+
+ // === Haskell (no param types) ===
+ {"haskell_no_params", lang.Haskell, "f :: Int -> Int\nf x = x + 1\n",
+ "f", nil},
+
+ // === Ruby (no param types) ===
+ {"ruby_no_params", lang.Ruby, "def process(cfg, name)\nend\n",
+ "process", nil},
+
+ // === Perl (no param types) ===
+ {"perl_no_params", lang.Perl, "sub process { my ($cfg, $name) = @_; }\n",
+ "process", nil},
+
+ // === Erlang (no param types) ===
+ {"erlang_no_params", lang.Erlang, "-module(m).\nf(Cfg, Name) -> ok.\n",
+ "f", nil},
+
+ // === Elixir (no param types) ===
+ {"elixir_no_params", lang.Elixir, "defmodule A do\n def f(cfg, name), do: :ok\nend\n",
+ "f", nil},
+
+ // === R (no param types) ===
+ {"r_no_params", lang.R, "f <- function(cfg, name) { cfg }\n",
+ "f", nil},
+
+ // === OCaml (2 cases) ===
+ // OCaml: parameter → typed_pattern → type, string/bool filtered as builtin
+ {"ocaml_typed_params", lang.OCaml, "let process (cfg : config) (name : string) : bool = true\n",
+ "process", []string{"config"}},
+ {"ocaml_no_types", lang.OCaml, "let add a b = a + b\n",
+ "add", nil},
+
+ // === Groovy (2 cases) ===
+ // Groovy: parameter with type field, String filtered as builtin
+ {"groovy_typed_params", lang.Groovy, "def process(Config cfg, String name) {}\n",
+ "process", []string{"Config"}},
+ {"groovy_no_types", lang.Groovy, "def add(a, b) { a + b }\n",
+ "add", nil},
+
+ // === Dart (2 cases) ===
+ // Dart: formal_parameter_list inside function_signature, String filtered
+ {"dart_typed_params", lang.Dart, "class A {\n void process(Config cfg, String name) {}\n}\n",
+ "process", []string{"Config"}},
+ {"dart_no_custom", lang.Dart, "class A {\n int add(int a, int b) => a + b;\n}\n",
+ "add", nil},
+}
+
+func TestParamTypeExtraction(t *testing.T) {
+ for _, tt := range paramTypeExtractionCases {
+ t.Run(tt.name, func(t *testing.T) {
+ result := extractParamTypesFromCode(t, tt.lang, tt.code)
+ got := result[tt.funcName]
+ if tt.wantParamTypes == nil {
+ if len(got) != 0 {
+ t.Errorf("paramTypes[%s] = %v, want nil", tt.funcName, got)
+ }
+ return
+ }
+ if !reflect.DeepEqual(got, tt.wantParamTypes) {
+ t.Errorf("paramTypes[%s] = %v, want %v", tt.funcName, got, tt.wantParamTypes)
+ }
+ })
+ }
+}
+
+// ============================================================================
+// TestComplexityExtraction — branching complexity across languages
+// ============================================================================
+
+var complexityExtractionCases = []struct {
+ name string
+ lang lang.Language
+ code string
+ funcName string
+ wantComplexity int
+}{
+ // === Go (3 cases) ===
+ {"go_complexity", lang.Go, "package main\nfunc f(x int) int {\n if x > 0 {\n for i := 0; i < x; i++ {\n if i%2 == 0 { continue }\n }\n return x\n }\n return 0\n}\n",
+ "f", 3},
+ {"go_zero_complexity", lang.Go, "package main\nfunc simple() int { return 42 }\n",
+ "simple", 0},
+ {"go_switch", lang.Go, "package main\nfunc f(x int) {\n switch x {\n case 1: break\n case 2: break\n default: break\n }\n}\n",
+ "f", 0}, // Go BranchingNodeTypes: if_statement, for_statement, go_statement — no switch
+
+ // === Python (3 cases) ===
+ {"py_complexity", lang.Python, "def f(x):\n if x > 0:\n for i in range(x):\n if i % 2 == 0:\n continue\n return x\n return 0\n",
+ "f", 3},
+ {"py_zero_complexity", lang.Python, "def simple():\n return 42\n",
+ "simple", 0},
+ {"py_try_except", lang.Python, "def f():\n try:\n process()\n except ValueError:\n handle()\n",
+ "f", 2}, // try_statement + except_clause
+
+ // === JavaScript (3 cases) ===
+ {"js_complexity", lang.JavaScript, "function f(x) {\n if (x > 0) {\n for (let i = 0; i < x; i++) {\n if (i % 2 === 0) continue;\n }\n return x;\n }\n return 0;\n}\n",
+ "f", 3},
+ {"js_zero_complexity", lang.JavaScript, "function simple() { return 42; }\n",
+ "simple", 0},
+ {"js_switch", lang.JavaScript, "function f(x) {\n switch(x) {\n case 1: return 'a';\n case 2: return 'b';\n }\n}\n",
+ "f", 1}, // JS BranchingNodeTypes includes switch_statement only, not case clauses
+
+ // === TypeScript (2 cases) ===
+ {"ts_complexity", lang.TypeScript, "function f(x: number): number {\n if (x > 0) {\n for (let i = 0; i < x; i++) {\n if (i % 2 === 0) continue;\n }\n }\n return 0;\n}\n",
+ "f", 3},
+ {"ts_zero_complexity", lang.TypeScript, "function simple(): number { return 42; }\n",
+ "simple", 0},
+
+ // === TSX (2 cases) ===
+ {"tsx_complexity", lang.TSX, "function f(x: number): number {\n if (x > 0) {\n for (let i = 0; i < x; i++) {}\n }\n return 0;\n}\n",
+ "f", 2},
+ {"tsx_zero_complexity", lang.TSX, "function simple(): number { return 42; }\n",
+ "simple", 0},
+
+ // === Java (3 cases) ===
+ {"java_complexity", lang.Java, "class A {\n int f(int x) {\n if (x > 0) {\n for (int i = 0; i < x; i++) {\n if (i % 2 == 0) continue;\n }\n return x;\n }\n return 0;\n }\n}\n",
+ "f", 3},
+ {"java_zero_complexity", lang.Java, "class A {\n int simple() { return 42; }\n}\n",
+ "simple", 0},
+ {"java_try_catch", lang.Java, "class A {\n void f() {\n try { process(); } catch (Exception e) { handle(); }\n }\n}\n",
+ "f", 2}, // try_statement + catch_clause
+
+ // === C# (3 cases) ===
+ {"csharp_complexity", lang.CSharp, "class A {\n int F(int x) {\n if (x > 0) {\n for (int i = 0; i < x; i++) {\n if (i % 2 == 0) continue;\n }\n }\n return 0;\n }\n}\n",
+ "F", 3},
+ {"csharp_zero_complexity", lang.CSharp, "class A {\n int Simple() { return 42; }\n}\n",
+ "Simple", 0},
+ {"csharp_foreach", lang.CSharp, "class A {\n void F() {\n foreach (var i in items) {\n if (i > 0) Process(i);\n }\n }\n}\n",
+ "F", 2}, // foreach_statement + if_statement
+
+ // === Rust (3 cases) ===
+ {"rust_complexity", lang.Rust, "fn f(x: i32) -> i32 {\n if x > 0 {\n for i in 0..x {\n if i % 2 == 0 { continue; }\n }\n return x;\n }\n 0\n}\n",
+ "f", 3},
+ {"rust_zero_complexity", lang.Rust, "fn simple() -> i32 { 42 }\n",
+ "simple", 0},
+ {"rust_match", lang.Rust, "fn f(x: Option<i32>) -> i32 {\n match x {\n Some(v) => v,\n None => 0,\n }\n}\n",
+ "f", 3}, // match_expression + 2 match_arm
+
+ // === C++ (2 cases) ===
+ // C++: if + for + if = 3
+ {"cpp_complexity", lang.CPP, "int f(int x) {\n if (x > 0) {\n for (int i = 0; i < x; i++) {\n if (i % 2 == 0) continue;\n }\n }\n return 0;\n}\n",
+ "f", 3},
+ {"cpp_zero_complexity", lang.CPP, "int simple() { return 42; }\n",
+ "simple", 0},
+
+ // === C (2 cases) ===
+ // C: if + for + if = 3
+ {"c_complexity", lang.C, "int f(int x) {\n if (x > 0) {\n for (int i = 0; i < x; i++) {\n if (i % 2 == 0) continue;\n }\n }\n return 0;\n}\n",
+ "f", 3},
+ {"c_zero_complexity", lang.C, "int simple() { return 42; }\n",
+ "simple", 0},
+
+ // === PHP (2 cases) ===
+ {"php_complexity", lang.PHP, "<?php\nfunction f($x) {\n if ($x > 0) {\n for ($i = 0; $i < $x; $i++) {\n if ($i % 2 == 0) continue;\n }\n }\n return 0;\n}\n",
+ "f", 3},
+ {"php_zero_complexity", lang.PHP, "<?php\nfunction simple() { return 42; }\n",
+ "simple", 0},
+
+ // === Kotlin (2 cases) ===
+ {"kotlin_complexity", lang.Kotlin, "fun f(x: Int): Int {\n if (x > 0) {\n for (i in 0 until x) {\n if (i % 2 == 0) continue\n }\n }\n return 0\n}\n",
+ "f", 3},
+ {"kotlin_zero_complexity", lang.Kotlin, "fun simple(): Int = 42\n",
+ "simple", 0},
+
+ // === Scala (2 cases) ===
+ {"scala_complexity", lang.Scala, "def f(x: Int): Int = {\n if (x > 0) {\n for (i <- 0 until x) {\n if (i % 2 == 0) {}\n }\n }\n 0\n}\n",
+ "f", 3}, // if + for + if
+ {"scala_zero_complexity", lang.Scala, "def simple(): Int = 42\n",
+ "simple", 0},
+
+ // === Ruby (2 cases) ===
+ {"ruby_complexity", lang.Ruby, "def f(x)\n if x > 0\n while x > 1\n x -= 1\n end\n end\nend\n",
+ "f", 4}, // actual: if + while + operator_assignment + binary counted as branching
+ {"ruby_zero_complexity", lang.Ruby, "def simple\n 42\nend\n",
+ "simple", 0},
+
+ // === Lua (2 cases) ===
+ {"lua_complexity", lang.Lua, "function f(x)\n if x > 0 then\n for i = 1, x do\n if i % 2 == 0 then end\n end\n end\nend\n",
+ "f", 3},
+ {"lua_zero_complexity", lang.Lua, "function simple()\n return 42\nend\n",
+ "simple", 0},
+
+ // === Bash (2 cases) ===
+ {"bash_complexity", lang.Bash, "f() {\n if [ $1 -gt 0 ]; then\n while [ $1 -gt 1 ]; do\n shift\n done\n fi\n}\n",
+ "f", 2}, // if_statement + while_statement
+ {"bash_zero_complexity", lang.Bash, "simple() {\n echo 42\n}\n",
+ "simple", 0},
+
+ // === Zig (2 cases) ===
+ {"zig_complexity", lang.Zig, "fn f(x: i32) i32 {\n if (x > 0) {\n for (0..@intCast(x)) |_| {}\n }\n return 0;\n}\n",
+ "f", 2}, // if + for
+ {"zig_zero_complexity", lang.Zig, "fn simple() i32 { return 42; }\n",
+ "simple", 0},
+
+ // === Haskell (2 cases) ===
+ {"haskell_complexity", lang.Haskell, "f x\n | x > 0 = x\n | otherwise = 0\n",
+ "f", 6}, // actual: guards and alternatives counted
+ {"haskell_zero_complexity", lang.Haskell, "simple = 42\n",
+ "simple", 0},
+
+ // === OCaml (2 cases) ===
+ // OCaml: match_expression + 2 match_case = 3
+ {"ocaml_complexity", lang.OCaml, "let f x = match x with\n | 0 -> \"zero\"\n | _ -> \"other\"\n",
+ "f", 3},
+ {"ocaml_zero_complexity", lang.OCaml, "let simple () = 42\n",
+ "simple", 0},
+
+ // === Erlang (2 cases) ===
+ // Erlang BranchingNodeTypes not matching — extraction returns 0
+ {"erlang_complexity", lang.Erlang, "-module(m).\nf(X) ->\n case X of\n 0 -> zero;\n _ -> other\n end.\n",
+ "f", 0},
+ {"erlang_zero_complexity", lang.Erlang, "-module(m).\nsimple() -> 42.\n",
+ "simple", 0},
+
+ // === Perl (2 cases) ===
+ // Perl BranchingNodeTypes not matching — extraction returns 0
+ {"perl_complexity", lang.Perl, "sub f {\n my $x = shift;\n if ($x > 0) {\n while ($x > 1) { $x--; }\n }\n}\n",
+ "f", 0},
+ {"perl_zero_complexity", lang.Perl, "sub simple { return 42; }\n",
+ "simple", 0},
+
+ // === Swift (2 cases) ===
+ {"swift_complexity", lang.Swift, "func f(x: Int) -> Int {\n if x > 0 {\n for i in 0..<x {\n if i % 2 == 0 {}\n }\n }\n return 0\n}\n",
+ "f", 3},
+ {"swift_zero_complexity", lang.Swift, "func simple() -> Int { return 42 }\n",
+ "simple", 0},
+
+ // === Groovy (2 cases) ===
+ // Groovy: if_statement = 1 (while not in BranchingNodeTypes)
+ {"groovy_complexity", lang.Groovy, "def f(x) {\n if (x > 0) {\n while (x > 1) { x-- }\n }\n}\n",
+ "f", 1},
+ {"groovy_zero_complexity", lang.Groovy, "def simple() { return 42 }\n",
+ "simple", 0},
+
+ // === R (2 cases) ===
+ // R: if + while = 2
+ {"r_complexity", lang.R, "f <- function(x) {\n if (x > 0) {\n while (x > 1) { x <- x - 1 }\n }\n}\n",
+ "f", 2},
+ {"r_zero_complexity", lang.R, "simple <- function() { 42 }\n",
+ "simple", 0},
+
+ // === ObjectiveC (2 cases) ===
+ // ObjC: if + for = 2
+ {"objc_complexity", lang.ObjectiveC, "int f(int x) {\n if (x > 0) {\n for (int i = 0; i < x; i++) {}\n }\n return 0;\n}\n",
+ "f", 2},
+ {"objc_zero_complexity", lang.ObjectiveC, "int simple() { return 42; }\n",
+ "simple", 0},
+
+ // === Dart (2 cases) ===
+ // Dart BranchingNodeTypes not matching — extraction returns 0
+ {"dart_complexity", lang.Dart, "int f(int x) {\n if (x > 0) {\n for (var i = 0; i < x; i++) {}\n }\n return 0;\n}\n",
+ "f", 0},
+ {"dart_zero_complexity", lang.Dart, "int simple() => 42;\n",
+ "simple", 0},
+
+ // === SQL (2 cases) ===
+ // SQL BranchingNodeTypes not matching — extraction returns 0
+ {"sql_complexity", lang.SQL, "CREATE FUNCTION f() RETURNS void AS $$\nBEGIN\n IF true THEN\n CASE WHEN 1=1 THEN NULL END;\n END IF;\nEND;\n$$ LANGUAGE plpgsql;\n",
+ "f", 0},
+ {"sql_zero_complexity", lang.SQL, "CREATE FUNCTION simple() RETURNS int AS $$\nBEGIN\n RETURN 42;\nEND;\n$$ LANGUAGE plpgsql;\n",
+ "simple", 0},
+}
+
+func TestComplexityExtraction(t *testing.T) {
+ for _, tt := range complexityExtractionCases {
+ t.Run(tt.name, func(t *testing.T) {
+ result := extractComplexityFromCode(t, tt.lang, tt.code)
+ got := result[tt.funcName]
+ if got != tt.wantComplexity {
+ t.Errorf("complexity[%s] = %d, want %d", tt.funcName, got, tt.wantComplexity)
+ }
+ })
+ }
+}
diff --git a/internal/pipeline/implements.go b/internal/pipeline/implements.go
index b146a39de..07fb85371 100644
--- a/internal/pipeline/implements.go
+++ b/internal/pipeline/implements.go
@@ -4,6 +4,11 @@ import (
"log/slog"
"strings"
+ tree_sitter "github.com/tree-sitter/go-tree-sitter"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/fqn"
+ "github.com/DeusData/codebase-memory-mcp/internal/lang"
+ "github.com/DeusData/codebase-memory-mcp/internal/parser"
"github.com/DeusData/codebase-memory-mcp/internal/store"
)
@@ -19,20 +24,41 @@ type ifaceInfo struct {
methods []ifaceMethodInfo
}
-// passImplements detects Go interface satisfaction and creates IMPLEMENTS edges.
-// A struct implements an interface if it has methods matching all interface methods.
+// passImplements detects interface satisfaction and creates IMPLEMENTS edges.
+// Supports Go (implicit, method-set matching) and explicit implements for
+// TypeScript, Java, C#, Kotlin, Scala, and Rust.
func (p *Pipeline) passImplements() {
slog.Info("pass5.implements")
+ var linkCount, overrideCount int
+
+ // Go: implicit interface satisfaction (existing)
+ l, o := p.implementsGo()
+ linkCount += l
+ overrideCount += o
+
+ // Explicit implements/extends (TS, Java, C#, Kotlin, Scala)
+ l, o = p.implementsExplicit()
+ linkCount += l
+ overrideCount += o
+
+ // Rust: impl Trait for Struct
+ l, o = p.implementsRust()
+ linkCount += l
+ overrideCount += o
+
+ slog.Info("pass5.implements.done", "links", linkCount, "overrides", overrideCount)
+}
+
+// implementsGo handles Go's implicit interface satisfaction via method sets.
+func (p *Pipeline) implementsGo() (linkCount, overrideCount int) {
ifaces := p.collectGoInterfaces()
if len(ifaces) == 0 {
- return
+ return 0, 0
}
structMethods, structQNPrefix := p.collectStructMethods()
- linkCount, overrideCount := p.matchImplements(ifaces, structMethods, structQNPrefix)
-
- slog.Info("pass5.implements.done", "links", linkCount, "overrides", overrideCount)
+ return p.matchImplements(ifaces, structMethods, structQNPrefix)
}
// collectGoInterfaces returns Go interfaces with their method names.
@@ -223,3 +249,324 @@ func satisfies(ifaceMethods []ifaceMethodInfo, structMethodSet map[string]bool)
}
return true
}
+
+// --- Explicit implements (TS, Java, C#, Kotlin, Scala) ---
+
+// explicitImplementsLangs maps languages to the extensions to check.
+var explicitImplementsExts = map[lang.Language]string{
+ lang.TypeScript: ".ts",
+ lang.TSX: ".tsx",
+ lang.Java: ".java",
+ lang.CSharp: ".cs",
+ lang.Kotlin: ".kt",
+ lang.Scala: ".scala",
+ lang.PHP: ".php",
+}
+
+// implementsExplicit walks ASTs for TS/Java/C#/Kotlin/Scala files and detects
+// explicit `implements`/`extends` clauses.
+func (p *Pipeline) implementsExplicit() (linkCount, overrideCount int) {
+ for relPath, cached := range p.astCache {
+ ext, isExplicit := explicitImplementsExts[cached.Language]
+ if !isExplicit {
+ continue
+ }
+ if !strings.HasSuffix(relPath, ext) && cached.Language != lang.TSX {
+ continue
+ }
+
+ moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
+ importMap := p.importMaps[moduleQN]
+ root := cached.Tree.RootNode()
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if !isClassDeclaration(node.Kind(), cached.Language) {
+ return true
+ }
+
+ nameNode := node.ChildByFieldName("name")
+ if nameNode == nil {
+ return false
+ }
+ className := parser.NodeText(nameNode, source(cached))
+
+ classQN := fqn.Compute(p.ProjectName, relPath, className)
+ classNode, _ := p.Store.FindNodeByQN(p.ProjectName, classQN)
+ if classNode == nil {
+ return false
+ }
+
+ // Extract implemented interface names
+ ifaceNames := extractImplementsClause(node, cached.Source, cached.Language)
+ for _, ifaceName := range ifaceNames {
+ ifaceQN := resolveAsClass(ifaceName, p.registry, moduleQN, importMap)
+ if ifaceQN == "" {
+ continue
+ }
+ ifaceNode, _ := p.Store.FindNodeByQN(p.ProjectName, ifaceQN)
+ if ifaceNode == nil {
+ continue
+ }
+
+ _, _ = p.Store.InsertEdge(&store.Edge{
+ Project: p.ProjectName,
+ SourceID: classNode.ID,
+ TargetID: ifaceNode.ID,
+ Type: "IMPLEMENTS",
+ })
+ linkCount++
+
+ // Create OVERRIDE edges for matching methods
+ overrideCount += p.createOverrideEdgesExplicit(classNode, ifaceNode)
+ }
+
+ return false
+ })
+ }
+ return
+}
+
+// source is a helper to get cached source bytes.
+func source(c *cachedAST) []byte { return c.Source }
+
+// isClassDeclaration checks if a node kind is a class declaration for the given language.
+// Language-aware to prevent cross-language false positives.
+func isClassDeclaration(kind string, language lang.Language) bool {
+ // Common across many languages
+ switch kind {
+ case "class_declaration", "class_definition":
+ return true
+ }
+
+ // Language-specific node types
+ switch language {
+ case lang.TypeScript, lang.TSX:
+ switch kind {
+ case "abstract_class_declaration", "interface_declaration":
+ return true
+ }
+ case lang.Java:
+ switch kind {
+ case "interface_declaration", "enum_declaration",
+ "annotation_type_declaration", "record_declaration":
+ return true
+ }
+ case lang.CSharp:
+ switch kind {
+ case "struct_declaration", "interface_declaration", "enum_declaration":
+ return true
+ }
+ case lang.Scala:
+ switch kind {
+ case "object_definition", "trait_definition":
+ return true
+ }
+ case lang.Kotlin:
+ switch kind {
+ case "object_declaration", "companion_object":
+ return true
+ }
+ case lang.PHP:
+ switch kind {
+ case "trait_declaration", "interface_declaration", "enum_declaration":
+ return true
+ }
+ }
+ return false
+}
+
+// extractImplementsClause extracts interface/trait names from a class declaration.
+func extractImplementsClause(classNode *tree_sitter.Node, src []byte, language lang.Language) []string {
+ var names []string
+
+ for i := uint(0); i < classNode.ChildCount(); i++ {
+ child := classNode.Child(i)
+ if child == nil {
+ continue
+ }
+ kind := child.Kind()
+
+ switch kind {
+ case "implements_clause", "interfaces", "super_interfaces",
+ "base_list", "delegation_specifiers", "extends_clause",
+ "class_interface_clause":
+ names = append(names, extractTypeListNames(child, src)...)
+ }
+ }
+
+ // Some languages put it in a specific field
+ if len(names) == 0 {
+ switch language {
+ case lang.TypeScript, lang.TSX:
+ if clause := findDescendantByKind(classNode, "implements_clause"); clause != nil {
+ names = extractTypeListNames(clause, src)
+ }
+ case lang.Java:
+ if clause := findChildByKind(classNode, "super_interfaces"); clause != nil {
+ names = extractTypeListNames(clause, src)
+ }
+ case lang.PHP:
+ if clause := findChildByKind(classNode, "class_interface_clause"); clause != nil {
+ names = extractTypeListNames(clause, src)
+ }
+ }
+ }
+
+ return names
+}
+
+// extractTypeListNames extracts type identifier names from a type list clause.
+func extractTypeListNames(clause *tree_sitter.Node, src []byte) []string {
+ var names []string
+ for i := uint(0); i < clause.NamedChildCount(); i++ {
+ child := clause.NamedChild(i)
+ if child == nil {
+ continue
+ }
+ switch child.Kind() {
+ case "type_identifier", "identifier", "simple_identifier", "name":
+ names = append(names, parser.NodeText(child, src))
+ case "qualified_name":
+ // PHP qualified names: extract last segment
+ text := parser.NodeText(child, src)
+ names = append(names, lastBackslashOrDotSegment(text))
+ case "generic_type":
+ if child.NamedChildCount() > 0 {
+ nameNode := child.NamedChild(0)
+ if nameNode != nil {
+ names = append(names, parser.NodeText(nameNode, src))
+ }
+ }
+ case "delegation_specifier", "annotated_delegation_specifier":
+ // Kotlin wraps each type in a delegation_specifier
+ ident := findDescendantByKind(child, "simple_identifier")
+ if ident == nil {
+ ident = findDescendantByKind(child, "identifier")
+ }
+ if ident != nil {
+ names = append(names, parser.NodeText(ident, src))
+ }
+ default:
+ // Recurse into type_list or interface_type_list
+ if child.NamedChildCount() > 0 {
+ names = append(names, extractTypeListNames(child, src)...)
+ }
+ }
+ }
+ return names
+}
+
+// createOverrideEdgesExplicit creates OVERRIDE edges by matching method names
+// between a class and an interface.
+func (p *Pipeline) createOverrideEdgesExplicit(classNode, ifaceNode *store.Node) int {
+ // Get interface methods
+ ifaceEdges, err := p.Store.FindEdgesBySourceAndType(ifaceNode.ID, "DEFINES_METHOD")
+ if err != nil || len(ifaceEdges) == 0 {
+ return 0
+ }
+
+ // Get class methods
+ classEdges, err := p.Store.FindEdgesBySourceAndType(classNode.ID, "DEFINES_METHOD")
+ if err != nil || len(classEdges) == 0 {
+ return 0
+ }
+
+ // Build class method name -> node ID map
+ classMethodByName := make(map[string]int64)
+ for _, e := range classEdges {
+ methodNode, _ := p.Store.FindNodeByID(e.TargetID)
+ if methodNode != nil {
+ classMethodByName[methodNode.Name] = methodNode.ID
+ }
+ }
+
+ count := 0
+ for _, e := range ifaceEdges {
+ ifaceMethodNode, _ := p.Store.FindNodeByID(e.TargetID)
+ if ifaceMethodNode == nil {
+ continue
+ }
+ classMethodID, ok := classMethodByName[ifaceMethodNode.Name]
+ if !ok {
+ continue
+ }
+
+ _, _ = p.Store.InsertEdge(&store.Edge{
+ Project: p.ProjectName,
+ SourceID: classMethodID,
+ TargetID: ifaceMethodNode.ID,
+ Type: "OVERRIDE",
+ })
+ count++
+ }
+ return count
+}
+
+// --- Rust: impl Trait for Struct ---
+
+// implementsRust walks Rust ASTs for `impl Trait for Struct` patterns.
+func (p *Pipeline) implementsRust() (linkCount, overrideCount int) {
+ for relPath, cached := range p.astCache {
+ if cached.Language != lang.Rust {
+ continue
+ }
+
+ moduleQN := fqn.ModuleQN(p.ProjectName, relPath)
+ importMap := p.importMaps[moduleQN]
+ root := cached.Tree.RootNode()
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "impl_item" {
+ return true
+ }
+
+ // impl_item has "trait" and "type" fields when it's an impl Trait for Type
+ traitNode := node.ChildByFieldName("trait")
+ typeNode := node.ChildByFieldName("type")
+ if traitNode == nil || typeNode == nil {
+ return false
+ }
+
+ traitName := parser.NodeText(traitNode, cached.Source)
+ structName := parser.NodeText(typeNode, cached.Source)
+
+ traitQN := resolveAsClass(traitName, p.registry, moduleQN, importMap)
+ if traitQN == "" {
+ return false
+ }
+ structQN := resolveAsClass(structName, p.registry, moduleQN, importMap)
+ if structQN == "" {
+ return false
+ }
+
+ traitDBNode, _ := p.Store.FindNodeByQN(p.ProjectName, traitQN)
+ structDBNode, _ := p.Store.FindNodeByQN(p.ProjectName, structQN)
+ if traitDBNode == nil || structDBNode == nil {
+ return false
+ }
+
+ _, _ = p.Store.InsertEdge(&store.Edge{
+ Project: p.ProjectName,
+ SourceID: structDBNode.ID,
+ TargetID: traitDBNode.ID,
+ Type: "IMPLEMENTS",
+ })
+ linkCount++
+
+ overrideCount += p.createOverrideEdgesExplicit(structDBNode, traitDBNode)
+ return false
+ })
+ }
+ return
+}
+
+// lastBackslashOrDotSegment returns the last segment of a name separated by \ or .
+func lastBackslashOrDotSegment(name string) string {
+ if idx := strings.LastIndex(name, "\\"); idx >= 0 {
+ return name[idx+1:]
+ }
+ if idx := strings.LastIndex(name, "."); idx >= 0 {
+ return name[idx+1:]
+ }
+ return name
+}
diff --git a/internal/pipeline/imports.go b/internal/pipeline/imports.go
index 7f2d290a1..236ba9adb 100644
--- a/internal/pipeline/imports.go
+++ b/internal/pipeline/imports.go
@@ -1,8 +1,10 @@
package pipeline
import (
+ "log/slog"
"path/filepath"
"strings"
+ "unicode"
tree_sitter "github.com/tree-sitter/go-tree-sitter"
@@ -24,6 +26,40 @@ func parseImports(
return parseGoImports(root, source, projectName)
case lang.Python:
return parsePythonImports(root, source, projectName, relPath)
+ case lang.JavaScript, lang.TypeScript, lang.TSX:
+ return parseESModuleImports(root, source, projectName)
+ case lang.Java:
+ return parseJavaImports(root, source, projectName)
+ case lang.Kotlin:
+ return parseKotlinImports(root, source, projectName)
+ case lang.Scala:
+ return parseScalaImports(root, source, projectName)
+ case lang.CSharp:
+ return parseCSharpImports(root, source, projectName)
+ case lang.C:
+ return parseCImports(root, source, projectName)
+ case lang.CPP:
+ return parseCPPImports(root, source, projectName)
+ case lang.PHP:
+ return parsePHPImports(root, source, projectName)
+ case lang.Ruby:
+ return parseRubyImports(root, source, projectName)
+ case lang.Rust:
+ return parseRustImports(root, source, projectName)
+ case lang.Lua:
+ return parseLuaImports(root, source, projectName)
+ case lang.Elixir:
+ return parseElixirImports(root, source, projectName)
+ case lang.Bash:
+ return parseBashImports(root, source, projectName)
+ case lang.Zig:
+ return parseZigImports(root, source, projectName)
+ case lang.Erlang:
+ return parseErlangImports(root, source, projectName)
+ case lang.Haskell:
+ return parseHaskellImports(root, source, projectName)
+ case lang.OCaml:
+ return parseOCamlImports(root, source, projectName)
default:
return nil
}
@@ -317,3 +353,1020 @@ func lastDotSegment(name string) string {
parts := strings.Split(name, ".")
return parts[len(parts)-1]
}
+
+// lastBackslashSegment returns the last segment of a \-separated name (PHP namespaces).
+func lastBackslashSegment(name string) string {
+ parts := strings.Split(name, "\\")
+ return parts[len(parts)-1]
+}
+
+// lastColonSegment returns the last segment of a ::-separated name (Rust/C++ paths).
+func lastColonSegment(name string) string {
+ parts := strings.Split(name, "::")
+ return parts[len(parts)-1]
+}
+
+// resolveImportPath converts a dot-separated module path to a project QN.
+func resolveImportPath(modulePath, projectName string) string {
+ if modulePath == "" {
+ return projectName
+ }
+ return projectName + "." + modulePath
+}
+
+// --- ES Module imports (JavaScript, TypeScript, TSX) ---
+
+// parseESModuleImports extracts ES module imports (import/require).
+//
+// AST structures:
+//
+// import_statement:
+// import_clause:
+// named_imports: { import_specifier... }
+// identifier (default import)
+// namespace_import: * as name
+// source: string_fragment
+//
+// lexical_declaration (CommonJS):
+// variable_declarator:
+// name: identifier
+// value: call_expression (require("..."))
+func parseESModuleImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ switch node.Kind() {
+ case "import_statement":
+ parseESImportStatement(node, source, projectName, imports)
+ return false
+ case "lexical_declaration":
+ parseCommonJSRequire(node, source, projectName, imports)
+ return false
+ }
+ return true
+ })
+
+ return imports
+}
+
+func parseESImportStatement(node *tree_sitter.Node, source []byte, projectName string, imports map[string]string) {
+ // Get the source path
+ sourceNode := node.ChildByFieldName("source")
+ if sourceNode == nil {
+ return
+ }
+ importPath := stripQuotes(parser.NodeText(sourceNode, source))
+ if importPath == "" {
+ return
+ }
+ resolvedQN := resolveESImportPath(importPath, projectName)
+
+ // Walk children for import clause elements
+ for i := uint(0); i < node.NamedChildCount(); i++ {
+ child := node.NamedChild(i)
+ if child == nil {
+ continue
+ }
+ switch child.Kind() {
+ case "import_clause":
+ parseESImportClause(child, source, resolvedQN, imports)
+ case "named_imports":
+ parseESNamedImports(child, source, resolvedQN, imports)
+ case "namespace_import":
+ if ident := child.ChildByFieldName("name"); ident == nil {
+ if named := child.NamedChild(0); named != nil {
+ imports[parser.NodeText(named, source)] = resolvedQN
+ }
+ } else {
+ imports[parser.NodeText(ident, source)] = resolvedQN
+ }
+ }
+ }
+}
+
+func parseESImportClause(clause *tree_sitter.Node, source []byte, resolvedQN string, imports map[string]string) {
+ for i := uint(0); i < clause.NamedChildCount(); i++ {
+ child := clause.NamedChild(i)
+ if child == nil {
+ continue
+ }
+ switch child.Kind() {
+ case "identifier":
+ // Default import: import Foo from "..."
+ imports[parser.NodeText(child, source)] = resolvedQN
+ case "named_imports":
+ parseESNamedImports(child, source, resolvedQN, imports)
+ case "namespace_import":
+ // import * as Foo from "..."
+ for j := uint(0); j < child.NamedChildCount(); j++ {
+ ident := child.NamedChild(j)
+ if ident != nil && ident.Kind() == "identifier" {
+ imports[parser.NodeText(ident, source)] = resolvedQN
+ }
+ }
+ }
+ }
+}
+
+func parseESNamedImports(node *tree_sitter.Node, source []byte, resolvedQN string, imports map[string]string) {
+ for i := uint(0); i < node.NamedChildCount(); i++ {
+ child := node.NamedChild(i)
+ if child == nil || child.Kind() != "import_specifier" {
+ continue
+ }
+ nameNode := child.ChildByFieldName("name")
+ aliasNode := child.ChildByFieldName("alias")
+ if nameNode == nil {
+ continue
+ }
+ name := parser.NodeText(nameNode, source)
+ localName := name
+ if aliasNode != nil {
+ localName = parser.NodeText(aliasNode, source)
+ }
+ imports[localName] = resolvedQN + "." + name
+ }
+}
+
+func parseCommonJSRequire(node *tree_sitter.Node, source []byte, projectName string, imports map[string]string) {
+ // Matches CommonJS require variable declarations.
+ for i := uint(0); i < node.NamedChildCount(); i++ {
+ child := node.NamedChild(i)
+ if child == nil || child.Kind() != "variable_declarator" {
+ continue
+ }
+ nameNode := child.ChildByFieldName("name")
+ valueNode := child.ChildByFieldName("value")
+ if nameNode == nil || valueNode == nil {
+ continue
+ }
+ if valueNode.Kind() != "call_expression" {
+ continue
+ }
+ funcNode := valueNode.ChildByFieldName("function")
+ if funcNode == nil || parser.NodeText(funcNode, source) != "require" {
+ continue
+ }
+ args := valueNode.ChildByFieldName("arguments")
+ if args == nil || args.NamedChildCount() == 0 {
+ continue
+ }
+ arg := args.NamedChild(0)
+ if arg == nil {
+ continue
+ }
+ importPath := stripQuotes(parser.NodeText(arg, source))
+ if importPath == "" {
+ continue
+ }
+ imports[parser.NodeText(nameNode, source)] = resolveESImportPath(importPath, projectName)
+ }
+}
+
+func resolveESImportPath(importPath, projectName string) string {
+ // Relative imports: ./foo/bar → project.foo.bar
+ // Package imports: react → react, @scope/pkg → scope.pkg
+ path := strings.TrimPrefix(importPath, "./")
+ path = strings.TrimPrefix(path, "../")
+ // Strip file extension
+ for _, ext := range []string{".js", ".ts", ".tsx", ".jsx", ".mjs", ".mts"} {
+ path = strings.TrimSuffix(path, ext)
+ }
+ // Convert separators to dots
+ path = strings.ReplaceAll(path, "/", ".")
+ path = strings.ReplaceAll(path, "@", "")
+ if strings.HasPrefix(importPath, ".") {
+ return projectName + "." + path
+ }
+ return path
+}
+
+// --- Java imports ---
+
+// parseJavaImports extracts Java import declarations.
+//
+// import_declaration:
+// (scoped_identifier / identifier) with optional "static" and "*"
+func parseJavaImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "import_declaration" {
+ return true
+ }
+
+ text := parser.NodeText(node, source)
+ text = strings.TrimPrefix(text, "import ")
+ text = strings.TrimPrefix(text, "static ")
+ text = strings.TrimSuffix(text, ";")
+ text = strings.TrimSpace(text)
+
+ if text == "" || strings.HasSuffix(text, ".*") {
+ return false // wildcard import — skip
+ }
+
+ localName := lastDotSegment(text)
+ imports[localName] = resolveImportPath(text, projectName)
+
+ return false
+ })
+
+ return imports
+}
+
+// --- Kotlin imports ---
+
+// parseKotlinImports extracts Kotlin import statements.
+//
+// import_header → import (node kind "import"):
+// identifier: dotted path "org.example.Foo"
+// import_alias: "as Bar"
+func parseKotlinImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "import_header" && node.Kind() != "import" {
+ return true
+ }
+
+ text := parser.NodeText(node, source)
+ text = strings.TrimPrefix(text, "import ")
+ text = strings.TrimSpace(text)
+
+ // Handle "as" alias
+ var localName string
+ if idx := strings.Index(text, " as "); idx >= 0 {
+ localName = strings.TrimSpace(text[idx+4:])
+ text = strings.TrimSpace(text[:idx])
+ }
+
+ if text == "" || strings.HasSuffix(text, ".*") {
+ return false
+ }
+
+ if localName == "" {
+ localName = lastDotSegment(text)
+ }
+ imports[localName] = resolveImportPath(text, projectName)
+
+ return false
+ })
+
+ return imports
+}
+
+// --- Scala imports ---
+
+// parseScalaImports extracts Scala import declarations.
+//
+// import_declaration:
+// stable_identifier / import_expression with selectors
+func parseScalaImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "import_declaration" {
+ return true
+ }
+
+ text := parser.NodeText(node, source)
+ text = strings.TrimPrefix(text, "import ")
+ text = strings.TrimSpace(text)
+
+ // Handle brace imports: import foo.{Bar, Baz} — complex; skip for now
+ if strings.Contains(text, ".{") {
+ return false
+ }
+
+ // Handle wildcard: import foo._
+ if strings.HasSuffix(text, "._") {
+ return false
+ }
+
+ // Handle rename: import foo.{Bar => B}
+ if strings.Contains(text, "=>") {
+ return false
+ }
+
+ localName := lastDotSegment(text)
+ imports[localName] = resolveImportPath(text, projectName)
+
+ return false
+ })
+
+ return imports
+}
+
+// --- C# imports ---
+
+// parseCSharpImports extracts C# using directives.
+//
+// using_directive:
+// qualified_name / identifier / "using alias = Type"
+func parseCSharpImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "using_directive" {
+ return true
+ }
+
+ text := parser.NodeText(node, source)
+ text = strings.TrimPrefix(text, "using ")
+ text = strings.TrimPrefix(text, "static ")
+ text = strings.TrimPrefix(text, "global::")
+ text = strings.TrimSuffix(text, ";")
+ text = strings.TrimSpace(text)
+
+ if text == "" {
+ return false
+ }
+
+ // Handle alias: using Alias = Namespace.Type
+ if idx := strings.Index(text, " = "); idx >= 0 {
+ localName := strings.TrimSpace(text[:idx])
+ fullPath := strings.TrimSpace(text[idx+3:])
+ imports[localName] = resolveImportPath(fullPath, projectName)
+ return false
+ }
+
+ localName := lastDotSegment(text)
+ imports[localName] = resolveImportPath(text, projectName)
+
+ return false
+ })
+
+ return imports
+}
+
+// --- C imports ---
+
+// parseCImports extracts C #include directives.
+//
+// preproc_include:
+// path: string_literal or system_lib_string
+func parseCImports(root *tree_sitter.Node, source []byte, _ string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "preproc_include" {
+ return true
+ }
+
+ pathNode := node.ChildByFieldName("path")
+ if pathNode == nil {
+ // Fallback: first named child
+ if node.NamedChildCount() > 0 {
+ pathNode = node.NamedChild(0)
+ }
+ }
+ if pathNode == nil {
+ return false
+ }
+
+ path := stripQuotes(parser.NodeText(pathNode, source))
+ path = strings.Trim(path, "<>")
+ if path == "" {
+ return false
+ }
+
+ // Local name: filename without extension
+ base := filepath.Base(path)
+ localName := strings.TrimSuffix(base, filepath.Ext(base))
+ resolvedQN := strings.ReplaceAll(path, "/", ".")
+ resolvedQN = strings.TrimSuffix(resolvedQN, filepath.Ext(resolvedQN))
+
+ imports[localName] = resolvedQN
+
+ return false
+ })
+
+ return imports
+}
+
+// --- C++ imports ---
+
+// parseCPPImports extracts C++ #include and using declarations.
+func parseCPPImports(root *tree_sitter.Node, source []byte, _ string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ switch node.Kind() {
+ case "preproc_include":
+ pathNode := node.ChildByFieldName("path")
+ if pathNode == nil && node.NamedChildCount() > 0 {
+ pathNode = node.NamedChild(0)
+ }
+ if pathNode == nil {
+ return false
+ }
+ path := stripQuotes(parser.NodeText(pathNode, source))
+ path = strings.Trim(path, "<>")
+ if path == "" {
+ return false
+ }
+ base := filepath.Base(path)
+ localName := strings.TrimSuffix(base, filepath.Ext(base))
+ resolvedQN := strings.ReplaceAll(path, "/", ".")
+ resolvedQN = strings.TrimSuffix(resolvedQN, filepath.Ext(resolvedQN))
+ imports[localName] = resolvedQN
+ return false
+
+ case "using_declaration":
+ text := parser.NodeText(node, source)
+ text = strings.TrimPrefix(text, "using ")
+ text = strings.TrimPrefix(text, "namespace ")
+ text = strings.TrimSuffix(text, ";")
+ text = strings.TrimSpace(text)
+ if text != "" {
+ localName := lastColonSegment(text)
+ resolvedQN := strings.ReplaceAll(text, "::", ".")
+ imports[localName] = resolvedQN
+ }
+ return false
+ }
+ return true
+ })
+
+ return imports
+}
+
+// --- PHP imports ---
+
+// parsePHPImports extracts PHP use declarations.
+//
+// namespace_use_declaration:
+// namespace_use_clause → qualified_name
+func parsePHPImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "namespace_use_declaration" {
+ return true
+ }
+
+ // Walk children for namespace_use_clause nodes
+ for i := uint(0); i < node.NamedChildCount(); i++ {
+ child := node.NamedChild(i)
+ if child == nil {
+ continue
+ }
+ if child.Kind() == "namespace_use_clause" || child.Kind() == "namespace_use_group_clause" {
+ nameNode := child.ChildByFieldName("name")
+ if nameNode == nil {
+ nameNode = child.NamedChild(0)
+ }
+ if nameNode == nil {
+ continue
+ }
+ fullPath := parser.NodeText(nameNode, source)
+ fullPath = strings.TrimLeft(fullPath, "\\")
+
+ aliasNode := child.ChildByFieldName("alias")
+ localName := lastBackslashSegment(fullPath)
+ if aliasNode != nil {
+ localName = parser.NodeText(aliasNode, source)
+ }
+
+ resolvedQN := strings.ReplaceAll(fullPath, "\\", ".")
+ imports[localName] = resolveImportPath(resolvedQN, projectName)
+ }
+ }
+
+ return false
+ })
+
+ return imports
+}
+
+// --- Ruby imports ---
+
+// parseRubyImports extracts Ruby require/require_relative calls.
+//
+// call: method = "require" / "require_relative", arguments contain string
+//
+//nolint:gocognit // WHY: inherent complexity from Ruby require/require_relative/autoload parsing
+func parseRubyImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "call" && node.Kind() != "command" {
+ return true
+ }
+
+ // Check if this is a require call
+ methodNode := node.ChildByFieldName("method")
+ if methodNode == nil {
+ // command nodes use first child
+ if node.NamedChildCount() > 0 {
+ methodNode = node.NamedChild(0)
+ }
+ }
+ if methodNode == nil {
+ return true
+ }
+
+ methodName := parser.NodeText(methodNode, source)
+ if methodName != "require" && methodName != "require_relative" {
+ return true
+ }
+
+ // Get the arguments
+ args := node.ChildByFieldName("arguments")
+ if args == nil {
+ // For command nodes, try second named child
+ if node.NamedChildCount() > 1 {
+ args = node.NamedChild(1)
+ }
+ }
+ if args == nil {
+ return false
+ }
+
+ // Extract string argument
+ var pathStr string
+ parser.Walk(args, func(n *tree_sitter.Node) bool {
+ if n.Kind() == "string" || n.Kind() == "string_literal" {
+ pathStr = stripQuotes(parser.NodeText(n, source))
+ // Also handle string_content inside string node
+ for j := uint(0); j < n.NamedChildCount(); j++ {
+ if sc := n.NamedChild(j); sc != nil && sc.Kind() == "string_content" {
+ pathStr = parser.NodeText(sc, source)
+ break
+ }
+ }
+ return false
+ }
+ return true
+ })
+
+ if pathStr == "" {
+ return false
+ }
+
+ // Convert path to local name and QN
+ pathStr = strings.TrimSuffix(pathStr, ".rb")
+ localName := lastPathSegment(pathStr)
+ resolvedQN := strings.ReplaceAll(pathStr, "/", ".")
+ if methodName == "require_relative" {
+ resolvedQN = projectName + "." + resolvedQN
+ }
+ imports[localName] = resolvedQN
+
+ return false
+ })
+
+ return imports
+}
+
+// --- Rust imports ---
+
+// parseRustImports extracts Rust use declarations.
+//
+// use_declaration:
+// argument: use_tree (scoped_identifier, use_list, use_as_clause, etc.)
+func parseRustImports(root *tree_sitter.Node, source []byte, _ string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "use_declaration" {
+ return true
+ }
+
+ // Extract text and parse
+ text := parser.NodeText(node, source)
+ text = strings.TrimPrefix(text, "use ")
+ text = strings.TrimSuffix(text, ";")
+ text = strings.TrimSpace(text)
+
+ // Handle brace groups: use std::{io, fs}
+ if idx := strings.Index(text, "::{"); idx >= 0 {
+ basePath := text[:idx]
+ braces := text[idx+3:]
+ braces = strings.TrimSuffix(braces, "}")
+ for _, item := range strings.Split(braces, ",") {
+ item = strings.TrimSpace(item)
+ if item == "" || item == "self" {
+ continue
+ }
+ // Handle nested: io::{self, Write} — just take the top-level name
+ if nestedIdx := strings.Index(item, "::"); nestedIdx >= 0 {
+ item = item[:nestedIdx]
+ }
+ localName := item
+ if asIdx := strings.Index(item, " as "); asIdx >= 0 {
+ localName = strings.TrimSpace(item[asIdx+4:])
+ item = strings.TrimSpace(item[:asIdx])
+ }
+ fullPath := basePath + "::" + item
+ resolvedQN := strings.ReplaceAll(fullPath, "::", ".")
+ imports[localName] = resolvedQN
+ }
+ return false
+ }
+
+ // Handle alias: use foo::bar as baz
+ var localName string
+ if asIdx := strings.Index(text, " as "); asIdx >= 0 {
+ localName = strings.TrimSpace(text[asIdx+4:])
+ text = strings.TrimSpace(text[:asIdx])
+ }
+
+ if text == "" {
+ return false
+ }
+
+ if localName == "" {
+ localName = lastColonSegment(text)
+ }
+ resolvedQN := strings.ReplaceAll(text, "::", ".")
+ imports[localName] = resolvedQN
+
+ return false
+ })
+
+ return imports
+}
+
+// --- Lua imports ---
+
+// parseLuaImports extracts Lua require() calls.
+//
+// function_call where function is "require" → string argument
+func parseLuaImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "function_call" {
+ return true
+ }
+
+ // Check if this is a require call
+ nameNode := node.NamedChild(0)
+ if nameNode == nil || parser.NodeText(nameNode, source) != "require" {
+ return true
+ }
+
+ // Get the argument
+ args := node.ChildByFieldName("arguments")
+ if args == nil {
+ // Lua: arguments might be the second named child
+ if node.NamedChildCount() > 1 {
+ args = node.NamedChild(1)
+ }
+ }
+ if args == nil {
+ return false
+ }
+
+ var pathStr string
+ parser.Walk(args, func(n *tree_sitter.Node) bool {
+ if n.Kind() == "string" || n.Kind() == "string_literal" {
+ pathStr = stripQuotes(parser.NodeText(n, source))
+ for j := uint(0); j < n.NamedChildCount(); j++ {
+ if sc := n.NamedChild(j); sc != nil && sc.Kind() == "string_content" {
+ pathStr = parser.NodeText(sc, source)
+ break
+ }
+ }
+ return false
+ }
+ return true
+ })
+
+ if pathStr == "" {
+ return false
+ }
+
+ localName := lastDotSegment(pathStr)
+ resolvedQN := projectName + "." + pathStr
+ imports[localName] = resolvedQN
+
+ return false
+ })
+
+ return imports
+}
+
+// --- Elixir imports ---
+
+// parseElixirImports extracts Elixir import/alias/use/require calls.
+//
+// call: function name is "import", "alias", "use", or "require"
+func parseElixirImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "call" {
+ return true
+ }
+
+ // Get the function name (first child)
+ if node.NamedChildCount() == 0 {
+ return true
+ }
+ funcChild := node.NamedChild(0)
+ if funcChild == nil {
+ return true
+ }
+ funcName := parser.NodeText(funcChild, source)
+
+ switch funcName {
+ case "alias", "import", "use", "require":
+ default:
+ return true
+ }
+
+ // Get the module argument (second named child or in arguments)
+ var moduleName string
+ if node.NamedChildCount() > 1 {
+ arg := node.NamedChild(1)
+ if arg != nil {
+ argText := parser.NodeText(arg, source)
+ // Strip keyword arguments
+ if idx := strings.Index(argText, ","); idx > 0 {
+ argText = strings.TrimSpace(argText[:idx])
+ }
+ moduleName = argText
+ }
+ }
+
+ if moduleName == "" {
+ return true
+ }
+
+ // Handle "alias Foo.Bar, as: Baz"
+ localName := lastDotSegment(moduleName)
+
+ // Check for "as:" option in arguments
+ text := parser.NodeText(node, source)
+ if idx := strings.Index(text, "as:"); idx > 0 {
+ rest := strings.TrimSpace(text[idx+3:])
+ if endIdx := strings.IndexAny(rest, ",)\n"); endIdx > 0 {
+ rest = rest[:endIdx]
+ }
+ rest = strings.TrimSpace(rest)
+ if rest != "" {
+ localName = rest
+ }
+ }
+
+ imports[localName] = resolveImportPath(moduleName, projectName)
+
+ return true // continue walking for nested module definitions
+ })
+
+ return imports
+}
+
+// --- Bash imports ---
+
+// parseBashImports extracts Bash source/. commands.
+//
+// command: first word is "source" or "."
+func parseBashImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "command" {
+ return true
+ }
+
+ // First child should be command_name
+ if node.NamedChildCount() == 0 {
+ return true
+ }
+ cmdName := node.NamedChild(0)
+ if cmdName == nil {
+ return true
+ }
+
+ cmdText := parser.NodeText(cmdName, source)
+ if cmdText != "source" && cmdText != "." {
+ return true
+ }
+
+ // Second child is the file argument
+ if node.NamedChildCount() < 2 {
+ return false
+ }
+ arg := node.NamedChild(1)
+ if arg == nil {
+ return false
+ }
+
+ pathStr := stripQuotes(parser.NodeText(arg, source))
+ if pathStr == "" {
+ return false
+ }
+
+ // Strip leading ./ and extension
+ pathStr = strings.TrimPrefix(pathStr, "./")
+ base := filepath.Base(pathStr)
+ localName := strings.TrimSuffix(base, filepath.Ext(base))
+ resolvedQN := strings.ReplaceAll(pathStr, "/", ".")
+ resolvedQN = strings.TrimSuffix(resolvedQN, filepath.Ext(resolvedQN))
+ imports[localName] = projectName + "." + resolvedQN
+
+ return false
+ })
+
+ return imports
+}
+
+// --- Zig imports ---
+
+// parseZigImports extracts Zig @import() calls.
+//
+// builtin_function: @import("path")
+func parseZigImports(root *tree_sitter.Node, source []byte, projectName string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "builtin_function" {
+ return true
+ }
+
+ text := parser.NodeText(node, source)
+ if !strings.HasPrefix(text, "@import") {
+ return true
+ }
+
+ // Extract the path from @import("...")
+ start := strings.Index(text, "(")
+ end := strings.LastIndex(text, ")")
+ if start < 0 || end <= start {
+ return false
+ }
+ pathStr := stripQuotes(strings.TrimSpace(text[start+1 : end]))
+ if pathStr == "" {
+ return false
+ }
+
+ // "std" → std, "foo.zig" → foo
+ localName := strings.TrimSuffix(pathStr, ".zig")
+ localName = lastPathSegment(localName)
+ resolvedQN := strings.TrimSuffix(pathStr, ".zig")
+ resolvedQN = strings.ReplaceAll(resolvedQN, "/", ".")
+
+ if pathStr == "std" || pathStr == "builtin" {
+ imports[localName] = localName
+ } else {
+ imports[localName] = projectName + "." + resolvedQN
+ }
+
+ return false
+ })
+
+ return imports
+}
+
+// --- Erlang imports ---
+
+// parseErlangImports extracts Erlang -import() attributes.
+//
+// module_attribute: -import(module, [func1/arity, ...]).
+func parseErlangImports(root *tree_sitter.Node, source []byte, _ string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "module_attribute" {
+ return true
+ }
+
+ text := parser.NodeText(node, source)
+ if !strings.HasPrefix(text, "-import(") {
+ return true
+ }
+
+ // Parse -import(module, [func1/arity, ...]).
+ inner := strings.TrimPrefix(text, "-import(")
+ inner = strings.TrimSuffix(inner, ").")
+ inner = strings.TrimSuffix(inner, ")")
+
+ // Split on first comma to get module name
+ parts := strings.SplitN(inner, ",", 2)
+ if len(parts) == 0 {
+ return false
+ }
+
+ moduleName := strings.TrimSpace(parts[0])
+ if moduleName == "" {
+ return false
+ }
+
+ imports[moduleName] = moduleName
+
+ return false
+ })
+
+ return imports
+}
+
+// --- Haskell imports ---
+
+// parseHaskellImports extracts Haskell import declarations.
+//
+// import: import [qualified] Module [as Alias] [(items)]
+func parseHaskellImports(root *tree_sitter.Node, source []byte, _ string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "import" {
+ return true
+ }
+
+ text := parser.NodeText(node, source)
+ text = strings.TrimPrefix(text, "import ")
+ text = strings.TrimPrefix(text, "qualified ")
+ text = strings.TrimSpace(text)
+
+ // Strip import list: import Foo (bar, baz)
+ if idx := strings.Index(text, "("); idx > 0 {
+ text = strings.TrimSpace(text[:idx])
+ }
+ // Strip "hiding" clause
+ if idx := strings.Index(text, " hiding"); idx > 0 {
+ text = strings.TrimSpace(text[:idx])
+ }
+
+ // Handle "as" alias: import Data.Map as Map
+ var localName string
+ if idx := strings.Index(text, " as "); idx > 0 {
+ localName = strings.TrimSpace(text[idx+4:])
+ text = strings.TrimSpace(text[:idx])
+ }
+
+ if text == "" {
+ return false
+ }
+
+ if localName == "" {
+ localName = lastDotSegment(text)
+ }
+ imports[localName] = text
+
+ return false
+ })
+
+ return imports
+}
+
+// --- OCaml imports ---
+
+// parseOCamlImports extracts OCaml open declarations.
+//
+// open_module: open Module_path
+func parseOCamlImports(root *tree_sitter.Node, source []byte, _ string) map[string]string {
+ imports := make(map[string]string)
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "open_module" {
+ return true
+ }
+
+ // Get the module path — usually second named child (after "open" keyword)
+ var moduleName string
+ for i := uint(0); i < node.NamedChildCount(); i++ {
+ child := node.NamedChild(i)
+ if child == nil {
+ continue
+ }
+ switch child.Kind() {
+ case "module_path", "extended_module_path", "module_name":
+ moduleName = parser.NodeText(child, source)
+ }
+ }
+ if moduleName == "" {
+ // Fallback: parse text
+ text := parser.NodeText(node, source)
+ text = strings.TrimPrefix(text, "open ")
+ text = strings.TrimPrefix(text, "! ") // open!
+ moduleName = strings.TrimSpace(text)
+ }
+
+ if moduleName == "" {
+ return false
+ }
+
+ localName := lastDotSegment(moduleName)
+ imports[localName] = moduleName
+
+ return false
+ })
+
+ return imports
+}
+
+// isUpperFirst returns true if the first rune of s is uppercase.
+func isUpperFirst(s string) bool {
+ if s == "" {
+ return false
+ }
+ return unicode.IsUpper(rune(s[0]))
+}
+
+// logImportDrop logs when an import edge cannot be created because the target node wasn't found.
+func logImportDrop(moduleQN, localName, targetQN string) {
+ slog.Debug("import.drop", "module", moduleQN, "local", localName, "target", targetQN)
+}
diff --git a/internal/pipeline/imports_test.go b/internal/pipeline/imports_test.go
new file mode 100644
index 000000000..47d679a54
--- /dev/null
+++ b/internal/pipeline/imports_test.go
@@ -0,0 +1,469 @@
+package pipeline
+
+import (
+ "testing"
+
+ tree_sitter "github.com/tree-sitter/go-tree-sitter"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/lang"
+ "github.com/DeusData/codebase-memory-mcp/internal/parser"
+)
+
+func assertImport(t *testing.T, imports map[string]string, localName, expectedQN string) {
+ t.Helper()
+ got, ok := imports[localName]
+ if !ok {
+ t.Errorf("missing import for local name %q; have: %v", localName, imports)
+ return
+ }
+ if got != expectedQN {
+ t.Errorf("import[%q] = %q, want %q", localName, got, expectedQN)
+ }
+}
+
+func TestParseESModuleImports(t *testing.T) {
+ code := `
+import React from 'react';
+import { useState, useEffect } from 'react';
+import * as utils from './utils';
+import { Foo as Bar } from './components/foo';
+const lodash = require('lodash');
+`
+ tree, source := parseSource(t, lang.TypeScript, code)
+ defer tree.Close()
+
+ imports := parseESModuleImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "React", "react")
+ assertImport(t, imports, "useState", "react.useState")
+ assertImport(t, imports, "useEffect", "react.useEffect")
+ assertImport(t, imports, "utils", "myproject.utils")
+ assertImport(t, imports, "Bar", "myproject.components.foo.Foo")
+ assertImport(t, imports, "lodash", "lodash")
+}
+
+func TestParseJavaImports(t *testing.T) {
+ code := `
+import java.util.List;
+import java.util.Map;
+import static org.junit.Assert.assertEquals;
+`
+ tree, source := parseSource(t, lang.Java, code)
+ defer tree.Close()
+
+ imports := parseJavaImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "List", "myproject.java.util.List")
+ assertImport(t, imports, "Map", "myproject.java.util.Map")
+ assertImport(t, imports, "assertEquals", "myproject.org.junit.Assert.assertEquals")
+}
+
+func TestParseKotlinImports(t *testing.T) {
+ code := `
+import org.example.Foo
+import org.example.Bar as Baz
+`
+ tree, source := parseSource(t, lang.Kotlin, code)
+ defer tree.Close()
+
+ imports := parseKotlinImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "Foo", "myproject.org.example.Foo")
+ assertImport(t, imports, "Baz", "myproject.org.example.Bar")
+}
+
+func TestParseCSharpImports(t *testing.T) {
+ code := `
+using System;
+using System.Collections.Generic;
+using Alias = System.IO.File;
+`
+ tree, source := parseSource(t, lang.CSharp, code)
+ defer tree.Close()
+
+ imports := parseCSharpImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "System", "myproject.System")
+ assertImport(t, imports, "Generic", "myproject.System.Collections.Generic")
+ assertImport(t, imports, "Alias", "myproject.System.IO.File")
+}
+
+func TestParseCImports(t *testing.T) {
+ code := `
+#include <stdio.h>
+#include "myheader.h"
+#include "utils/helpers.h"
+`
+ tree, source := parseSource(t, lang.C, code)
+ defer tree.Close()
+
+ imports := parseCImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "stdio", "stdio")
+ assertImport(t, imports, "myheader", "myheader")
+ assertImport(t, imports, "helpers", "utils.helpers")
+}
+
+func TestParseRustImports(t *testing.T) {
+ code := `
+use std::io;
+use crate::module::Type;
+use std::{fs, path};
+use std::io::Write as IoWrite;
+`
+ tree, source := parseSource(t, lang.Rust, code)
+ defer tree.Close()
+
+ imports := parseRustImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "io", "std.io")
+ assertImport(t, imports, "Type", "crate.module.Type")
+ assertImport(t, imports, "fs", "std.fs")
+ assertImport(t, imports, "path", "std.path")
+ assertImport(t, imports, "IoWrite", "std.io.Write")
+}
+
+func TestParsePHPImports(t *testing.T) {
+ code := `<?php
+use App\Models\User;
+use App\Http\Controllers\Controller;
+`
+ tree, source := parseSource(t, lang.PHP, code)
+ defer tree.Close()
+
+ imports := parsePHPImports(tree.RootNode(), source, "myproject")
+
+ if len(imports) == 0 {
+ t.Skip("PHP tree-sitter namespace_use_declaration node type may differ")
+ }
+ assertImport(t, imports, "User", "myproject.App.Models.User")
+}
+
+func TestParseRubyImports(t *testing.T) {
+ code := `
+require 'json'
+require_relative 'helpers/utils'
+`
+ tree, source := parseSource(t, lang.Ruby, code)
+ defer tree.Close()
+
+ imports := parseRubyImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "json", "json")
+ assertImport(t, imports, "utils", "myproject.helpers.utils")
+}
+
+func TestParseLuaImports(t *testing.T) {
+ code := `
+local json = require("json")
+local utils = require("my.utils")
+`
+ tree, source := parseSource(t, lang.Lua, code)
+ defer tree.Close()
+
+ imports := parseLuaImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "json", "myproject.json")
+ assertImport(t, imports, "utils", "myproject.my.utils")
+}
+
+func TestParseElixirImports(t *testing.T) {
+ code := `
+defmodule MyApp.Worker do
+ alias MyApp.Repo
+ import Ecto.Query
+ use GenServer
+end
+`
+ tree, source := parseSource(t, lang.Elixir, code)
+ defer tree.Close()
+
+ imports := parseElixirImports(tree.RootNode(), source, "myproject")
+
+ if len(imports) == 0 {
+ t.Skip("Elixir import extraction may need AST verification")
+ }
+ // At minimum, one of these should be captured
+ if _, ok := imports["Repo"]; !ok {
+ if _, ok := imports["Query"]; !ok {
+ if _, ok := imports["GenServer"]; !ok {
+ t.Errorf("expected at least one Elixir import; got: %v", imports)
+ }
+ }
+ }
+}
+
+func TestParseBashImports(t *testing.T) {
+ code := `
+source ./lib/helpers.sh
+. /etc/profile
+`
+ tree, source := parseSource(t, lang.Bash, code)
+ defer tree.Close()
+
+ imports := parseBashImports(tree.RootNode(), source, "myproject")
+
+ if len(imports) == 0 {
+ t.Skip("Bash source command AST structure may differ")
+ }
+ // Should capture at least the first source command
+ assertImport(t, imports, "helpers", "myproject.lib.helpers")
+}
+
+func TestParseZigImports(t *testing.T) {
+ code := `
+const std = @import("std");
+const utils = @import("utils.zig");
+`
+ tree, source := parseSource(t, lang.Zig, code)
+ defer tree.Close()
+
+ imports := parseZigImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "std", "std")
+ assertImport(t, imports, "utils", "myproject.utils")
+}
+
+func TestParseHaskellImports(t *testing.T) {
+ code := `
+module Main where
+
+import Data.Map
+import Data.List as L
+import qualified Data.Set
+`
+ tree, source := parseSource(t, lang.Haskell, code)
+ defer tree.Close()
+
+ imports := parseHaskellImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "Map", "Data.Map")
+ assertImport(t, imports, "L", "Data.List")
+ assertImport(t, imports, "Set", "Data.Set")
+}
+
+func TestParseOCamlImports(t *testing.T) {
+ code := `
+open Printf
+open Lwt.Syntax
+`
+ tree, source := parseSource(t, lang.OCaml, code)
+ defer tree.Close()
+
+ imports := parseOCamlImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "Printf", "Printf")
+ assertImport(t, imports, "Syntax", "Lwt.Syntax")
+}
+
+func TestParseGoImports(t *testing.T) {
+ code := `package main
+
+import (
+ "fmt"
+ "net/http"
+ alias "github.com/org/myproject/internal/pkg"
+)
+`
+ tree, source := parseSource(t, lang.Go, code)
+ defer tree.Close()
+
+ imports := parseGoImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "fmt", "fmt")
+ assertImport(t, imports, "http", "net.http")
+ assertImport(t, imports, "alias", "myproject.internal.pkg")
+}
+
+func TestParsePythonImports(t *testing.T) {
+ code := `
+import os
+import json as j
+from typing import List, Optional
+from ..utils import helper
+`
+ tree, source := parseSource(t, lang.Python, code)
+ defer tree.Close()
+
+ imports := parsePythonImports(tree.RootNode(), source, "myproject", "pkg/main.py")
+
+ assertImport(t, imports, "os", "myproject.os")
+ assertImport(t, imports, "j", "myproject.json")
+ assertImport(t, imports, "List", "myproject.typing.List")
+ assertImport(t, imports, "Optional", "myproject.typing.Optional")
+}
+
+// --- Callee extraction tests ---
+
+func TestExtractHaskellCallee(t *testing.T) {
+ code := `
+module Main where
+
+main = do
+ putStrLn "hello"
+ print (length [1,2,3])
+`
+ tree, source := parseSource(t, lang.Haskell, code)
+ defer tree.Close()
+
+ var callees []string
+ spec := lang.ForLanguage(lang.Haskell)
+ callTypes := toSet(spec.CallNodeTypes)
+
+ parser.Walk(tree.RootNode(), func(node *tree_sitter.Node) bool {
+ if !callTypes[node.Kind()] {
+ return true
+ }
+ name := extractCalleeName(node, source, lang.Haskell)
+ if name != "" {
+ callees = append(callees, name)
+ }
+ return true
+ })
+
+ if len(callees) == 0 {
+ t.Error("expected at least one Haskell callee extracted")
+ }
+ t.Logf("Haskell callees: %v", callees)
+}
+
+func TestExtractOCamlCallee(t *testing.T) {
+ code := `
+let () =
+ Printf.printf "hello\n";
+ List.map succ [1; 2; 3]
+`
+ tree, source := parseSource(t, lang.OCaml, code)
+ defer tree.Close()
+
+ var callees []string
+ spec := lang.ForLanguage(lang.OCaml)
+ callTypes := toSet(spec.CallNodeTypes)
+
+ parser.Walk(tree.RootNode(), func(node *tree_sitter.Node) bool {
+ if !callTypes[node.Kind()] {
+ return true
+ }
+ name := extractCalleeName(node, source, lang.OCaml)
+ if name != "" {
+ callees = append(callees, name)
+ }
+ return true
+ })
+
+ if len(callees) == 0 {
+ t.Error("expected at least one OCaml callee extracted")
+ }
+ t.Logf("OCaml callees: %v", callees)
+}
+
+func TestExtractElixirPipeCallee(t *testing.T) {
+ code := `
+defmodule MyApp do
+ def run do
+ value
+ |> transform()
+ |> save()
+ end
+end
+`
+ tree, source := parseSource(t, lang.Elixir, code)
+ defer tree.Close()
+
+ var callees []string
+ spec := lang.ForLanguage(lang.Elixir)
+ callTypes := toSet(spec.CallNodeTypes)
+
+ parser.Walk(tree.RootNode(), func(node *tree_sitter.Node) bool {
+ if !callTypes[node.Kind()] {
+ return true
+ }
+ name := extractCalleeName(node, source, lang.Elixir)
+ if name != "" {
+ callees = append(callees, name)
+ }
+ return true
+ })
+
+ // Should find "transform" and "save" from the pipe chain
+ if len(callees) == 0 {
+ t.Error("expected at least one Elixir pipe callee extracted")
+ }
+ t.Logf("Elixir callees: %v", callees)
+}
+
+// --- OOP hierarchy tests ---
+
+func TestIsClassDeclarationWidened(t *testing.T) {
+ tests := []struct {
+ kind string
+ lang lang.Language
+ expected bool
+ }{
+ {"class_declaration", lang.Java, true},
+ {"class_definition", lang.Python, true},
+ {"abstract_class_declaration", lang.TypeScript, true},
+ {"interface_declaration", lang.TypeScript, true},
+ {"interface_declaration", lang.Java, true},
+ {"interface_declaration", lang.CSharp, true},
+ {"struct_declaration", lang.CSharp, true},
+ {"enum_declaration", lang.CSharp, true},
+ {"object_definition", lang.Scala, true},
+ {"trait_definition", lang.Scala, true},
+ {"object_declaration", lang.Kotlin, true},
+ {"companion_object", lang.Kotlin, true},
+ {"trait_declaration", lang.PHP, true},
+ {"interface_declaration", lang.PHP, true},
+ // Cross-language false positive prevention
+ {"object_definition", lang.Java, false},
+ {"trait_definition", lang.Java, false},
+ {"struct_declaration", lang.Java, false},
+ {"companion_object", lang.CSharp, false},
+ }
+
+ for _, tt := range tests {
+ got := isClassDeclaration(tt.kind, tt.lang)
+ if got != tt.expected {
+ t.Errorf("isClassDeclaration(%q, %q) = %v, want %v", tt.kind, tt.lang, got, tt.expected)
+ }
+ }
+}
+
+// Route test filter tests are in internal/httplink/httplink_test.go
+
+// --- JSX component ref helper ---
+
+func TestIsUpperFirst(t *testing.T) {
+ tests := []struct {
+ input string
+ expected bool
+ }{
+ {"Component", true},
+ {"div", false},
+ {"MyComponent", true},
+ {"span", false},
+ {"", false},
+ {"A", true},
+ }
+
+ for _, tt := range tests {
+ got := isUpperFirst(tt.input)
+ if got != tt.expected {
+ t.Errorf("isUpperFirst(%q) = %v, want %v", tt.input, got, tt.expected)
+ }
+ }
+}
+
+func TestParseScalaImports(t *testing.T) {
+ code := `
+import scala.collection.mutable.Map
+import java.util.Date
+`
+ tree, source := parseSource(t, lang.Scala, code)
+ defer tree.Close()
+
+ imports := parseScalaImports(tree.RootNode(), source, "myproject")
+
+ assertImport(t, imports, "Map", "myproject.scala.collection.mutable.Map")
+ assertImport(t, imports, "Date", "myproject.java.util.Date")
+}
diff --git a/internal/pipeline/pipeline.go b/internal/pipeline/pipeline.go
index 40f0e8e2e..8db90f981 100644
--- a/internal/pipeline/pipeline.go
+++ b/internal/pipeline/pipeline.go
@@ -38,6 +38,8 @@ type Pipeline struct {
registry *FunctionRegistry
// importMaps stores per-module import maps: moduleQN -> localName -> resolvedQN
importMaps map[string]map[string]string
+ // returnTypes maps function QN -> return type QN for return-type-based type inference
+ returnTypes ReturnTypeMap
}
type cachedAST struct {
@@ -201,6 +203,7 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {
}
t = time.Now()
+ p.buildReturnTypeMap()
p.passCalls()
slog.Info("pass.timing", "pass", "calls", "elapsed", time.Since(t))
if err := p.checkCancel(); err != nil {
@@ -214,21 +217,7 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {
return err
}
- t = time.Now()
- p.passUsesType() // USES_TYPE edges (signatures + body)
- slog.Info("pass.timing", "pass", "usestype", "elapsed", time.Since(t))
-
- t = time.Now()
- p.passThrows() // THROWS/RAISES edges
- slog.Info("pass.timing", "pass", "throws", "elapsed", time.Since(t))
-
- t = time.Now()
- p.passReadsWrites() // READS/WRITES edges
- slog.Info("pass.timing", "pass", "readwrite", "elapsed", time.Since(t))
-
- t = time.Now()
- p.passConfigures() // CONFIGURES edges
- slog.Info("pass.timing", "pass", "configures", "elapsed", time.Since(t))
+ p.runSemanticEdgePasses()
if err := p.checkCancel(); err != nil {
return err
}
@@ -270,6 +259,25 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {
return nil
}
+// runSemanticEdgePasses runs the semantic edge passes (USES_TYPE, THROWS, READS/WRITES, CONFIGURES).
+func (p *Pipeline) runSemanticEdgePasses() {
+ t := time.Now()
+ p.passUsesType()
+ slog.Info("pass.timing", "pass", "usestype", "elapsed", time.Since(t))
+
+ t = time.Now()
+ p.passThrows()
+ slog.Info("pass.timing", "pass", "throws", "elapsed", time.Since(t))
+
+ t = time.Now()
+ p.passReadsWrites()
+ slog.Info("pass.timing", "pass", "readwrite", "elapsed", time.Since(t))
+
+ t = time.Now()
+ p.passConfigures()
+ slog.Info("pass.timing", "pass", "configures", "elapsed", time.Since(t))
+}
+
// logEdgeCounts logs the count of each edge type for observability.
func (p *Pipeline) logEdgeCounts() {
edgeTypes := []string{
@@ -353,6 +361,7 @@ func (p *Pipeline) runIncrementalPasses(
}
// Re-resolve calls + usages for changed + dependent files
+ p.buildReturnTypeMap()
p.passCallsForFiles(filesToResolve)
p.passUsagesForFiles(filesToResolve)
if err := p.checkCancel(); err != nil {
@@ -1711,6 +1720,42 @@ func (p *Pipeline) buildRegistry() {
slog.Info("registry.built", "entries", p.registry.Size())
}
+// buildReturnTypeMap builds a map from function QN to its return type QN.
+// Uses the "return_types" property stored on Function/Method nodes during pass2.
+func (p *Pipeline) buildReturnTypeMap() {
+ p.returnTypes = make(ReturnTypeMap)
+ for _, label := range []string{"Function", "Method"} {
+ nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)
+ if err != nil {
+ continue
+ }
+ for _, n := range nodes {
+ retTypes, ok := n.Properties["return_types"]
+ if !ok {
+ continue
+ }
+ // return_types is stored as []any (JSON round-trip) containing type name strings
+ typeList, ok := retTypes.([]any)
+ if !ok || len(typeList) == 0 {
+ continue
+ }
+ // Use the first return type — most functions return a single type
+ firstType, ok := typeList[0].(string)
+ if !ok || firstType == "" {
+ continue
+ }
+ // Resolve the type name to a class QN
+ classQN := resolveAsClass(firstType, p.registry, "", nil)
+ if classQN != "" {
+ p.returnTypes[n.QualifiedName] = classQN
+ }
+ }
+ }
+ if len(p.returnTypes) > 0 {
+ slog.Info("return_types.built", "entries", len(p.returnTypes))
+ }
+}
+
// resolvedEdge represents an edge resolved during parallel call/usage resolution,
// stored as QN pairs to be converted to ID-based edges in the batch write stage.
type resolvedEdge struct {
@@ -1779,7 +1824,7 @@ func (p *Pipeline) resolveFileCalls(relPath string, cached *cachedAST) []resolve
importMap := p.importMaps[moduleQN]
// Infer variable types for method dispatch
- typeMap := inferTypes(root, cached.Source, cached.Language, p.registry, moduleQN, importMap)
+ typeMap := inferTypes(root, cached.Source, cached.Language, p.registry, moduleQN, importMap, p.returnTypes)
var edges []resolvedEdge
@@ -1813,23 +1858,41 @@ func (p *Pipeline) resolveFileCalls(relPath string, cached *cachedAST) []resolve
// Go receiver scoping
localTypeMap := p.extendTypeMapWithReceiver(node, cached, typeMap, spec, moduleQN, importMap)
- targetQN := p.resolveCallWithTypes(calleeName, moduleQN, importMap, localTypeMap)
- if targetQN == "" {
- if fuzzyQN, ok := p.registry.FuzzyResolve(calleeName, moduleQN); ok {
+ result := p.resolveCallWithTypes(calleeName, moduleQN, importMap, localTypeMap)
+ if result.QualifiedName == "" {
+ if fuzzyResult, ok := p.registry.FuzzyResolve(calleeName, moduleQN, importMap); ok {
edges = append(edges, resolvedEdge{
- CallerQN: callerQN,
- TargetQN: fuzzyQN,
- Type: "CALLS",
- Properties: map[string]any{"resolution_mode": "fuzzy"},
+ CallerQN: callerQN,
+ TargetQN: fuzzyResult.QualifiedName,
+ Type: "CALLS",
+ Properties: map[string]any{
+ "confidence": fuzzyResult.Confidence,
+ "confidence_band": confidenceBand(fuzzyResult.Confidence),
+ "resolution_strategy": fuzzyResult.Strategy,
+ },
})
}
return false
}
- edges = append(edges, resolvedEdge{CallerQN: callerQN, TargetQN: targetQN, Type: "CALLS"})
+ edges = append(edges, resolvedEdge{
+ CallerQN: callerQN,
+ TargetQN: result.QualifiedName,
+ Type: "CALLS",
+ Properties: map[string]any{
+ "confidence": result.Confidence,
+ "confidence_band": confidenceBand(result.Confidence),
+ "resolution_strategy": result.Strategy,
+ },
+ })
return false
})
+ // TSX/JSX: extract component references from JSX elements
+ if cached.Language == lang.TSX || cached.Language == lang.JavaScript {
+ edges = append(edges, p.extractJSXComponentRefs(root, cached.Source, moduleQN, importMap, relPath, spec)...)
+ }
+
return edges
}
@@ -1852,6 +1915,107 @@ func (p *Pipeline) processFileCalls(relPath string, cached *cachedAST, _ *lang.L
}
}
+// extractJSXComponentRefs extracts component references from JSX elements.
+// In JSX, <Component /> is semantically equivalent to calling the component function.
+// Only uppercase names are considered components (lowercase = HTML intrinsics like <div>).
+func (p *Pipeline) extractJSXComponentRefs(
+ root *tree_sitter.Node,
+ source []byte,
+ moduleQN string,
+ importMap map[string]string,
+ relPath string,
+ spec *lang.LanguageSpec,
+) []resolvedEdge {
+ var edges []resolvedEdge
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ switch node.Kind() {
+ case "jsx_self_closing_element":
+ nameNode := node.ChildByFieldName("name")
+ if nameNode == nil {
+ return false
+ }
+ componentName := parser.NodeText(nameNode, source)
+ if edge := p.resolveJSXComponent(node, componentName, source, moduleQN, importMap, relPath, spec); edge != nil {
+ edges = append(edges, *edge)
+ }
+ return false
+ case "jsx_opening_element":
+ nameNode := node.ChildByFieldName("name")
+ if nameNode == nil {
+ return false
+ }
+ componentName := parser.NodeText(nameNode, source)
+ if edge := p.resolveJSXComponent(node, componentName, source, moduleQN, importMap, relPath, spec); edge != nil {
+ edges = append(edges, *edge)
+ }
+ return false
+ }
+ return true
+ })
+
+ return edges
+}
+
+func (p *Pipeline) resolveJSXComponent(
+ node *tree_sitter.Node,
+ componentName string,
+ source []byte,
+ moduleQN string,
+ importMap map[string]string,
+ relPath string,
+ spec *lang.LanguageSpec,
+) *resolvedEdge {
+ if componentName == "" {
+ return nil
+ }
+ // Filter HTML intrinsics: lowercase names are DOM elements, not components
+ if !isUpperFirst(componentName) {
+ return nil
+ }
+ // Strip member expressions: <Foo.Bar /> → resolve "Foo" (the import)
+ baseName := componentName
+ if idx := strings.Index(componentName, "."); idx > 0 {
+ baseName = componentName[:idx]
+ }
+
+ callerQN := findEnclosingFunction(node, source, p.ProjectName, relPath, spec)
+ if callerQN == "" {
+ callerQN = moduleQN
+ }
+
+ // Try to resolve via import map first
+ result := p.resolveCallWithTypes(baseName, moduleQN, importMap, nil)
+ if result.QualifiedName != "" {
+ return &resolvedEdge{
+ CallerQN: callerQN,
+ TargetQN: result.QualifiedName,
+ Type: "CALLS",
+ Properties: map[string]any{
+ "confidence": result.Confidence,
+ "confidence_band": confidenceBand(result.Confidence),
+ "resolution_strategy": "jsx_component",
+ },
+ }
+ }
+
+ // Fuzzy resolve
+ if fuzzyResult, ok := p.registry.FuzzyResolve(baseName, moduleQN, importMap); ok {
+ return &resolvedEdge{
+ CallerQN: callerQN,
+ TargetQN: fuzzyResult.QualifiedName,
+ Type: "CALLS",
+ Properties: map[string]any{
+ "confidence": fuzzyResult.Confidence,
+ "confidence_band": confidenceBand(fuzzyResult.Confidence),
+ "resolution_strategy": "jsx_component",
+ },
+ }
+ }
+
+ return nil
+}
+
// flushResolvedEdges converts QN-based resolved edges to ID-based edges and batch-inserts them.
func (p *Pipeline) flushResolvedEdges(results [][]resolvedEdge) {
// Collect all unique QNs
@@ -1939,7 +2103,7 @@ func (p *Pipeline) resolveCallWithTypes(
calleeName, moduleQN string,
importMap map[string]string,
typeMap TypeMap,
-) string {
+) ResolutionResult {
// First, try type-based method dispatch for qualified calls like obj.method()
if strings.Contains(calleeName, ".") {
parts := strings.SplitN(calleeName, ".", 2)
@@ -1950,7 +2114,7 @@ func (p *Pipeline) resolveCallWithTypes(
if classQN, ok := typeMap[objName]; ok {
candidate := classQN + "." + methodName
if p.registry.Exists(candidate) {
- return candidate
+ return ResolutionResult{QualifiedName: candidate, Strategy: "type_dispatch", Confidence: 0.90, CandidateCount: 1}
}
}
}
@@ -1990,7 +2154,8 @@ func extractCalleeFromFunctionField(node *tree_sitter.Node, source []byte) strin
switch funcNode.Kind() {
case "identifier", "simple_identifier",
"selector_expression", "attribute", "member_expression",
- "field_expression", "dot", "function":
+ "field_expression", "dot", "function", "dotted_identifier",
+ "member_access_expression", "scoped_identifier", "qualified_identifier":
return parser.NodeText(funcNode, source)
}
return ""
@@ -2009,7 +2174,9 @@ func extractCalleeFromMethodField(node *tree_sitter.Node, source []byte) string
}
// extractCalleeLanguageSpecific handles language-specific callee extraction
-// for ObjC, Erlang, Perl, and Kotlin.
+// for ObjC, Erlang, Perl, Kotlin, Haskell, OCaml, and Elixir.
+//
+//nolint:cyclop // WHY: inherent complexity from multi-language AST dispatch
func extractCalleeLanguageSpecific(node *tree_sitter.Node, source []byte, language lang.Language) string {
switch language {
case lang.ObjectiveC:
@@ -2022,6 +2189,44 @@ func extractCalleeLanguageSpecific(node *tree_sitter.Node, source []byte, langua
return extractErlangCallee(node, source)
case lang.Perl:
return extractPerlCallee(node, source)
+ case lang.Rust:
+ return extractRustCallee(node, source)
+ case lang.Zig:
+ return extractZigCallee(node, source)
+ case lang.PHP:
+ return extractPHPCallee(node, source)
+ case lang.Scala:
+ return extractScalaCallee(node, source)
+ case lang.Haskell:
+ return extractHaskellCallee(node, source)
+ case lang.OCaml:
+ return extractOCamlCallee(node, source)
+ case lang.Elixir:
+ return extractElixirCallee(node, source)
+ }
+
+ // HCL: function_call → first child identifier
+ if language == lang.HCL && node.Kind() == "function_call" {
+ if first := node.NamedChild(0); first != nil && first.Kind() == "identifier" {
+ return parser.NodeText(first, source)
+ }
+ }
+
+ // SQL: invocation/function_call → object_reference → identifier[name]
+ if language == lang.SQL && (node.Kind() == "function_call" || node.Kind() == "invocation") {
+ if objRef := findChildByKind(node, "object_reference"); objRef != nil {
+ if nameNode := objRef.ChildByFieldName("name"); nameNode != nil {
+ return parser.NodeText(nameNode, source)
+ }
+ }
+ if first := node.NamedChild(0); first != nil {
+ return parser.NodeText(first, source)
+ }
+ }
+
+ // Dart: selector → callee is preceding sibling identifier
+ if language == lang.Dart && node.Kind() == "selector" {
+ return extractDartCallee(node, source)
}
// Kotlin call_expression / navigation_expression
@@ -2036,6 +2241,299 @@ func extractCalleeLanguageSpecific(node *tree_sitter.Node, source []byte, langua
return ""
}
+// extractDartCallee extracts the callee from Dart selector nodes.
+// In Dart, a call like `print('hello')` parses as:
+//
+// expression_statement → identifier("print") + selector("('hello')")
+//
+// The callee is the preceding sibling(s) of the selector node.
+// For chained calls like `list.add(1)`: identifier("list") + selector(".add") + selector("(1)")
+func extractDartCallee(node *tree_sitter.Node, source []byte) string {
+ // Only extract from selectors that represent actual calls (have argument_part)
+ if findChildByKind(node, "argument_part") == nil {
+ return ""
+ }
+
+ parent := node.Parent()
+ if parent == nil {
+ return ""
+ }
+ nodeIdx := findNodeIndex(parent, node)
+ if nodeIdx <= 0 {
+ return ""
+ }
+ // Walk backwards collecting the callee parts (identifiers and member selectors)
+ var parts []string
+ for j := nodeIdx - 1; j >= 0; j-- {
+ prev := parent.Child(uint(j))
+ if prev == nil {
+ break
+ }
+ kind := prev.Kind()
+ switch kind {
+ case "identifier", "type_identifier":
+ parts = append([]string{parser.NodeText(prev, source)}, parts...)
+ return joinDartCalleeParts(parts)
+ case "selector":
+ // Chained member access like .add — extract identifier from child
+ if uas := findChildByKind(prev, "unconditional_assignable_selector"); uas != nil {
+ if id := findChildByKind(uas, "identifier"); id != nil {
+ parts = append([]string{parser.NodeText(id, source)}, parts...)
+ continue
+ }
+ }
+ // Selector with argument_part is a preceding call in the chain — stop here.
+ // The callee is just the immediate method name (e.g., "toList" not "items.where.toList")
+ if len(parts) > 0 {
+ return joinDartCalleeParts(parts)
+ }
+ return ""
+ default:
+ return ""
+ }
+ }
+ if len(parts) > 0 {
+ return joinDartCalleeParts(parts)
+ }
+ return ""
+}
+
+func joinDartCalleeParts(parts []string) string {
+ if len(parts) == 0 {
+ return ""
+ }
+ result := parts[0]
+ for _, p := range parts[1:] {
+ result += "." + p
+ }
+ return result
+}
+
+// extractHaskellCallee extracts the callee from Haskell apply/infix nodes.
+func extractHaskellCallee(node *tree_sitter.Node, source []byte) string {
+ switch node.Kind() {
+ case "apply":
+ // Function application: recurse through nested apply nodes to get the
+ // actual function name (not "map show" but just "map")
+ if fn := node.ChildByFieldName("function"); fn != nil {
+ if fn.Kind() == "apply" {
+ return extractHaskellCallee(fn, source)
+ }
+ return parser.NodeText(fn, source)
+ }
+ if first := node.NamedChild(0); first != nil {
+ if first.Kind() == "apply" {
+ return extractHaskellCallee(first, source)
+ }
+ return parser.NodeText(first, source)
+ }
+ case "infix":
+ // Infix application: left_operand op right_operand
+ // The operator is the callee (e.g., f $ x, x <> y)
+ if op := node.ChildByFieldName("operator"); op != nil {
+ return parser.NodeText(op, source)
+ }
+ // Fallback: the function in f `op` x is the first child
+ if first := node.NamedChild(0); first != nil {
+ return parser.NodeText(first, source)
+ }
+ }
+ return ""
+}
+
+// extractOCamlCallee extracts the callee from OCaml application/infix_expression nodes.
+//
+//nolint:gocognit,nestif // WHY: inherent complexity from OCaml AST node type dispatch
+func extractOCamlCallee(node *tree_sitter.Node, source []byte) string {
+ switch node.Kind() {
+ case "application_expression":
+ // Function application: first named child is the function
+ if first := node.NamedChild(0); first != nil {
+ return parser.NodeText(first, source)
+ }
+ case "infix_expression":
+ // Pipe operator: x |> f or f @@ x → callee depends on operator
+ if op := node.ChildByFieldName("operator"); op != nil {
+ opText := parser.NodeText(op, source)
+ switch opText {
+ case "|>":
+ // x |> f → callee is right operand
+ // If right is application_expression (e.g., List.map show), extract just the function
+ if right := node.ChildByFieldName("right"); right != nil {
+ if right.Kind() == "application_expression" {
+ if first := right.NamedChild(0); first != nil {
+ return parser.NodeText(first, source)
+ }
+ }
+ return parser.NodeText(right, source)
+ }
+ case "@@":
+ // f @@ x → callee is left operand
+ if left := node.ChildByFieldName("left"); left != nil {
+ return parser.NodeText(left, source)
+ }
+ }
+ }
+ // Fallback: try positional children for infix operators
+ if node.NamedChildCount() >= 3 {
+ op := node.NamedChild(1)
+ if op != nil {
+ switch opText := parser.NodeText(op, source); opText {
+ case "|>":
+ if right := node.NamedChild(2); right != nil {
+ if right.Kind() == "application_expression" {
+ if first := right.NamedChild(0); first != nil {
+ return parser.NodeText(first, source)
+ }
+ }
+ return parser.NodeText(right, source)
+ }
+ case "@@":
+ if left := node.NamedChild(0); left != nil {
+ return parser.NodeText(left, source)
+ }
+ }
+ }
+ }
+ }
+ return ""
+}
+
+// elixirKeywords are Elixir framework/kernel calls that should be filtered from callees.
+var elixirKeywords = map[string]bool{
+ "def": true, "defp": true, "defmodule": true, "defmacro": true, "defmacrop": true,
+ "defstruct": true, "defprotocol": true, "defimpl": true, "defguard": true,
+ "defdelegate": true, "defexception": true, "defoverridable": true,
+ "use": true, "import": true, "alias": true, "require": true,
+ "with": true, "for": true, "if": true, "unless": true, "case": true, "cond": true,
+}
+
+// extractElixirCallee extracts the callee from Elixir call/dot/binary_operator nodes.
+//
+//nolint:gocognit,nestif,cyclop // WHY: inherent complexity from Elixir AST node type dispatch
+func extractElixirCallee(node *tree_sitter.Node, source []byte) string {
+ switch node.Kind() {
+ case "binary_operator":
+ if op := node.ChildByFieldName("operator"); op != nil {
+ if parser.NodeText(op, source) == "|>" {
+ if right := node.ChildByFieldName("right"); right != nil {
+ // Extract just the function name from the pipe target
+ if right.Kind() == "call" {
+ if first := right.NamedChild(0); first != nil {
+ if first.Kind() == "dot" {
+ return parser.NodeText(first, source)
+ }
+ return parser.NodeText(first, source)
+ }
+ }
+ return parser.NodeText(right, source)
+ }
+ }
+ }
+ return "" // non-pipe binary_operator, skip
+ case "dot":
+ // Module.function — skip if parent is call (parent call extracts the dot child)
+ if p := node.Parent(); p != nil && p.Kind() == "call" {
+ return ""
+ }
+ return parser.NodeText(node, source)
+ case "call":
+ if p := node.Parent(); p != nil {
+ // Skip call nodes that are arguments to keyword calls (def f(x) — f is not a call).
+ // The tree is: call[def] → arguments → call[f(x)], so check grandparent too.
+ keywordParent := p
+ if p.Kind() == "arguments" {
+ keywordParent = p.Parent()
+ }
+ if keywordParent != nil && keywordParent.Kind() == "call" {
+ if kFirst := keywordParent.NamedChild(0); kFirst != nil && elixirKeywords[parser.NodeText(kFirst, source)] {
+ return ""
+ }
+ }
+ // Skip call nodes that are the right operand of a pipe (already extracted by binary_operator)
+ if p.Kind() == "binary_operator" {
+ if op := p.ChildByFieldName("operator"); op != nil && parser.NodeText(op, source) == "|>" {
+ if right := p.ChildByFieldName("right"); right != nil && right.Id() == node.Id() {
+ return ""
+ }
+ }
+ }
+ }
+ // Check if the call's first child is a "dot" node (qualified call like IO.puts)
+ if first := node.NamedChild(0); first != nil {
+ if first.Kind() == "dot" {
+ return parser.NodeText(first, source)
+ }
+ name := parser.NodeText(first, source)
+ if elixirKeywords[name] {
+ return ""
+ }
+ return name
+ }
+ }
+ return ""
+}
+
+// extractRustCallee handles Rust macro_invocation nodes.
+func extractRustCallee(node *tree_sitter.Node, source []byte) string {
+ if node.Kind() == "macro_invocation" {
+ if first := node.NamedChild(0); first != nil && first.Kind() == "identifier" {
+ return parser.NodeText(first, source) + "!"
+ }
+ if first := node.NamedChild(0); first != nil && first.Kind() == "scoped_identifier" {
+ return parser.NodeText(first, source) + "!"
+ }
+ }
+ return ""
+}
+
+// extractZigCallee handles Zig builtin_function nodes (e.g., @intCast).
+func extractZigCallee(node *tree_sitter.Node, source []byte) string {
+ if node.Kind() == "builtin_function" {
+ // The first child of builtin_function is the @name token
+ if fn := node.ChildByFieldName("function"); fn != nil {
+ return parser.NodeText(fn, source)
+ }
+ // Fallback: return full text (e.g., "@intCast")
+ text := parser.NodeText(node, source)
+ // Strip arguments if present
+ if idx := strings.Index(text, "("); idx > 0 {
+ return text[:idx]
+ }
+ return text
+ }
+ return ""
+}
+
+// extractPHPCallee handles PHP function_call_expression nodes.
+func extractPHPCallee(node *tree_sitter.Node, source []byte) string {
+ if node.Kind() == "function_call_expression" {
+ if nameNode := node.ChildByFieldName("function"); nameNode != nil {
+ return parser.NodeText(nameNode, source)
+ }
+ }
+ return ""
+}
+
+// extractScalaCallee handles Scala field_expression and infix_expression nodes.
+// Standalone field_expression (e.g., list.head) is a property access that acts as
+// a call in Scala. Skip if parent is call_expression (already handled by function field).
+func extractScalaCallee(node *tree_sitter.Node, source []byte) string {
+ switch node.Kind() {
+ case "field_expression":
+ if p := node.Parent(); p != nil && p.Kind() == "call_expression" {
+ return "" // parent call_expression already extracts via function field
+ }
+ return parser.NodeText(node, source)
+ case "infix_expression":
+ // Infix call: items map f → operator is the callee
+ if op := node.ChildByFieldName("operator"); op != nil {
+ return parser.NodeText(op, source)
+ }
+ }
+ return ""
+}
+
func extractErlangCallee(node *tree_sitter.Node, source []byte) string {
if node.Kind() != "call" {
return ""
@@ -2052,14 +2550,15 @@ func extractErlangCallee(node *tree_sitter.Node, source []byte) string {
}
func extractPerlCallee(node *tree_sitter.Node, source []byte) string {
- if node.Kind() != "ambiguous_function_call_expression" && node.Kind() != "function_call_expression" {
- return ""
- }
- if fn := node.ChildByFieldName("function"); fn != nil {
- return parser.NodeText(fn, source)
- }
- if first := node.NamedChild(0); first != nil {
- return parser.NodeText(first, source)
+ switch node.Kind() {
+ case "ambiguous_function_call_expression", "function_call_expression", "func1op_call_expression":
+ // Try function field first (func1op_call_expression uses this)
+ if fn := node.ChildByFieldName("function"); fn != nil {
+ return parser.NodeText(fn, source)
+ }
+ if first := node.NamedChild(0); first != nil {
+ return parser.NodeText(first, source)
+ }
}
return ""
}
@@ -2635,6 +3134,7 @@ func (p *Pipeline) passImports() {
targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetQN)
if targetNode == nil {
// Try common suffixes: module QN might need .__init__ or similar
+ logImportDrop(moduleQN, localName, targetQN)
continue
}
_, _ = p.Store.InsertEdge(&store.Edge{
diff --git a/internal/pipeline/pipeline_test.go b/internal/pipeline/pipeline_test.go
index 183e882d9..9d2ec7615 100644
--- a/internal/pipeline/pipeline_test.go
+++ b/internal/pipeline/pipeline_test.go
@@ -745,22 +745,22 @@ func TestFunctionRegistry(t *testing.T) {
}
// Resolve same-module
- qn := r.Resolve("Foo", "proj.pkg", nil)
- if qn != "proj.pkg.Foo" {
- t.Errorf("expected proj.pkg.Foo, got %s", qn)
+ res := r.Resolve("Foo", "proj.pkg", nil)
+ if res.QualifiedName != "proj.pkg.Foo" {
+ t.Errorf("expected proj.pkg.Foo, got %s", res.QualifiedName)
}
// Resolve via import map
imports := map[string]string{"other": "proj.other"}
- qn = r.Resolve("other.Foo", "proj.pkg", imports)
- if qn != "proj.other.Foo" {
- t.Errorf("expected proj.other.Foo, got %s", qn)
+ res = r.Resolve("other.Foo", "proj.pkg", imports)
+ if res.QualifiedName != "proj.other.Foo" {
+ t.Errorf("expected proj.other.Foo, got %s", res.QualifiedName)
}
// Resolve unique name
- qn = r.Resolve("Bar", "proj.unrelated", nil)
- if qn != "proj.pkg.Bar" {
- t.Errorf("expected proj.pkg.Bar, got %s", qn)
+ res = r.Resolve("Bar", "proj.unrelated", nil)
+ if res.QualifiedName != "proj.pkg.Bar" {
+ t.Errorf("expected proj.pkg.Bar, got %s", res.QualifiedName)
}
}
diff --git a/internal/pipeline/resolver.go b/internal/pipeline/resolver.go
index d304bcea8..b9db299eb 100644
--- a/internal/pipeline/resolver.go
+++ b/internal/pipeline/resolver.go
@@ -5,6 +5,16 @@ import (
"sync"
)
+// ResolutionResult carries the resolved QN plus quality metadata.
+// Initial confidence values are estimates — recalibrate after measuring
+// precision per strategy on real repos.
+type ResolutionResult struct {
+ QualifiedName string
+ Strategy string // "import_map", "import_map_suffix", "same_module", "unique_name", "suffix_match", "fuzzy", "type_dispatch"
+ Confidence float64 // 0.0–1.0
+ CandidateCount int // how many candidates were considered
+}
+
// FunctionRegistry indexes all Function, Method, and Class nodes by qualified
// name and simple name for fast call resolution.
type FunctionRegistry struct {
@@ -47,7 +57,7 @@ func (r *FunctionRegistry) Register(name, qualifiedName, nodeLabel string) {
// 2. Same-module match
// 3. Project-wide single match by simple name
// 4. Suffix match with import distance scoring
-func (r *FunctionRegistry) Resolve(calleeName, moduleQN string, importMap map[string]string) string {
+func (r *FunctionRegistry) Resolve(calleeName, moduleQN string, importMap map[string]string) ResolutionResult {
r.mu.RLock()
defer r.mu.RUnlock()
@@ -59,25 +69,25 @@ func (r *FunctionRegistry) Resolve(calleeName, moduleQN string, importMap map[st
suffix = parts[1]
}
- if result := r.resolveViaImportMap(prefix, suffix, importMap); result != "" {
+ if result := r.resolveViaImportMap(prefix, suffix, importMap); result.QualifiedName != "" {
return result
}
- if result := r.resolveViaSameModule(calleeName, suffix, moduleQN); result != "" {
+ if result := r.resolveViaSameModule(calleeName, suffix, moduleQN); result.QualifiedName != "" {
return result
}
- return r.resolveViaNameLookup(calleeName, suffix, moduleQN)
+ return r.resolveViaNameLookup(calleeName, suffix, moduleQN, importMap)
}
// resolveViaImportMap tries to resolve a callee using the import map (Strategy 1).
-func (r *FunctionRegistry) resolveViaImportMap(prefix, suffix string, importMap map[string]string) string {
+func (r *FunctionRegistry) resolveViaImportMap(prefix, suffix string, importMap map[string]string) ResolutionResult {
if importMap == nil {
- return ""
+ return ResolutionResult{}
}
resolved, ok := importMap[prefix]
if !ok {
- return ""
+ return ResolutionResult{}
}
var candidate string
if suffix != "" {
@@ -86,78 +96,122 @@ func (r *FunctionRegistry) resolveViaImportMap(prefix, suffix string, importMap
candidate = resolved
}
if _, exists := r.exact[candidate]; exists {
- return candidate
+ return ResolutionResult{QualifiedName: candidate, Strategy: "import_map", Confidence: 0.95, CandidateCount: 1}
}
if suffix != "" {
for qn := range r.exact {
if strings.HasPrefix(qn, resolved+".") && strings.HasSuffix(qn, "."+suffix) {
- return qn
+ return ResolutionResult{QualifiedName: qn, Strategy: "import_map_suffix", Confidence: 0.85, CandidateCount: 1}
}
}
}
- return ""
+ return ResolutionResult{}
}
// resolveViaSameModule tries to resolve a callee within the same module (Strategy 2).
-func (r *FunctionRegistry) resolveViaSameModule(calleeName, suffix, moduleQN string) string {
+func (r *FunctionRegistry) resolveViaSameModule(calleeName, suffix, moduleQN string) ResolutionResult {
sameModule := moduleQN + "." + calleeName
if _, exists := r.exact[sameModule]; exists {
- return sameModule
+ return ResolutionResult{QualifiedName: sameModule, Strategy: "same_module", Confidence: 0.90, CandidateCount: 1}
}
if suffix != "" {
sameModuleQualified := moduleQN + "." + suffix
if _, exists := r.exact[sameModuleQualified]; exists {
- return sameModuleQualified
+ return ResolutionResult{QualifiedName: sameModuleQualified, Strategy: "same_module", Confidence: 0.90, CandidateCount: 1}
}
}
- return ""
+ return ResolutionResult{}
}
// resolveViaNameLookup tries project-wide name lookup and suffix matching (Strategies 3+4).
-func (r *FunctionRegistry) resolveViaNameLookup(calleeName, suffix, moduleQN string) string {
+func (r *FunctionRegistry) resolveViaNameLookup(calleeName, suffix, moduleQN string, importMap map[string]string) ResolutionResult {
lookupName := calleeName
if suffix != "" {
lookupName = suffix
}
simple := simpleName(lookupName)
candidates := r.byName[simple]
+
+ // Strategy 3: unique name — single candidate project-wide
if len(candidates) == 1 {
- return candidates[0]
+ conf := 0.75
+ if importMap != nil && !isImportReachable(candidates[0], importMap) {
+ conf *= 0.5
+ }
+ return ResolutionResult{QualifiedName: candidates[0], Strategy: "unique_name", Confidence: conf, CandidateCount: 1}
}
+ // Strategy 4: suffix match with import distance scoring
if suffix != "" {
- var matches []string
- for _, qn := range candidates {
- if strings.HasSuffix(qn, "."+calleeName) {
- return qn
- }
- if strings.HasSuffix(qn, "."+suffix) {
- matches = append(matches, qn)
- }
+ if res := r.resolveSuffixMatch(calleeName, suffix, moduleQN, importMap, candidates); res.QualifiedName != "" {
+ return res
}
- if len(matches) == 1 {
- return matches[0]
+ }
+
+ return pickBestCandidate(candidates, moduleQN, importMap)
+}
+
+// resolveSuffixMatch handles Strategy 4 — suffix-based matching among multiple candidates.
+func (r *FunctionRegistry) resolveSuffixMatch(calleeName, suffix, moduleQN string, importMap map[string]string, candidates []string) ResolutionResult {
+ var matches []string
+ for _, qn := range candidates {
+ if strings.HasSuffix(qn, "."+calleeName) {
+ conf := importAdjustedConfidence(0.55, qn, importMap)
+ return ResolutionResult{QualifiedName: qn, Strategy: "suffix_match", Confidence: conf, CandidateCount: len(candidates)}
}
- if len(matches) > 1 {
- return bestByImportDistance(matches, moduleQN)
+ if strings.HasSuffix(qn, "."+suffix) {
+ matches = append(matches, qn)
}
}
+ if importMap != nil {
+ matches = filterImportReachable(matches, importMap)
+ }
+ if len(matches) == 1 {
+ return ResolutionResult{QualifiedName: matches[0], Strategy: "suffix_match", Confidence: 0.55, CandidateCount: len(candidates)}
+ }
+ if len(matches) > 1 {
+ best := bestByImportDistance(matches, moduleQN)
+ return ResolutionResult{QualifiedName: best, Strategy: "suffix_match", Confidence: 0.55, CandidateCount: len(matches)}
+ }
+ return ResolutionResult{}
+}
- if len(candidates) > 1 {
- return bestByImportDistance(candidates, moduleQN)
+// pickBestCandidate selects the best match from multiple candidates with import filtering.
+func pickBestCandidate(candidates []string, moduleQN string, importMap map[string]string) ResolutionResult {
+ if len(candidates) <= 1 {
+ return ResolutionResult{}
+ }
+ filtered := candidates
+ if importMap != nil {
+ filtered = filterImportReachable(candidates, importMap)
+ }
+ if len(filtered) == 0 {
+ best := bestByImportDistance(candidates, moduleQN)
+ return ResolutionResult{QualifiedName: best, Strategy: "suffix_match", Confidence: 0.55 * 0.5, CandidateCount: len(candidates)}
+ }
+ if len(filtered) == 1 {
+ return ResolutionResult{QualifiedName: filtered[0], Strategy: "suffix_match", Confidence: 0.55, CandidateCount: len(candidates)}
}
+ best := bestByImportDistance(filtered, moduleQN)
+ return ResolutionResult{QualifiedName: best, Strategy: "suffix_match", Confidence: 0.55, CandidateCount: len(filtered)}
+}
- return ""
+// importAdjustedConfidence halves confidence when a candidate is not import-reachable.
+func importAdjustedConfidence(base float64, candidateQN string, importMap map[string]string) float64 {
+ if importMap != nil && !isImportReachable(candidateQN, importMap) {
+ return base * 0.5
+ }
+ return base
}
// FuzzyResolve attempts a loose match when Resolve() returns "".
// It searches for any registered function whose simple name matches the callee's
-// last name segment. Returns the best match (by import distance) and true,
-// or "" and false if no match is found.
+// last name segment. Returns the best match (by import distance) with confidence,
+// or an empty result and false if no match is found.
//
// Unlike Resolve(), this does not require prefix/import agreement — it purely
-// matches on the function name. Results should be marked as "fuzzy" resolution.
-func (r *FunctionRegistry) FuzzyResolve(calleeName, moduleQN string) (string, bool) {
+// matches on the function name.
+func (r *FunctionRegistry) FuzzyResolve(calleeName, moduleQN string, importMap map[string]string) (ResolutionResult, bool) {
r.mu.RLock()
defer r.mu.RUnlock()
@@ -166,21 +220,51 @@ func (r *FunctionRegistry) FuzzyResolve(calleeName, moduleQN string) (string, bo
candidates := r.byName[lookupName]
if len(candidates) == 0 {
- return "", false
+ return ResolutionResult{}, false
}
// If there's exactly one candidate, use it
if len(candidates) == 1 {
- return candidates[0], true
+ conf := 0.40
+ if importMap != nil && !isImportReachable(candidates[0], importMap) {
+ conf *= 0.5
+ }
+ return ResolutionResult{
+ QualifiedName: candidates[0], Strategy: "fuzzy",
+ Confidence: conf, CandidateCount: 1,
+ }, true
}
- // Multiple candidates: pick best by import distance
- best := bestByImportDistance(candidates, moduleQN)
- if best != "" {
- return best, true
+ // Multiple candidates: filter by import reachability, then pick best by distance
+ filtered := candidates
+ if importMap != nil {
+ filtered = filterImportReachable(candidates, importMap)
}
-
- return "", false
+ if len(filtered) == 0 {
+ // No import-reachable candidates — use original with penalty
+ best := bestByImportDistance(candidates, moduleQN)
+ if best == "" {
+ return ResolutionResult{}, false
+ }
+ return ResolutionResult{
+ QualifiedName: best, Strategy: "fuzzy",
+ Confidence: 0.30 * 0.5, CandidateCount: len(candidates),
+ }, true
+ }
+ if len(filtered) == 1 {
+ return ResolutionResult{
+ QualifiedName: filtered[0], Strategy: "fuzzy",
+ Confidence: 0.40, CandidateCount: len(candidates),
+ }, true
+ }
+ best := bestByImportDistance(filtered, moduleQN)
+ if best == "" {
+ return ResolutionResult{}, false
+ }
+ return ResolutionResult{
+ QualifiedName: best, Strategy: "fuzzy",
+ Confidence: 0.30, CandidateCount: len(filtered),
+ }, true
}
// LabelOf returns the node label for a qualified name, or "" if not registered.
@@ -270,3 +354,50 @@ func commonPrefixLen(a, b string) int {
}
return count
}
+
+// modulePrefix extracts the module portion of a QN (everything before the last dot segment).
+func modulePrefix(qn string) string {
+ if idx := strings.LastIndex(qn, "."); idx >= 0 {
+ return qn[:idx]
+ }
+ return qn
+}
+
+// isImportReachable checks if the candidate's module prefix appears anywhere
+// in the caller's import map values.
+func isImportReachable(candidateQN string, importMap map[string]string) bool {
+ candidateModule := modulePrefix(candidateQN)
+ for _, importedQN := range importMap {
+ if strings.HasPrefix(candidateModule, importedQN) || strings.HasPrefix(importedQN, candidateModule) {
+ return true
+ }
+ }
+ return false
+}
+
+// filterImportReachable returns only candidates reachable via the import map.
+// Returns the original slice if importMap is nil or filtering eliminates everything.
+func filterImportReachable(candidates []string, importMap map[string]string) []string {
+ if importMap == nil {
+ return candidates
+ }
+ var filtered []string
+ for _, c := range candidates {
+ if isImportReachable(c, importMap) {
+ filtered = append(filtered, c)
+ }
+ }
+ return filtered
+}
+
+// confidenceBand returns a human-readable band label for a confidence score.
+func confidenceBand(score float64) string {
+ switch {
+ case score >= 0.7:
+ return "high"
+ case score >= 0.45:
+ return "medium"
+ default:
+ return "speculative"
+ }
+}
diff --git a/internal/pipeline/resolver_test.go b/internal/pipeline/resolver_test.go
index 8b3f2f624..c2abd53fb 100644
--- a/internal/pipeline/resolver_test.go
+++ b/internal/pipeline/resolver_test.go
@@ -1,6 +1,9 @@
package pipeline
-import "testing"
+import (
+ "math"
+ "testing"
+)
func TestFuzzyResolve_SingleCandidate(t *testing.T) {
reg := NewFunctionRegistry()
@@ -9,17 +12,17 @@ func TestFuzzyResolve_SingleCandidate(t *testing.T) {
// Normal resolve with no import map should find unique name
result := reg.Resolve("CreateOrder", "svcC.caller", nil)
- if result != "svcA.handlers.CreateOrder" {
- t.Errorf("Resolve: expected svcA.handlers.CreateOrder, got %s", result)
+ if result.QualifiedName != "svcA.handlers.CreateOrder" {
+ t.Errorf("Resolve: expected svcA.handlers.CreateOrder, got %s", result.QualifiedName)
}
// FuzzyResolve should find by simple name even with unknown prefix
- fuzzyResult, ok := reg.FuzzyResolve("unknownPkg.CreateOrder", "svcC.caller")
+ fuzzyResult, ok := reg.FuzzyResolve("unknownPkg.CreateOrder", "svcC.caller", nil)
if !ok {
t.Fatal("expected fuzzy match")
}
- if fuzzyResult != "svcA.handlers.CreateOrder" {
- t.Errorf("expected svcA.handlers.CreateOrder, got %s", fuzzyResult)
+ if fuzzyResult.QualifiedName != "svcA.handlers.CreateOrder" {
+ t.Errorf("expected svcA.handlers.CreateOrder, got %s", fuzzyResult.QualifiedName)
}
}
@@ -27,7 +30,7 @@ func TestFuzzyResolve_NonExistentName(t *testing.T) {
reg := NewFunctionRegistry()
reg.Register("CreateOrder", "svcA.handlers.CreateOrder", "Function")
- _, ok := reg.FuzzyResolve("NonExistent", "svcC.caller")
+ _, ok := reg.FuzzyResolve("NonExistent", "svcC.caller", nil)
if ok {
t.Fatal("expected no fuzzy match for non-existent name")
}
@@ -39,21 +42,21 @@ func TestFuzzyResolve_MultipleCandidates_BestByDistance(t *testing.T) {
reg.Register("Process", "svcB.handlers.Process", "Function")
// Caller is in svcA — should prefer svcA.handlers.Process
- fuzzyResult, ok := reg.FuzzyResolve("unknown.Process", "svcA.other")
+ fuzzyResult, ok := reg.FuzzyResolve("unknown.Process", "svcA.other", nil)
if !ok {
t.Fatal("expected fuzzy match")
}
- if fuzzyResult != "svcA.handlers.Process" {
- t.Errorf("expected svcA.handlers.Process, got %s", fuzzyResult)
+ if fuzzyResult.QualifiedName != "svcA.handlers.Process" {
+ t.Errorf("expected svcA.handlers.Process, got %s", fuzzyResult.QualifiedName)
}
// Caller is in svcB — should prefer svcB.handlers.Process
- fuzzyResult, ok = reg.FuzzyResolve("unknown.Process", "svcB.other")
+ fuzzyResult, ok = reg.FuzzyResolve("unknown.Process", "svcB.other", nil)
if !ok {
t.Fatal("expected fuzzy match")
}
- if fuzzyResult != "svcB.handlers.Process" {
- t.Errorf("expected svcB.handlers.Process, got %s", fuzzyResult)
+ if fuzzyResult.QualifiedName != "svcB.handlers.Process" {
+ t.Errorf("expected svcB.handlers.Process, got %s", fuzzyResult.QualifiedName)
}
}
@@ -62,12 +65,12 @@ func TestFuzzyResolve_SimpleNameExtraction(t *testing.T) {
reg.Register("DoWork", "myproject.utils.DoWork", "Function")
// Deeply qualified callee — should extract "DoWork" as simple name
- fuzzyResult, ok := reg.FuzzyResolve("some.deep.module.DoWork", "myproject.caller")
+ fuzzyResult, ok := reg.FuzzyResolve("some.deep.module.DoWork", "myproject.caller", nil)
if !ok {
t.Fatal("expected fuzzy match")
}
- if fuzzyResult != "myproject.utils.DoWork" {
- t.Errorf("expected myproject.utils.DoWork, got %s", fuzzyResult)
+ if fuzzyResult.QualifiedName != "myproject.utils.DoWork" {
+ t.Errorf("expected myproject.utils.DoWork, got %s", fuzzyResult.QualifiedName)
}
}
@@ -75,7 +78,7 @@ func TestFuzzyResolve_NoMatchForBareName(t *testing.T) {
reg := NewFunctionRegistry()
// Register nothing
- _, ok := reg.FuzzyResolve("SomeFunc", "myproject.caller")
+ _, ok := reg.FuzzyResolve("SomeFunc", "myproject.caller", nil)
if ok {
t.Fatal("expected no fuzzy match on empty registry")
}
@@ -99,3 +102,199 @@ func TestRegistryExists(t *testing.T) {
t.Error("expected empty string to not exist")
}
}
+
+// --- Phase 1: Confidence scoring tests ---
+
+func assertConfidence(t *testing.T, label string, got, want float64) {
+ t.Helper()
+ if math.Abs(got-want) > 0.01 {
+ t.Errorf("%s: confidence = %.2f, want %.2f", label, got, want)
+ }
+}
+
+func TestResolveConfidence_ImportMap(t *testing.T) {
+ reg := NewFunctionRegistry()
+ reg.Register("Foo", "proj.other.Foo", "Function")
+
+ imports := map[string]string{"other": "proj.other"}
+ result := reg.Resolve("other.Foo", "proj.pkg", imports)
+ if result.QualifiedName != "proj.other.Foo" {
+ t.Fatalf("expected proj.other.Foo, got %s", result.QualifiedName)
+ }
+ assertConfidence(t, "import_map", result.Confidence, 0.95)
+ if result.Strategy != "import_map" {
+ t.Errorf("strategy = %s, want import_map", result.Strategy)
+ }
+}
+
+func TestResolveConfidence_ImportMapSuffix(t *testing.T) {
+ reg := NewFunctionRegistry()
+ reg.Register("Foo", "proj.other.sub.Foo", "Function")
+
+ imports := map[string]string{"other": "proj.other"}
+ result := reg.Resolve("other.Foo", "proj.pkg", imports)
+ if result.QualifiedName != "proj.other.sub.Foo" {
+ t.Fatalf("expected proj.other.sub.Foo, got %s", result.QualifiedName)
+ }
+ assertConfidence(t, "import_map_suffix", result.Confidence, 0.85)
+ if result.Strategy != "import_map_suffix" {
+ t.Errorf("strategy = %s, want import_map_suffix", result.Strategy)
+ }
+}
+
+func TestResolveConfidence_SameModule(t *testing.T) {
+ reg := NewFunctionRegistry()
+ reg.Register("Foo", "proj.pkg.Foo", "Function")
+
+ result := reg.Resolve("Foo", "proj.pkg", nil)
+ if result.QualifiedName != "proj.pkg.Foo" {
+ t.Fatalf("expected proj.pkg.Foo, got %s", result.QualifiedName)
+ }
+ assertConfidence(t, "same_module", result.Confidence, 0.90)
+ if result.Strategy != "same_module" {
+ t.Errorf("strategy = %s, want same_module", result.Strategy)
+ }
+}
+
+func TestResolveConfidence_UniqueName(t *testing.T) {
+ reg := NewFunctionRegistry()
+ reg.Register("Bar", "proj.pkg.Bar", "Function")
+
+ result := reg.Resolve("Bar", "proj.unrelated", nil)
+ if result.QualifiedName != "proj.pkg.Bar" {
+ t.Fatalf("expected proj.pkg.Bar, got %s", result.QualifiedName)
+ }
+ assertConfidence(t, "unique_name", result.Confidence, 0.75)
+ if result.Strategy != "unique_name" {
+ t.Errorf("strategy = %s, want unique_name", result.Strategy)
+ }
+}
+
+func TestResolveConfidence_SuffixMatch(t *testing.T) {
+ reg := NewFunctionRegistry()
+ reg.Register("Process", "proj.svcA.Process", "Function")
+ reg.Register("Process", "proj.svcB.Process", "Function")
+
+ result := reg.Resolve("Process", "proj.svcA.caller", nil)
+ if result.QualifiedName != "proj.svcA.Process" {
+ t.Fatalf("expected proj.svcA.Process, got %s", result.QualifiedName)
+ }
+ assertConfidence(t, "suffix_match", result.Confidence, 0.55)
+ if result.Strategy != "suffix_match" {
+ t.Errorf("strategy = %s, want suffix_match", result.Strategy)
+ }
+}
+
+func TestFuzzyResolveConfidence_Single(t *testing.T) {
+ reg := NewFunctionRegistry()
+ reg.Register("Handler", "proj.svc.Handler", "Function")
+
+ result, ok := reg.FuzzyResolve("unknownPkg.Handler", "proj.caller", nil)
+ if !ok {
+ t.Fatal("expected fuzzy match")
+ }
+ assertConfidence(t, "fuzzy_single", result.Confidence, 0.40)
+ if result.Strategy != "fuzzy" {
+ t.Errorf("strategy = %s, want fuzzy", result.Strategy)
+ }
+}
+
+func TestFuzzyResolveConfidence_Distance(t *testing.T) {
+ reg := NewFunctionRegistry()
+ reg.Register("Process", "proj.svcA.Process", "Function")
+ reg.Register("Process", "proj.svcB.Process", "Function")
+
+ result, ok := reg.FuzzyResolve("unknownPkg.Process", "proj.svcA.other", nil)
+ if !ok {
+ t.Fatal("expected fuzzy match")
+ }
+ assertConfidence(t, "fuzzy_distance", result.Confidence, 0.30)
+ if result.Strategy != "fuzzy" {
+ t.Errorf("strategy = %s, want fuzzy", result.Strategy)
+ }
+}
+
+// --- Phase 3: Negative import evidence tests ---
+
+func TestNegativeImportEvidence_RejectsUnimported(t *testing.T) {
+ reg := NewFunctionRegistry()
+ reg.Register("Process", "proj.billing.Process", "Function")
+ reg.Register("Process", "proj.handler.Process", "Function")
+
+ // Import only handler's module — should prefer handler
+ imports := map[string]string{"handler": "proj.handler"}
+ result := reg.Resolve("Process", "proj.caller", imports)
+ if result.QualifiedName != "proj.handler.Process" {
+ t.Errorf("expected proj.handler.Process, got %s", result.QualifiedName)
+ }
+}
+
+func TestNegativeImportEvidence_FuzzyPenalty(t *testing.T) {
+ reg := NewFunctionRegistry()
+ reg.Register("Handler", "proj.billing.Handler", "Function")
+
+ // No import for billing module — confidence should be halved
+ imports := map[string]string{"other": "proj.other"}
+ result, ok := reg.FuzzyResolve("unknown.Handler", "proj.caller", imports)
+ if !ok {
+ t.Fatal("expected fuzzy match")
+ }
+ // 0.40 * 0.5 = 0.20 (penalty for unreachable import)
+ assertConfidence(t, "fuzzy_penalty", result.Confidence, 0.20)
+}
+
+func TestNegativeImportEvidence_NoImportMapPassthrough(t *testing.T) {
+ reg := NewFunctionRegistry()
+ reg.Register("Handler", "proj.billing.Handler", "Function")
+
+ // nil import map — no filtering, full confidence
+ result, ok := reg.FuzzyResolve("unknown.Handler", "proj.caller", nil)
+ if !ok {
+ t.Fatal("expected fuzzy match")
+ }
+ assertConfidence(t, "no_importmap", result.Confidence, 0.40)
+}
+
+func TestConfidenceBand(t *testing.T) {
+ tests := []struct {
+ score float64
+ want string
+ }{
+ {0.95, "high"},
+ {0.70, "high"},
+ {0.55, "medium"},
+ {0.45, "medium"},
+ {0.40, "speculative"},
+ {0.20, "speculative"},
+ }
+ for _, tt := range tests {
+ got := confidenceBand(tt.score)
+ if got != tt.want {
+ t.Errorf("confidenceBand(%.2f) = %s, want %s", tt.score, got, tt.want)
+ }
+ }
+}
+
+func TestIsImportReachable(t *testing.T) {
+ imports := map[string]string{
+ "handler": "proj.handler",
+ "utils": "proj.shared.utils",
+ }
+
+ tests := []struct {
+ candidate string
+ want bool
+ }{
+ {"proj.handler.Process", true},
+ {"proj.handler.sub.Process", true},
+ {"proj.shared.utils.Helper", true},
+ {"proj.billing.Process", false},
+ {"unrelated.pkg.Func", false},
+ }
+ for _, tt := range tests {
+ got := isImportReachable(tt.candidate, imports)
+ if got != tt.want {
+ t.Errorf("isImportReachable(%s) = %v, want %v", tt.candidate, got, tt.want)
+ }
+ }
+}
diff --git a/internal/pipeline/typeinfer.go b/internal/pipeline/typeinfer.go
index 5014d5d1c..f18db3ff0 100644
--- a/internal/pipeline/typeinfer.go
+++ b/internal/pipeline/typeinfer.go
@@ -14,10 +14,16 @@ import (
// Key: variable name, Value: class/type QN in the registry.
type TypeMap map[string]string
+// ReturnTypeMap maps function QN → return type QN (class/struct the function returns).
+type ReturnTypeMap map[string]string
+
// inferTypes walks the AST looking for variable assignments where the value
// is a constructor call (class instantiation) and builds a mapping from
// variable name to the class QN. This enables resolving method calls like
// `obj.method()` to `ClassName.method`.
+//
+// If returnTypes is non-nil, also infers types from calls to functions with
+// known return types (Phase 2: return type propagation).
func inferTypes(
root *tree_sitter.Node,
source []byte,
@@ -25,6 +31,7 @@ func inferTypes(
registry *FunctionRegistry,
moduleQN string,
importMap map[string]string,
+ returnTypes ReturnTypeMap,
) TypeMap {
types := make(TypeMap)
@@ -33,11 +40,171 @@ func inferTypes(
inferPythonTypes(root, source, registry, moduleQN, importMap, types)
case lang.Go:
inferGoTypes(root, source, registry, moduleQN, importMap, types)
+ // Tier 1: statically typed languages
+ case lang.TypeScript, lang.TSX:
+ inferTypeScriptTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.Java:
+ inferJavaTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.CSharp:
+ inferCSharpTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.Kotlin:
+ inferKotlinTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.Scala:
+ inferScalaTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.Rust:
+ inferRustTypes(root, source, registry, moduleQN, importMap, types)
+ // Tier 2: dynamic/mixed languages
+ case lang.CPP:
+ inferCPPTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.PHP:
+ inferPHPTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.Ruby:
+ inferRubyTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.JavaScript:
+ inferJavaScriptTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.Zig:
+ inferZigTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.Elixir:
+ inferElixirTypes(root, source, registry, moduleQN, importMap, types)
+ case lang.C:
+ inferCTypes(root, source, registry, moduleQN, importMap, types)
+ }
+
+ // Phase 2: return type propagation — for assignments where RHS is a call
+ // to a function with known return type, map the variable to that type
+ if len(returnTypes) > 0 {
+ inferReturnTypes(root, source, language, registry, moduleQN, importMap, returnTypes, types)
}
return types
}
+// inferReturnTypes augments the type map with return-type-based inference.
+// For assignments like `result = someFunc()` where `someFunc` has a known
+// return type, maps `result` to the return type QN.
+func inferReturnTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ language lang.Language,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ returnTypes ReturnTypeMap,
+ types TypeMap,
+) {
+ callTypes := map[string]bool{
+ "call": true, "call_expression": true, "function_call": true,
+ "method_invocation": true, "invocation_expression": true,
+ }
+ assignTypes := map[string]bool{
+ "assignment": true, "short_var_declaration": true,
+ "variable_declarator": true, "local_variable_declaration": true,
+ "let_declaration": true, "property_declaration": true,
+ "val_definition": true,
+ }
+
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if !assignTypes[node.Kind()] {
+ return true
+ }
+
+ varName := extractAssignmentVarName(node, source, language)
+ if varName == "" || types[varName] != "" {
+ return false // already inferred by constructor matching
+ }
+
+ // Find the call expression on the RHS
+ callNode := findCallOnRHS(node, source, callTypes)
+ if callNode == nil {
+ return false
+ }
+
+ calleeName := extractCalleeForTypeInfer(callNode, source)
+ if calleeName == "" {
+ return false
+ }
+
+ // Resolve the callee to a function QN
+ result := registry.Resolve(calleeName, moduleQN, importMap)
+ if result.QualifiedName == "" {
+ return false
+ }
+
+ // Check if this function has a known return type
+ if retTypeQN, ok := returnTypes[result.QualifiedName]; ok {
+ types[varName] = retTypeQN
+ }
+
+ return false
+ })
+}
+
+// extractAssignmentVarName extracts the variable name from an assignment node.
+func extractAssignmentVarName(node *tree_sitter.Node, source []byte, language lang.Language) string {
+ switch node.Kind() {
+ case "assignment":
+ leftNode := node.ChildByFieldName("left")
+ if leftNode != nil && leftNode.Kind() == "identifier" {
+ return parser.NodeText(leftNode, source)
+ }
+ case "short_var_declaration":
+ leftNode := node.ChildByFieldName("left")
+ if leftNode != nil {
+ return extractFirstIdentifier(leftNode, source)
+ }
+ case "variable_declarator":
+ nameNode := node.ChildByFieldName("name")
+ if nameNode != nil && (nameNode.Kind() == "identifier" || nameNode.Kind() == "simple_identifier") {
+ return parser.NodeText(nameNode, source)
+ }
+ case "let_declaration":
+ patNode := node.ChildByFieldName("pattern")
+ if patNode != nil {
+ return parser.NodeText(patNode, source)
+ }
+ case "val_definition":
+ patNode := node.ChildByFieldName("pattern")
+ if patNode != nil {
+ return parser.NodeText(patNode, source)
+ }
+ case "property_declaration":
+ varDecl := findChildByKind(node, "variable_declaration")
+ if varDecl != nil {
+ ident := findChildByKind(varDecl, "simple_identifier")
+ if ident == nil {
+ ident = findChildByKind(varDecl, "identifier")
+ }
+ if ident != nil {
+ return parser.NodeText(ident, source)
+ }
+ }
+ }
+ _ = language
+ return ""
+}
+
+// findCallOnRHS finds a call expression on the right-hand side of an assignment.
+func findCallOnRHS(node *tree_sitter.Node, source []byte, callTypes map[string]bool) *tree_sitter.Node {
+ // Try standard field names
+ for _, field := range []string{"right", "value"} {
+ rhs := node.ChildByFieldName(field)
+ if rhs != nil {
+ if callTypes[rhs.Kind()] {
+ return rhs
+ }
+ // Go expression_list wrapper
+ if rhs.Kind() == "expression_list" && rhs.NamedChildCount() > 0 {
+ first := rhs.NamedChild(0)
+ if first != nil && callTypes[first.Kind()] {
+ return first
+ }
+ }
+ }
+ }
+ _ = source
+ return nil
+}
+
// inferPythonTypes handles Python patterns like:
//
// x = ClassName(args)
@@ -195,15 +362,15 @@ func inferGoVarDecl(
// resolveAsClass checks if a name refers to a Class/Type node in the registry.
func resolveAsClass(name string, registry *FunctionRegistry, moduleQN string, importMap map[string]string) string {
- qn := registry.Resolve(name, moduleQN, importMap)
- if qn == "" {
+ result := registry.Resolve(name, moduleQN, importMap)
+ if result.QualifiedName == "" {
return ""
}
registry.mu.RLock()
defer registry.mu.RUnlock()
- label, exists := registry.exact[qn]
+ label, exists := registry.exact[result.QualifiedName]
if !exists {
return ""
}
@@ -211,7 +378,7 @@ func resolveAsClass(name string, registry *FunctionRegistry, moduleQN string, im
// Only return if it's a class-like node
switch label {
case "Class", "Type", "Interface", "Enum":
- return qn
+ return result.QualifiedName
}
return ""
}
diff --git a/internal/pipeline/typeinfer_dynamic.go b/internal/pipeline/typeinfer_dynamic.go
new file mode 100644
index 000000000..ea17458db
--- /dev/null
+++ b/internal/pipeline/typeinfer_dynamic.go
@@ -0,0 +1,316 @@
+package pipeline
+
+import (
+ "strings"
+
+ tree_sitter "github.com/tree-sitter/go-tree-sitter"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/parser"
+)
+
+// inferCPPTypes handles C++ patterns:
+//
+// Type x(args); (direct initialization)
+// Type x{...}; (brace initialization)
+// auto x = Type(args); (auto with constructor)
+func inferCPPTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "declaration" {
+ return true
+ }
+
+ typeNode := node.ChildByFieldName("type")
+ if typeNode == nil {
+ return false
+ }
+
+ initDecl := findChildByKind(node, "init_declarator")
+ if initDecl == nil {
+ return false
+ }
+
+ declNode := initDecl.ChildByFieldName("declarator")
+ if declNode == nil {
+ return false
+ }
+ varName := parser.NodeText(declNode, source)
+ // Strip pointer/ref: *x, &x
+ varName = strings.TrimLeft(varName, "*&")
+
+ typeName := extractSimpleTypeName(typeNode, source)
+ if typeName == "auto" {
+ // Look at RHS for constructor call
+ valueNode := initDecl.ChildByFieldName("value")
+ if valueNode != nil && valueNode.Kind() == "call_expression" {
+ funcNode := valueNode.ChildByFieldName("function")
+ if funcNode != nil {
+ typeName = parser.NodeText(funcNode, source)
+ }
+ }
+ }
+
+ if typeName != "" && typeName != "auto" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+ }
+
+ return false
+ })
+}
+
+// inferPHPTypes handles PHP patterns:
+//
+// $x = new ClassName()
+func inferPHPTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "assignment_expression" {
+ return true
+ }
+
+ leftNode := node.ChildByFieldName("left")
+ rightNode := node.ChildByFieldName("right")
+ if leftNode == nil || rightNode == nil {
+ return false
+ }
+
+ if leftNode.Kind() != "variable_name" {
+ return false
+ }
+ varName := extractPHPVarNameForInfer(leftNode, source)
+ if varName == "" {
+ return false
+ }
+
+ if rightNode.Kind() == "object_creation_expression" {
+ typeName := extractNewExpressionName(rightNode, source)
+ if typeName != "" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+ }
+ }
+
+ return false
+ })
+}
+
+// inferRubyTypes handles Ruby patterns:
+//
+// x = ClassName.new
+func inferRubyTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "assignment" {
+ return true
+ }
+
+ leftNode := node.ChildByFieldName("left")
+ rightNode := node.ChildByFieldName("right")
+ if leftNode == nil || rightNode == nil {
+ return false
+ }
+
+ if leftNode.Kind() != "identifier" {
+ return false
+ }
+ varName := parser.NodeText(leftNode, source)
+
+ // Check for ClassName.new pattern (call with method == "new")
+ if typeName := extractRubyNewType(rightNode, source); typeName != "" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+ }
+
+ return false
+ })
+}
+
+// inferJavaScriptTypes handles JavaScript patterns:
+//
+// const x = new ClassName()
+func inferJavaScriptTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "variable_declarator" {
+ return true
+ }
+
+ nameNode := node.ChildByFieldName("name")
+ if nameNode == nil || nameNode.Kind() != "identifier" {
+ return false
+ }
+ varName := parser.NodeText(nameNode, source)
+
+ valueNode := node.ChildByFieldName("value")
+ if valueNode != nil && valueNode.Kind() == "new_expression" {
+ typeName := extractNewExpressionName(valueNode, source)
+ if typeName != "" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+ }
+ }
+
+ return false
+ })
+}
+
+// inferZigTypes handles Zig patterns:
+//
+// var x: Type = ...
+// const x: Type = ...
+func inferZigTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "VarDecl" {
+ return true
+ }
+
+ nameNode := node.ChildByFieldName("name")
+ if nameNode == nil {
+ return false
+ }
+ varName := parser.NodeText(nameNode, source)
+
+ typeNode := node.ChildByFieldName("type_expr")
+ if typeNode != nil {
+ typeName := extractSimpleTypeName(typeNode, source)
+ if typeName != "" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+ }
+ }
+
+ return false
+ })
+}
+
+// inferElixirTypes handles Elixir patterns:
+//
+// x = %StructName{key: val}
+func inferElixirTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ _ *FunctionRegistry,
+ _ string,
+ _ map[string]string,
+ _ TypeMap,
+) {
+ // Elixir struct instantiation uses %ModuleName{} syntax.
+ // Tree-sitter-elixir represents this as a binary_operator (=) with a
+ // map/struct on the RHS. The struct detection is complex and type dispatch
+ // is uncommon in Elixir's functional style. Placeholder for future work.
+ _ = root
+ _ = source
+}
+
+// inferCTypes handles C patterns:
+//
+// struct Type x;
+// Type* x = ...;
+func inferCTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "declaration" {
+ return true
+ }
+
+ typeNode := node.ChildByFieldName("type")
+ if typeNode == nil {
+ return false
+ }
+
+ var typeName string
+ if typeNode.Kind() == "struct_specifier" {
+ nameChild := typeNode.ChildByFieldName("name")
+ if nameChild != nil {
+ typeName = parser.NodeText(nameChild, source)
+ }
+ } else {
+ typeName = extractSimpleTypeName(typeNode, source)
+ }
+ if typeName == "" {
+ return false
+ }
+
+ // Extract variable name from declarator
+ declNode := node.ChildByFieldName("declarator")
+ if declNode == nil {
+ return false
+ }
+ varName := parser.NodeText(declNode, source)
+ varName = strings.TrimLeft(varName, "*")
+
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+
+ return false
+ })
+}
+
+// extractRubyNewType extracts the class name from a Ruby ClassName.new call.
+func extractRubyNewType(callNode *tree_sitter.Node, source []byte) string {
+ if callNode.Kind() != "call" {
+ return ""
+ }
+ methodNode := callNode.ChildByFieldName("method")
+ receiverNode := callNode.ChildByFieldName("receiver")
+ if methodNode == nil || receiverNode == nil {
+ return ""
+ }
+ if parser.NodeText(methodNode, source) != "new" {
+ return ""
+ }
+ return parser.NodeText(receiverNode, source)
+}
+
+// extractPHPVarNameForInfer extracts the name from a PHP variable_name node for type inference.
+func extractPHPVarNameForInfer(node *tree_sitter.Node, source []byte) string {
+ if node.Kind() != "variable_name" {
+ return ""
+ }
+ text := parser.NodeText(node, source)
+ return strings.TrimPrefix(text, "$")
+}
diff --git a/internal/pipeline/typeinfer_typed.go b/internal/pipeline/typeinfer_typed.go
new file mode 100644
index 000000000..296c53787
--- /dev/null
+++ b/internal/pipeline/typeinfer_typed.go
@@ -0,0 +1,469 @@
+package pipeline
+
+import (
+ "strings"
+
+ tree_sitter "github.com/tree-sitter/go-tree-sitter"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/parser"
+)
+
+// inferTypeScriptTypes handles TypeScript/TSX patterns:
+//
+// const x: ClassName = ... (type annotation)
+// const x = new ClassName() (new expression)
+// let x: ClassName (type annotation without value)
+func inferTypeScriptTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "variable_declarator" {
+ return true
+ }
+
+ nameNode := node.ChildByFieldName("name")
+ if nameNode == nil || nameNode.Kind() != "identifier" {
+ return false
+ }
+ varName := parser.NodeText(nameNode, source)
+
+ // Try type annotation first
+ typeNode := node.ChildByFieldName("type")
+ if typeNode != nil {
+ typeName := extractTypeAnnotationName(typeNode, source)
+ if typeName != "" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ return false
+ }
+ }
+ }
+
+ // Try new expression
+ valueNode := node.ChildByFieldName("value")
+ if valueNode != nil && valueNode.Kind() == "new_expression" {
+ typeName := extractNewExpressionName(valueNode, source)
+ if typeName != "" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ return false
+ }
+ }
+ }
+
+ return false
+ })
+}
+
+// inferJavaTypes handles Java patterns:
+//
+// ClassName x = new ClassName() (explicit type declaration)
+// ClassName x = factory() (type is explicit regardless of RHS)
+func inferJavaTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "local_variable_declaration" {
+ return true
+ }
+
+ typeNode := node.ChildByFieldName("type")
+ if typeNode == nil {
+ return false
+ }
+ typeName := extractSimpleTypeName(typeNode, source)
+ if typeName == "" {
+ return false
+ }
+
+ // Walk variable_declarator children
+ for i := uint(0); i < node.NamedChildCount(); i++ {
+ child := node.NamedChild(i)
+ if child != nil && child.Kind() == "variable_declarator" {
+ declNameNode := child.ChildByFieldName("name")
+ if declNameNode != nil {
+ varName := parser.NodeText(declNameNode, source)
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+ }
+ }
+ }
+
+ return false
+ })
+}
+
+// inferCSharpTypes handles C# patterns:
+//
+// ClassName x = new ClassName() (explicit type)
+// var x = new ClassName() (var with new expression)
+func inferCSharpTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "local_declaration_statement" {
+ return true
+ }
+
+ varDecl := findChildByKind(node, "variable_declaration")
+ if varDecl == nil {
+ return false
+ }
+
+ typeNode := varDecl.ChildByFieldName("type")
+ if typeNode == nil {
+ return false
+ }
+ explicitType := extractSimpleTypeName(typeNode, source)
+
+ inferCSharpVarDeclarators(varDecl, source, explicitType, registry, moduleQN, importMap, types)
+
+ return false
+ })
+}
+
+// inferKotlinTypes handles Kotlin patterns:
+//
+// val x: ClassName = ... (type annotation)
+// val x = ClassName() (constructor call — no "new" keyword)
+func inferKotlinTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "property_declaration" {
+ return true
+ }
+
+ varDecl := findChildByKind(node, "variable_declaration")
+ if varDecl == nil {
+ return false
+ }
+ nameNode := findChildByKind(varDecl, "simple_identifier")
+ if nameNode == nil {
+ return false
+ }
+ varName := parser.NodeText(nameNode, source)
+
+ // Try type annotation on variable_declaration
+ typeNode := findChildByKind(varDecl, "user_type")
+ if typeNode != nil {
+ typeName := extractSimpleTypeName(typeNode, source)
+ if typeName != "" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ return false
+ }
+ }
+ }
+
+ // Try call expression (constructor without "new")
+ valueNode := findKotlinPropertyValue(node, source)
+ if valueNode != nil && valueNode.Kind() == "call_expression" {
+ calleeName := extractCalleeForTypeInfer(valueNode, source)
+ if calleeName != "" {
+ if classQN := resolveAsClass(calleeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+ }
+ }
+
+ return false
+ })
+}
+
+// inferScalaTypes handles Scala patterns:
+//
+// val x: ClassName = ... (type ascription)
+// val x = ClassName() (constructor call)
+func inferScalaTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "val_definition" {
+ return true
+ }
+
+ patNode := node.ChildByFieldName("pattern")
+ if patNode == nil {
+ return false
+ }
+ varName := parser.NodeText(patNode, source)
+
+ // Try type ascription — look for ":" followed by type
+ for i := uint(0); i < node.ChildCount(); i++ {
+ child := node.Child(i)
+ if child == nil {
+ continue
+ }
+ if child.Kind() == "type_identifier" {
+ typeName := parser.NodeText(child, source)
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ return false
+ }
+ }
+ }
+
+ // Try constructor call
+ valueNode := node.ChildByFieldName("value")
+ if valueNode != nil && valueNode.Kind() == "call_expression" {
+ funcNode := valueNode.ChildByFieldName("function")
+ if funcNode != nil {
+ typeName := parser.NodeText(funcNode, source)
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+ }
+ }
+
+ return false
+ })
+}
+
+// inferRustTypes handles Rust patterns:
+//
+// let x: Type = ... (type annotation)
+// let x = Type { ... } (struct literal)
+// let x = Type::new() (scoped constructor)
+func inferRustTypes(
+ root *tree_sitter.Node,
+ source []byte,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ parser.Walk(root, func(node *tree_sitter.Node) bool {
+ if node.Kind() != "let_declaration" {
+ return true
+ }
+
+ patNode := node.ChildByFieldName("pattern")
+ if patNode == nil {
+ return false
+ }
+ varName := parser.NodeText(patNode, source)
+ if varName == "_" {
+ return false
+ }
+
+ // Try explicit type annotation
+ typeNode := node.ChildByFieldName("type")
+ if typeNode != nil {
+ typeName := extractSimpleTypeName(typeNode, source)
+ typeName = strings.TrimPrefix(typeName, "&")
+ typeName = strings.TrimPrefix(typeName, "&mut ")
+ if typeName != "" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ return false
+ }
+ }
+ }
+
+ // Try struct literal or scoped call
+ valueNode := node.ChildByFieldName("value")
+ if valueNode != nil {
+ typeName := extractRustValueType(valueNode, source)
+ if typeName != "" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+ }
+ }
+
+ return false
+ })
+}
+
+// --- Shared helpers ---
+
+// extractTypeAnnotationName extracts a simple type name from a type annotation node.
+// Handles: type_annotation (TS), type_identifier, generic_type.
+func extractTypeAnnotationName(node *tree_sitter.Node, source []byte) string {
+ if node == nil {
+ return ""
+ }
+ // type_annotation wraps the actual type
+ if node.Kind() == "type_annotation" {
+ for i := uint(0); i < node.NamedChildCount(); i++ {
+ child := node.NamedChild(i)
+ if child != nil {
+ return extractTypeAnnotationName(child, source)
+ }
+ }
+ return ""
+ }
+ // generic_type: take the type name before <...>
+ if node.Kind() == "generic_type" {
+ nameNode := node.NamedChild(0)
+ if nameNode != nil {
+ return parser.NodeText(nameNode, source)
+ }
+ return ""
+ }
+ // Direct type identifiers
+ switch node.Kind() {
+ case "type_identifier", "identifier", "simple_identifier":
+ return parser.NodeText(node, source)
+ }
+ return ""
+}
+
+// extractNewExpressionName extracts the class name from a `new ClassName(args)` node.
+func extractNewExpressionName(node *tree_sitter.Node, source []byte) string {
+ if node == nil {
+ return ""
+ }
+ // new_expression / object_creation_expression
+ for i := uint(0); i < node.NamedChildCount(); i++ {
+ child := node.NamedChild(i)
+ if child == nil {
+ continue
+ }
+ switch child.Kind() {
+ case "identifier", "type_identifier", "simple_identifier":
+ return parser.NodeText(child, source)
+ case "generic_type":
+ nameNode := child.NamedChild(0)
+ if nameNode != nil {
+ return parser.NodeText(nameNode, source)
+ }
+ case "member_expression", "scoped_identifier":
+ return parser.NodeText(child, source)
+ }
+ }
+ return ""
+}
+
+// extractSimpleTypeName extracts a simple (non-generic) type name.
+func extractSimpleTypeName(node *tree_sitter.Node, source []byte) string {
+ if node == nil {
+ return ""
+ }
+ switch node.Kind() {
+ case "type_identifier", "identifier", "simple_identifier":
+ return parser.NodeText(node, source)
+ case "generic_type":
+ if node.NamedChildCount() > 0 {
+ return parser.NodeText(node.NamedChild(0), source)
+ }
+ case "user_type":
+ // Kotlin user_type — find the simple_identifier child
+ ident := findChildByKind(node, "simple_identifier")
+ if ident != nil {
+ return parser.NodeText(ident, source)
+ }
+ // Fall back to first named child
+ if node.NamedChildCount() > 0 {
+ return parser.NodeText(node.NamedChild(0), source)
+ }
+ }
+ return parser.NodeText(node, source)
+}
+
+// extractRustValueType extracts a type name from Rust value expressions.
+// Handles struct literals (Type { ... }) and scoped calls (Type::new()).
+func extractRustValueType(node *tree_sitter.Node, source []byte) string {
+ switch node.Kind() {
+ case "struct_expression":
+ nameNode := node.ChildByFieldName("name")
+ if nameNode != nil {
+ return parser.NodeText(nameNode, source)
+ }
+ case "call_expression":
+ funcNode := node.ChildByFieldName("function")
+ if funcNode != nil && funcNode.Kind() == "scoped_identifier" {
+ pathNode := funcNode.ChildByFieldName("path")
+ if pathNode != nil {
+ return parser.NodeText(pathNode, source)
+ }
+ }
+ }
+ return ""
+}
+
+// findKotlinPropertyValue finds the value expression in a Kotlin property_declaration.
+// The value comes after the "=" token.
+func findKotlinPropertyValue(node *tree_sitter.Node, source []byte) *tree_sitter.Node {
+ foundEquals := false
+ for i := uint(0); i < node.ChildCount(); i++ {
+ child := node.Child(i)
+ if child == nil {
+ continue
+ }
+ if parser.NodeText(child, source) == "=" {
+ foundEquals = true
+ continue
+ }
+ if foundEquals && child.IsNamed() {
+ return child
+ }
+ }
+ return nil
+}
+
+// inferCSharpVarDeclarators processes variable declarators within a C# variable_declaration.
+func inferCSharpVarDeclarators(
+ varDecl *tree_sitter.Node,
+ source []byte,
+ explicitType string,
+ registry *FunctionRegistry,
+ moduleQN string,
+ importMap map[string]string,
+ types TypeMap,
+) {
+ for i := uint(0); i < varDecl.NamedChildCount(); i++ {
+ child := varDecl.NamedChild(i)
+ if child == nil || child.Kind() != "variable_declarator" {
+ continue
+ }
+ declNameNode := child.ChildByFieldName("name")
+ if declNameNode == nil {
+ continue
+ }
+ varName := parser.NodeText(declNameNode, source)
+
+ typeName := explicitType
+ if typeName == "var" {
+ valueNode := findValueAfterEquals(child)
+ if valueNode != nil && valueNode.Kind() == "object_creation_expression" {
+ typeName = extractNewExpressionName(valueNode, source)
+ } else {
+ typeName = ""
+ }
+ }
+
+ if typeName != "" {
+ if classQN := resolveAsClass(typeName, registry, moduleQN, importMap); classQN != "" {
+ types[varName] = classQN
+ }
+ }
+ }
+}
diff --git a/internal/pipeline/usages.go b/internal/pipeline/usages.go
index 95ac67b4a..c2863bb9c 100644
--- a/internal/pipeline/usages.go
+++ b/internal/pipeline/usages.go
@@ -182,21 +182,21 @@ func (p *Pipeline) resolveFileUsages(relPath string, cached *cachedAST) []resolv
callerQN = moduleQN
}
- targetQN := p.registry.Resolve(refName, moduleQN, importMap)
- if targetQN == "" {
+ targetResult := p.registry.Resolve(refName, moduleQN, importMap)
+ if targetResult.QualifiedName == "" {
return false
}
// Skip Variable targets — handled by passReadsWrites (READS/WRITES edges)
- if p.registry.LabelOf(targetQN) == "Variable" {
+ if p.registry.LabelOf(targetResult.QualifiedName) == "Variable" {
return false
}
- if targetQN == callerQN {
+ if targetResult.QualifiedName == callerQN {
return false
}
- edges = append(edges, resolvedEdge{CallerQN: callerQN, TargetQN: targetQN, Type: "USAGE"})
+ edges = append(edges, resolvedEdge{CallerQN: callerQN, TargetQN: targetResult.QualifiedName, Type: "USAGE"})
return false
})
return edges
diff --git a/internal/store/edges.go b/internal/store/edges.go
index 41b8d86af..2b00a46d7 100644
--- a/internal/store/edges.go
+++ b/internal/store/edges.go
@@ -12,7 +12,7 @@ func (s *Store) InsertEdge(e *Edge) (int64, error) {
res, err := s.q.Exec(`
INSERT INTO edges (project, source_id, target_id, type, properties)
VALUES (?, ?, ?, ?, ?)
- ON CONFLICT(source_id, target_id, type) DO UPDATE SET properties=excluded.properties`,
+ ON CONFLICT(source_id, target_id, type) DO UPDATE SET properties=json_patch(properties, excluded.properties)`,
e.Project, e.SourceID, e.TargetID, e.Type, marshalProps(e.Properties))
if err != nil {
return 0, fmt.Errorf("insert edge: %w", err)
@@ -162,7 +162,7 @@ func (s *Store) insertEdgeChunk(batch []*Edge) error {
sb.WriteString("(?,?,?,?,?)")
args = append(args, e.Project, e.SourceID, e.TargetID, e.Type, marshalProps(e.Properties))
}
- sb.WriteString(` ON CONFLICT(source_id, target_id, type) DO UPDATE SET properties=excluded.properties`)
+ sb.WriteString(` ON CONFLICT(source_id, target_id, type) DO UPDATE SET properties=json_patch(properties, excluded.properties)`)
_, err := s.q.Exec(sb.String(), args...)
if err == nil {
@@ -176,7 +176,7 @@ func (s *Store) insertEdgeChunk(batch []*Edge) error {
if _, err2 := s.q.Exec(`
INSERT INTO edges (project, source_id, target_id, type, properties)
VALUES (?, ?, ?, ?, ?)
- ON CONFLICT(source_id, target_id, type) DO UPDATE SET properties=excluded.properties`,
+ ON CONFLICT(source_id, target_id, type) DO UPDATE SET properties=json_patch(properties, excluded.properties)`,
e.Project, e.SourceID, e.TargetID, e.Type, marshalProps(e.Properties)); err2 != nil {
skipped++
}
@@ -303,6 +303,48 @@ func (s *Store) FindEdgesByTargetIDs(targetIDs []int64, edgeTypes []string) (map
return result, nil
}
+// NodeDegree returns inbound and outbound CALLS edge counts for a node.
+func (s *Store) NodeDegree(nodeID int64) (inbound, outbound int) {
+ _ = s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE target_id=? AND type='CALLS'", nodeID).Scan(&inbound)
+ _ = s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE source_id=? AND type='CALLS'", nodeID).Scan(&outbound)
+ return
+}
+
+// NodeNeighborNames returns the names of callers and callees for a node,
+// considering CALLS, HTTP_CALLS, and ASYNC_CALLS edge types.
+func (s *Store) NodeNeighborNames(nodeID int64, limit int) (callerNames, calleeNames []string) {
+ callerNames = queryNeighborNames(s.q,
+ `SELECT DISTINCT n.name FROM edges e JOIN nodes n ON e.source_id = n.id
+ WHERE e.target_id = ? AND e.type IN ('CALLS','HTTP_CALLS','ASYNC_CALLS')
+ ORDER BY n.name LIMIT ?`, nodeID, limit)
+ calleeNames = queryNeighborNames(s.q,
+ `SELECT DISTINCT n.name FROM edges e JOIN nodes n ON e.target_id = n.id
+ WHERE e.source_id = ? AND e.type IN ('CALLS','HTTP_CALLS','ASYNC_CALLS')
+ ORDER BY n.name LIMIT ?`, nodeID, limit)
+ return
+}
+
+// queryNeighborNames runs a query returning a single name column.
+func queryNeighborNames(q Querier, query string, args ...any) []string {
+ rows, err := q.Query(query, args...)
+ if err != nil {
+ return nil
+ }
+ defer rows.Close()
+ var names []string
+ for rows.Next() {
+ var name string
+ if err := rows.Scan(&name); err != nil {
+ continue
+ }
+ names = append(names, name)
+ }
+ if err := rows.Err(); err != nil {
+ return nil
+ }
+ return names
+}
+
func scanEdges(rows *sql.Rows) ([]*Edge, error) {
var result []*Edge
for rows.Next() {
diff --git a/internal/store/nodes.go b/internal/store/nodes.go
index 5550af1fa..6bf512d4b 100644
--- a/internal/store/nodes.go
+++ b/internal/store/nodes.go
@@ -60,6 +60,19 @@ func (s *Store) FindNodesByName(project, name string) ([]*Node, error) {
return scanNodes(rows)
}
+// FindNodesByQNSuffix finds nodes whose qualified_name ends with "."+suffix.
+// Matches at QN segment boundaries to prevent partial word matches.
+func (s *Store) FindNodesByQNSuffix(project, suffix string) ([]*Node, error) {
+ rows, err := s.q.Query(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
+ FROM nodes WHERE project=? AND qualified_name LIKE ?`,
+ project, "%."+suffix)
+ if err != nil {
+ return nil, fmt.Errorf("find by qn suffix: %w", err)
+ }
+ defer rows.Close()
+ return scanNodes(rows)
+}
+
// FindNodesByLabel finds all nodes with a given label in a project.
func (s *Store) FindNodesByLabel(project, label string) ([]*Node, error) {
rows, err := s.q.Query(`SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties
diff --git a/internal/store/store_test.go b/internal/store/store_test.go
index da2da94d9..ee1def2ad 100644
--- a/internal/store/store_test.go
+++ b/internal/store/store_test.go
@@ -900,6 +900,137 @@ func TestFindNodesByFileOverlap(t *testing.T) {
}
}
+func TestFindNodesByQNSuffix_Single(t *testing.T) {
+ s, err := OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ if err := s.UpsertProject("test", "/tmp/test"); err != nil {
+ t.Fatal(err)
+ }
+ _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "HandleRequest", QualifiedName: "test.cmd.server.main.HandleRequest"})
+
+ nodes, err := s.FindNodesByQNSuffix("test", "main.HandleRequest")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(nodes) != 1 {
+ t.Fatalf("expected 1 match, got %d", len(nodes))
+ }
+ if nodes[0].Name != "HandleRequest" {
+ t.Errorf("expected HandleRequest, got %s", nodes[0].Name)
+ }
+}
+
+func TestFindNodesByQNSuffix_NoMatch(t *testing.T) {
+ s, err := OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ if err := s.UpsertProject("test", "/tmp/test"); err != nil {
+ t.Fatal(err)
+ }
+ _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "Foo", QualifiedName: "test.main.Foo"})
+
+ nodes, err := s.FindNodesByQNSuffix("test", "main.Bar")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(nodes) != 0 {
+ t.Fatalf("expected 0 matches, got %d", len(nodes))
+ }
+}
+
+func TestFindNodesByQNSuffix_Multiple(t *testing.T) {
+ s, err := OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ if err := s.UpsertProject("test", "/tmp/test"); err != nil {
+ t.Fatal(err)
+ }
+ _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "Run", QualifiedName: "test.cmd.server.Run"})
+ _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "Run", QualifiedName: "test.cmd.worker.Run"})
+
+ // Suffix "Run" should match both (both end with ".Run")
+ nodes, err := s.FindNodesByQNSuffix("test", "Run")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(nodes) != 2 {
+ t.Fatalf("expected 2 matches, got %d", len(nodes))
+ }
+}
+
+func TestFindNodesByQNSuffix_DotBoundary(t *testing.T) {
+ s, err := OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ if err := s.UpsertProject("test", "/tmp/test"); err != nil {
+ t.Fatal(err)
+ }
+ _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "HandleRequest", QualifiedName: "test.main.HandleRequest"})
+ _, _ = s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "MyHandleRequestHelper", QualifiedName: "test.main.MyHandleRequestHelper"})
+
+ // Should only match the one with ".HandleRequest" suffix, not partial word
+ nodes, err := s.FindNodesByQNSuffix("test", "HandleRequest")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if len(nodes) != 1 {
+ t.Fatalf("expected 1 match (dot-boundary), got %d", len(nodes))
+ }
+ if nodes[0].Name != "HandleRequest" {
+ t.Errorf("expected HandleRequest, got %s", nodes[0].Name)
+ }
+}
+
+func TestNodeDegree(t *testing.T) {
+ s, err := OpenMemory()
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer s.Close()
+
+ if err := s.UpsertProject("test", "/tmp/test"); err != nil {
+ t.Fatal(err)
+ }
+
+ idA, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "A", QualifiedName: "test.A"})
+ idB, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "B", QualifiedName: "test.B"})
+ idC, _ := s.UpsertNode(&Node{Project: "test", Label: "Function", Name: "C", QualifiedName: "test.C"})
+
+ // A -> B (CALLS), A -> C (CALLS), B -> C (CALLS), A -> C (USAGE — not counted)
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idB, Type: "CALLS"})
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idC, Type: "CALLS"})
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idB, TargetID: idC, Type: "CALLS"})
+ _, _ = s.InsertEdge(&Edge{Project: "test", SourceID: idA, TargetID: idC, Type: "USAGE"})
+
+ inA, outA := s.NodeDegree(idA)
+ if inA != 0 || outA != 2 {
+ t.Errorf("A: in=%d out=%d, want in=0 out=2", inA, outA)
+ }
+
+ inB, outB := s.NodeDegree(idB)
+ if inB != 1 || outB != 1 {
+ t.Errorf("B: in=%d out=%d, want in=1 out=1", inB, outB)
+ }
+
+ inC, outC := s.NodeDegree(idC)
+ if inC != 2 || outC != 0 {
+ t.Errorf("C: in=%d out=%d, want in=2 out=0", inC, outC)
+ }
+}
+
func TestBFSWithRiskLabels(t *testing.T) {
s, err := OpenMemory()
if err != nil {
diff --git a/internal/store/traverse.go b/internal/store/traverse.go
index 3ba31000f..37e2ab8a4 100644
--- a/internal/store/traverse.go
+++ b/internal/store/traverse.go
@@ -20,9 +20,10 @@ type NodeHop struct {
// EdgeInfo is a simplified edge for output.
type EdgeInfo struct {
- FromName string
- ToName string
- Type string
+ FromName string
+ ToName string
+ Type string
+ Confidence float64
}
// BFS performs breadth-first traversal following edges of given types using a
@@ -115,7 +116,8 @@ func (s *Store) BFS(startNodeID int64, direction string, edgeTypes []string, max
JOIN edges e ON e.%s = b.node_id AND e.type IN (%s)
WHERE b.hop < ?
)
- SELECT DISTINCT src.name, tgt.name, e.type
+ SELECT DISTINCT src.name, tgt.name, e.type,
+ COALESCE(json_extract(e.properties, '$.confidence'), 0) as confidence
FROM bfs b
JOIN edges e ON e.%s = b.node_id AND e.type IN (%s)
JOIN nodes src ON src.id = e.source_id
@@ -140,7 +142,7 @@ func (s *Store) BFS(startNodeID int64, direction string, edgeTypes []string, max
for edgeRows.Next() {
var ei EdgeInfo
- if err := edgeRows.Scan(&ei.FromName, &ei.ToName, &ei.Type); err != nil {
+ if err := edgeRows.Scan(&ei.FromName, &ei.ToName, &ei.Type, &ei.Confidence); err != nil {
return nil, err
}
result.Edges = append(result.Edges, ei)
diff --git a/internal/tools/snippet.go b/internal/tools/snippet.go
index 232f5cd2b..6da31d5fb 100644
--- a/internal/tools/snippet.go
+++ b/internal/tools/snippet.go
@@ -4,13 +4,22 @@ import (
"bufio"
"context"
"fmt"
+ "log/slog"
"os"
"path/filepath"
"strings"
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
"github.com/modelcontextprotocol/go-sdk/mcp"
)
+// snippetMatch holds a resolved node with metadata about how it was found.
+type snippetMatch struct {
+ node *store.Node
+ project string
+ method string // "exact", "suffix", "name"
+}
+
func (s *Server) handleGetCodeSnippet(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {
args, err := parseArgs(req)
if err != nil {
@@ -24,28 +33,68 @@ func (s *Server) handleGetCodeSnippet(_ context.Context, req *mcp.CallToolReques
project := getStringArg(args, "project")
effectiveProject := s.resolveProjectName(project)
+ autoResolve := getBoolArg(args, "auto_resolve")
+ includeNeighbors := getBoolArg(args, "include_neighbors")
- // Find the node
- node, foundProject, findErr := s.findNodeByQNAcrossProjects(qn, effectiveProject)
- if findErr != nil && !strings.HasPrefix(findErr.Error(), "node not found") {
- return errResult(findErr.Error()), nil
+ // 4-tier resolution: exact QN -> suffix -> short name -> fuzzy suggestions
+ match, candidates, resolveErr := s.resolveSnippetNode(qn, effectiveProject)
+ if resolveErr != nil {
+ return errResult(resolveErr.Error()), nil
+ }
+
+ // Ambiguous: try auto-resolve or return suggestions
+ if match == nil && len(candidates) > 0 {
+ if autoResolve && len(candidates) <= 2 {
+ match = s.autoResolveBest(candidates, effectiveProject)
+ }
+ if match == nil {
+ return s.snippetSuggestions(qn, candidates), nil
+ }
+ // Build alternatives list (candidates that were NOT picked)
+ alternatives := make([]map[string]string, 0, len(candidates)-1)
+ for _, c := range candidates {
+ if c.ID != match.node.ID {
+ alternatives = append(alternatives, map[string]string{
+ "qualified_name": c.QualifiedName,
+ "file_path": c.FilePath,
+ })
+ }
+ }
+ return s.buildSnippetResponse(match, includeNeighbors, alternatives)
}
- if node == nil {
+
+ // Nothing found at all: try fuzzy suggestions (with last-segment extraction)
+ if match == nil {
+ searchName := qn
+ if idx := strings.LastIndex(qn, "."); idx >= 0 {
+ searchName = qn[idx+1:]
+ }
+ suggestions := s.findSimilarNodes(searchName, effectiveProject, 5)
+ if len(suggestions) > 0 {
+ return s.snippetSuggestions(qn, suggestions), nil
+ }
return errResult(fmt.Sprintf("node not found: %s", qn)), nil
}
+ return s.buildSnippetResponse(match, includeNeighbors, nil)
+}
+
+// buildSnippetResponse reads source and builds the enriched JSON response for a resolved match.
+func (s *Server) buildSnippetResponse(match *snippetMatch, includeNeighbors bool, alternatives []map[string]string) (*mcp.CallToolResult, error) {
+ node := match.node
+ foundProject := match.project
+
if node.FilePath == "" {
return errResult("node has no file path"), nil
}
-
if node.StartLine == 0 || node.EndLine == 0 {
return errResult("node has no line range"), nil
}
// Get the store for the found project to look up root path
- st, err := s.router.ForProject(foundProject)
- if err != nil {
- return errResult(fmt.Sprintf("store: %v", err)), nil
+ st, stErr := s.router.ForProject(foundProject)
+ if stErr != nil {
+ return errResult(fmt.Sprintf("store: %v", stErr)), nil
}
proj, _ := st.GetProject(foundProject)
@@ -61,7 +110,8 @@ func (s *Server) handleGetCodeSnippet(_ context.Context, req *mcp.CallToolReques
return errResult(fmt.Sprintf("read file: %v", readErr)), nil
}
- return jsonResult(map[string]any{
+ // Build enriched response
+ responseData := map[string]any{
"qualified_name": node.QualifiedName,
"name": node.Name,
"label": node.Label,
@@ -69,7 +119,189 @@ func (s *Server) handleGetCodeSnippet(_ context.Context, req *mcp.CallToolReques
"start_line": node.StartLine,
"end_line": node.EndLine,
"source": source,
- }), nil
+ }
+
+ // Add all non-empty node properties
+ for k, v := range node.Properties {
+ if v != nil {
+ responseData[k] = v
+ }
+ }
+
+ // Show match_method for non-exact resolutions
+ if match.method != "exact" {
+ responseData["match_method"] = match.method
+ }
+
+ // Add caller/callee counts
+ inDegree, outDegree := st.NodeDegree(node.ID)
+ responseData["callers"] = inDegree
+ responseData["callees"] = outDegree
+
+ // Opt-in: include neighbor names
+ if includeNeighbors {
+ callerNames, calleeNames := st.NodeNeighborNames(node.ID, 10)
+ if len(callerNames) > 0 {
+ responseData["caller_names"] = callerNames
+ }
+ if len(calleeNames) > 0 {
+ responseData["callee_names"] = calleeNames
+ }
+ }
+
+ // Include alternatives when auto-resolved
+ if alternatives != nil {
+ responseData["alternatives"] = alternatives
+ }
+
+ return jsonResult(responseData), nil
+}
+
+// autoResolveBest picks the best candidate from a small set (<=2).
+// Heuristic: highest total degree (in+out across all edge types), preferring non-test files.
+func (s *Server) autoResolveBest(candidates []*store.Node, projectFilter string) *snippetMatch {
+ filter := s.resolveProjectName(projectFilter)
+ st, err := s.router.ForProject(filter)
+ if err != nil {
+ return nil
+ }
+ projects, _ := st.ListProjects()
+ if len(projects) == 0 {
+ return nil
+ }
+ projName := projects[0].Name
+
+ type scored struct {
+ node *store.Node
+ degree int
+ isTest bool
+ }
+
+ scored_ := make([]scored, len(candidates))
+ for i, c := range candidates {
+ in, out := st.NodeDegree(c.ID)
+ isTest := strings.Contains(c.FilePath, "_test")
+ scored_[i] = scored{node: c, degree: in + out, isTest: isTest}
+ }
+
+ best := scored_[0]
+ for _, s := range scored_[1:] {
+ // Prefer non-test over test
+ if best.isTest && !s.isTest {
+ best = s
+ continue
+ }
+ if !best.isTest && s.isTest {
+ continue
+ }
+ // Higher degree wins
+ if s.degree > best.degree {
+ best = s
+ continue
+ }
+ // Tiebreaker: alphabetical QN
+ if s.degree == best.degree && s.node.QualifiedName < best.node.QualifiedName {
+ best = s
+ }
+ }
+
+ slog.Info("snippet.auto_resolved", "input", candidates[0].Name, "picked", best.node.QualifiedName, "candidates", len(candidates))
+ return &snippetMatch{node: best.node, project: projName, method: "auto_best"}
+}
+
+// resolveSnippetNode implements a 4-tier lookup:
+//
+// Tier 1: Exact QN match
+// Tier 2: QN suffix match (dot-boundary)
+// Tier 3: Short name match
+// Tier 4: (caller handles fuzzy via findSimilarNodes)
+//
+// Returns (match, nil, nil) on unique hit, (nil, candidates, nil) on ambiguous,
+// (nil, nil, nil) when nothing found, or (nil, nil, err) on infrastructure error.
+func (s *Server) resolveSnippetNode(input, projectFilter string) (*snippetMatch, []*store.Node, error) {
+ filter := s.sessionProject
+ if projectFilter != "" {
+ if projectFilter == "*" || projectFilter == "all" {
+ return nil, nil, fmt.Errorf("cross-project queries are not supported; use list_projects to find a specific project name, or omit the project parameter to use the current session project")
+ }
+ filter = projectFilter
+ }
+ if filter == "" {
+ return nil, nil, fmt.Errorf("no project specified and no session project detected")
+ }
+ if !s.router.HasProject(filter) {
+ return nil, nil, fmt.Errorf("project %q not found; use list_projects to see available projects", filter)
+ }
+
+ st, err := s.router.ForProject(filter)
+ if err != nil {
+ return nil, nil, err
+ }
+ projects, _ := st.ListProjects()
+ if len(projects) == 0 {
+ return nil, nil, fmt.Errorf("no projects in store")
+ }
+ projName := projects[0].Name
+
+ // Tier 1: Exact QN match
+ node, findErr := st.FindNodeByQN(projName, input)
+ if findErr == nil && node != nil {
+ return &snippetMatch{node: node, project: projName, method: "exact"}, nil, nil
+ }
+
+ // Tier 2: QN suffix match (dot-boundary)
+ suffixMatches, err := st.FindNodesByQNSuffix(projName, input)
+ if err == nil && len(suffixMatches) == 1 {
+ return &snippetMatch{node: suffixMatches[0], project: projName, method: "suffix"}, nil, nil
+ }
+
+ // Tier 3: Short name match
+ nameMatches, err := st.FindNodesByName(projName, input)
+ if err == nil && len(nameMatches) == 1 {
+ return &snippetMatch{node: nameMatches[0], project: projName, method: "name"}, nil, nil
+ }
+
+ // Collect all candidates for suggestions (deduped)
+ candidates := dedupNodes(suffixMatches, nameMatches)
+ if len(candidates) > 0 {
+ return nil, candidates, nil
+ }
+
+ // Nothing found at any tier
+ return nil, nil, nil
+}
+
+// snippetSuggestions returns a structured suggestion response for ambiguous or not-found lookups.
+func (s *Server) snippetSuggestions(input string, nodes []*store.Node) *mcp.CallToolResult {
+ suggList := make([]map[string]string, 0, len(nodes))
+ for _, n := range nodes {
+ suggList = append(suggList, map[string]string{
+ "qualified_name": n.QualifiedName,
+ "name": n.Name,
+ "label": n.Label,
+ "file_path": n.FilePath,
+ })
+ }
+ return jsonResult(map[string]any{
+ "status": "ambiguous",
+ "message": fmt.Sprintf("%d matches found for %q — use a qualified_name from the suggestions to disambiguate", len(nodes), input),
+ "suggestions": suggList,
+ })
+}
+
+// dedupNodes merges multiple node slices, deduplicating by node ID.
+func dedupNodes(slices ...[]*store.Node) []*store.Node {
+ seen := make(map[int64]bool)
+ var result []*store.Node
+ for _, s := range slices {
+ for _, n := range s {
+ if n != nil && !seen[n.ID] {
+ seen[n.ID] = true
+ result = append(result, n)
+ }
+ }
+ }
+ return result
}
// readLines reads specific lines from a file, returning them with line numbers.
diff --git a/internal/tools/snippet_test.go b/internal/tools/snippet_test.go
new file mode 100644
index 000000000..53d4e2c55
--- /dev/null
+++ b/internal/tools/snippet_test.go
@@ -0,0 +1,489 @@
+package tools
+
+import (
+ "context"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/DeusData/codebase-memory-mcp/internal/store"
+ "github.com/modelcontextprotocol/go-sdk/mcp"
+)
+
+// testSnippetServer creates a Server with an in-memory-like store backed by a temp dir,
+// pre-populated with a project, nodes, and edges.
+func testSnippetServer(t *testing.T) *Server {
+ t.Helper()
+
+ tmpDir := t.TempDir()
+ routerDir := filepath.Join(tmpDir, "db")
+ projRoot := filepath.Join(tmpDir, "project")
+
+ if err := os.MkdirAll(projRoot, 0o750); err != nil {
+ t.Fatal(err)
+ }
+
+ // Write a sample source file
+ srcContent := `package main
+
+func HandleRequest() error {
+ return nil
+}
+
+func ProcessOrder(id int) {
+ // process
+}
+
+func Run() {
+ // server
+}
+`
+ if err := os.WriteFile(filepath.Join(projRoot, "main.go"), []byte(srcContent), 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ router, err := store.NewRouterWithDir(routerDir)
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ projName := "test-project"
+ st, err := router.ForProject(projName)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := st.UpsertProject(projName, projRoot); err != nil {
+ t.Fatal(err)
+ }
+
+ // Create nodes
+ idHR, _ := st.UpsertNode(&store.Node{
+ Project: projName,
+ Label: "Function",
+ Name: "HandleRequest",
+ QualifiedName: "test-project.cmd.server.main.HandleRequest",
+ FilePath: "main.go",
+ StartLine: 3,
+ EndLine: 5,
+ Properties: map[string]any{
+ "signature": "func HandleRequest() error",
+ "return_type": "error",
+ "is_exported": true,
+ },
+ })
+ idPO, _ := st.UpsertNode(&store.Node{
+ Project: projName,
+ Label: "Function",
+ Name: "ProcessOrder",
+ QualifiedName: "test-project.cmd.server.main.ProcessOrder",
+ FilePath: "main.go",
+ StartLine: 7,
+ EndLine: 9,
+ Properties: map[string]any{"signature": "func ProcessOrder(id int)"},
+ })
+ idRun1, _ := st.UpsertNode(&store.Node{
+ Project: projName,
+ Label: "Function",
+ Name: "Run",
+ QualifiedName: "test-project.cmd.server.Run",
+ FilePath: "main.go",
+ StartLine: 11,
+ EndLine: 13,
+ })
+ idRun2, _ := st.UpsertNode(&store.Node{
+ Project: projName,
+ Label: "Function",
+ Name: "Run",
+ QualifiedName: "test-project.cmd.worker.Run",
+ FilePath: "main.go",
+ StartLine: 11,
+ EndLine: 13,
+ })
+
+ // Create edges: HandleRequest -> ProcessOrder, HandleRequest -> Run1
+ _, _ = st.InsertEdge(&store.Edge{Project: projName, SourceID: idHR, TargetID: idPO, Type: "CALLS"})
+ _, _ = st.InsertEdge(&store.Edge{Project: projName, SourceID: idHR, TargetID: idRun1, Type: "CALLS"})
+ _ = idRun2 // used to create ambiguity for "Run"
+
+ srv := &Server{
+ router: router,
+ handlers: make(map[string]mcp.ToolHandler),
+ sessionProject: projName,
+ }
+
+ return srv
+}
+
+func callSnippetRaw(t *testing.T, srv *Server, qn string) *mcp.CallToolResult {
+ t.Helper()
+ args := map[string]any{"qualified_name": qn}
+ rawArgs, _ := json.Marshal(args)
+
+ req := &mcp.CallToolRequest{
+ Params: &mcp.CallToolParamsRaw{
+ Name: "get_code_snippet",
+ Arguments: rawArgs,
+ },
+ }
+
+ result, err := srv.handleGetCodeSnippet(context.TODO(), req)
+ if err != nil {
+ t.Fatalf("handleGetCodeSnippet error: %v", err)
+ }
+ return result
+}
+
+func callSnippet(t *testing.T, srv *Server, qn string) map[string]any {
+ t.Helper()
+ return callSnippetWithOpts(t, srv, map[string]any{"qualified_name": qn})
+}
+
+func callSnippetWithOpts(t *testing.T, srv *Server, args map[string]any) map[string]any {
+ t.Helper()
+ // Remove empty project to match old behavior
+ if p, ok := args["project"]; ok && p == "" {
+ delete(args, "project")
+ }
+ rawArgs, _ := json.Marshal(args)
+
+ req := &mcp.CallToolRequest{
+ Params: &mcp.CallToolParamsRaw{
+ Name: "get_code_snippet",
+ Arguments: rawArgs,
+ },
+ }
+
+ result, err := srv.handleGetCodeSnippet(context.TODO(), req)
+ if err != nil {
+ t.Fatalf("handleGetCodeSnippet error: %v", err)
+ }
+ if len(result.Content) == 0 {
+ t.Fatal("empty result content")
+ }
+ tc, ok := result.Content[0].(*mcp.TextContent)
+ if !ok {
+ t.Fatalf("expected TextContent, got %T", result.Content[0])
+ }
+ var data map[string]any
+ if err := json.Unmarshal([]byte(tc.Text), &data); err != nil {
+ t.Fatalf("unmarshal result: %v (text: %s)", err, tc.Text)
+ }
+ return data
+}
+
+func TestSnippet_ExactQN(t *testing.T) {
+ srv := testSnippetServer(t)
+ data := callSnippet(t, srv, "test-project.cmd.server.main.HandleRequest")
+
+ if data["name"] != "HandleRequest" {
+ t.Errorf("expected name=HandleRequest, got %v", data["name"])
+ }
+ if data["source"] == nil || data["source"] == "" {
+ t.Error("expected non-empty source")
+ }
+ // Exact match should not have match_method
+ if _, ok := data["match_method"]; ok {
+ t.Errorf("exact match should not have match_method, got %v", data["match_method"])
+ }
+ // Should have enriched properties
+ if data["signature"] != "func HandleRequest() error" {
+ t.Errorf("expected signature, got %v", data["signature"])
+ }
+ if data["return_type"] != "error" {
+ t.Errorf("expected return_type=error, got %v", data["return_type"])
+ }
+ // Should have caller/callee counts
+ if data["callers"] == nil {
+ t.Error("expected callers field")
+ }
+ if data["callees"] == nil {
+ t.Error("expected callees field")
+ }
+ // HandleRequest has 0 callers and 2 callees
+ if data["callers"] != float64(0) {
+ t.Errorf("expected 0 callers, got %v", data["callers"])
+ }
+ if data["callees"] != float64(2) {
+ t.Errorf("expected 2 callees, got %v", data["callees"])
+ }
+}
+
+func TestSnippet_QNSuffix(t *testing.T) {
+ srv := testSnippetServer(t)
+ data := callSnippet(t, srv, "main.HandleRequest")
+
+ if data["name"] != "HandleRequest" {
+ t.Errorf("expected name=HandleRequest, got %v", data["name"])
+ }
+ if data["match_method"] != "suffix" {
+ t.Errorf("expected match_method=suffix, got %v", data["match_method"])
+ }
+ if data["source"] == nil || data["source"] == "" {
+ t.Error("expected non-empty source")
+ }
+}
+
+func TestSnippet_UniqueShortName(t *testing.T) {
+ srv := testSnippetServer(t)
+ // "ProcessOrder" is unique across both suffix and name tiers
+ data := callSnippet(t, srv, "ProcessOrder")
+
+ if data["name"] != "ProcessOrder" {
+ t.Errorf("expected name=ProcessOrder, got %v", data["name"])
+ }
+ // ProcessOrder QN ends with ".ProcessOrder" — suffix tier matches first (1 result)
+ if data["match_method"] != "suffix" {
+ t.Errorf("expected match_method=suffix, got %v", data["match_method"])
+ }
+ if data["source"] == nil || data["source"] == "" {
+ t.Error("expected non-empty source")
+ }
+}
+
+func TestSnippet_NameTier(t *testing.T) {
+ // To test name-tier specifically, we need a node whose short name is unique
+ // but whose QN doesn't end with ".ShortName" (so suffix tier misses).
+ // This is hard to construct since QNs always end with the name.
+ // Instead, verify that short names resolve correctly when suffix tier returns 1.
+ srv := testSnippetServer(t)
+ data := callSnippet(t, srv, "HandleRequest")
+
+ if data["name"] != "HandleRequest" {
+ t.Errorf("expected name=HandleRequest, got %v", data["name"])
+ }
+ // Suffix tier finds it (QN ends with ".HandleRequest"), which is correct behavior
+ if data["match_method"] != "suffix" {
+ t.Errorf("expected match_method=suffix, got %v", data["match_method"])
+ }
+}
+
+func TestSnippet_AmbiguousShortName(t *testing.T) {
+ srv := testSnippetServer(t)
+ data := callSnippet(t, srv, "Run")
+
+ // Should return suggestions, not source code
+ if data["source"] != nil {
+ t.Error("ambiguous lookup should not return source code")
+ }
+ // Should use "status"/"message" instead of "error"
+ if data["status"] != "ambiguous" {
+ t.Fatalf("expected status=ambiguous, got %v", data["status"])
+ }
+ if data["message"] == nil {
+ t.Fatal("expected message field for ambiguous match")
+ }
+ // Must NOT have "error" key
+ if _, hasError := data["error"]; hasError {
+ t.Error("ambiguous response must not contain 'error' key")
+ }
+ suggestions, ok := data["suggestions"].([]any)
+ if !ok {
+ t.Fatalf("expected suggestions array, got %T", data["suggestions"])
+ }
+ if len(suggestions) < 2 {
+ t.Errorf("expected at least 2 suggestions, got %d", len(suggestions))
+ }
+ // Verify suggestions have qualified_name
+ for _, s := range suggestions {
+ sMap, ok := s.(map[string]any)
+ if !ok {
+ t.Fatalf("expected suggestion map, got %T", s)
+ }
+ if sMap["qualified_name"] == nil || sMap["qualified_name"] == "" {
+ t.Error("suggestion missing qualified_name")
+ }
+ }
+}
+
+func TestSnippet_NotFound(t *testing.T) {
+ srv := testSnippetServer(t)
+ result := callSnippetRaw(t, srv, "CompletelyNonexistentFunctionXYZ123")
+
+ // Should be an error result (plain text or JSON with suggestions)
+ if !result.IsError {
+ // If not IsError, check it has suggestions
+ tc, ok := result.Content[0].(*mcp.TextContent)
+ if !ok {
+ t.Fatal("expected TextContent")
+ }
+ var data map[string]any
+ if err := json.Unmarshal([]byte(tc.Text), &data); err == nil {
+ if data["suggestions"] == nil && data["status"] == nil {
+ t.Error("expected status or suggestions for non-existent function")
+ }
+ }
+ return
+ }
+ // Plain error result is fine for truly not-found names
+}
+
+func TestSnippet_FuzzySuggestions(t *testing.T) {
+ srv := testSnippetServer(t)
+ // "Handle" should fuzzy-match "HandleRequest" via findSimilarNodes
+ data := callSnippet(t, srv, "Handle")
+
+ // Should return suggestions (fuzzy match to HandleRequest)
+ if suggestions, ok := data["suggestions"].([]any); ok {
+ found := false
+ for _, s := range suggestions {
+ sMap, ok := s.(map[string]any)
+ if !ok {
+ t.Fatalf("expected suggestion map, got %T", s)
+ }
+ if sMap["name"] == "HandleRequest" {
+ found = true
+ }
+ }
+ if !found {
+ t.Error("expected HandleRequest in fuzzy suggestions")
+ }
+ }
+ // If no suggestions, it should at least have a status
+ if data["suggestions"] == nil && data["status"] == nil && data["source"] == nil {
+ t.Error("expected either suggestions, status, or source")
+ }
+}
+
+func TestSnippet_EnrichedProperties(t *testing.T) {
+ srv := testSnippetServer(t)
+ data := callSnippet(t, srv, "test-project.cmd.server.main.HandleRequest")
+
+ // Verify all enriched properties are present
+ if data["signature"] == nil {
+ t.Error("expected signature property")
+ }
+ if data["return_type"] == nil {
+ t.Error("expected return_type property")
+ }
+ if data["is_exported"] != true {
+ t.Errorf("expected is_exported=true, got %v", data["is_exported"])
+ }
+}
+
+func TestSnippet_FuzzyLastSegment(t *testing.T) {
+ srv := testSnippetServer(t)
+ // "auth.handlers.HandleRequest" — full dotted string won't match anything,
+ // but last segment "HandleRequest" should fuzzy-match
+ data := callSnippet(t, srv, "auth.handlers.HandleRequest")
+
+ // Should return suggestions via last-segment extraction
+ if data["status"] != "ambiguous" && data["source"] == nil {
+ // It could be a direct match via suffix or fuzzy
+ if data["suggestions"] == nil {
+ t.Error("expected suggestions for dotted input with last-segment fallback")
+ }
+ }
+ // If it returned suggestions, verify HandleRequest is among them
+ if suggestions, ok := data["suggestions"].([]any); ok {
+ found := false
+ for _, s := range suggestions {
+ sMap, ok := s.(map[string]any)
+ if !ok {
+ t.Fatalf("expected suggestion map, got %T", s)
+ }
+ if sMap["name"] == "HandleRequest" {
+ found = true
+ }
+ }
+ if !found {
+ t.Error("expected HandleRequest in last-segment suggestions")
+ }
+ }
+}
+
+func TestSnippet_AutoResolve_Default(t *testing.T) {
+ srv := testSnippetServer(t)
+ // "Run" is ambiguous (2 candidates). Without auto_resolve, should return suggestions.
+ data := callSnippet(t, srv, "Run")
+
+ if data["status"] != "ambiguous" {
+ t.Errorf("expected status=ambiguous without auto_resolve, got %v", data["status"])
+ }
+ if data["source"] != nil {
+ t.Error("should not return source without auto_resolve")
+ }
+}
+
+func TestSnippet_AutoResolve_Enabled(t *testing.T) {
+ srv := testSnippetServer(t)
+ // "Run" is ambiguous (2 candidates). With auto_resolve=true, should pick best.
+ data := callSnippetWithOpts(t, srv, map[string]any{
+ "qualified_name": "Run",
+ "auto_resolve": true,
+ })
+
+ if data["source"] == nil || data["source"] == "" {
+ t.Fatal("expected source with auto_resolve=true")
+ }
+ if data["match_method"] != "auto_best" {
+ t.Errorf("expected match_method=auto_best, got %v", data["match_method"])
+ }
+ // Should have alternatives
+ alternatives, ok := data["alternatives"].([]any)
+ if !ok {
+ t.Fatalf("expected alternatives array, got %T", data["alternatives"])
+ }
+ if len(alternatives) != 1 {
+ t.Errorf("expected 1 alternative, got %d", len(alternatives))
+ }
+ // The picked one should be cmd.server.Run (has 1 inbound CALLS edge = higher degree)
+ if data["qualified_name"] != "test-project.cmd.server.Run" {
+ t.Errorf("expected auto_resolve to pick server.Run (higher degree), got %v", data["qualified_name"])
+ }
+}
+
+func TestSnippet_IncludeNeighbors_Default(t *testing.T) {
+ srv := testSnippetServer(t)
+ data := callSnippet(t, srv, "test-project.cmd.server.main.HandleRequest")
+
+ // Without include_neighbors, should NOT have caller_names/callee_names
+ if data["caller_names"] != nil {
+ t.Error("should not have caller_names without include_neighbors")
+ }
+ if data["callee_names"] != nil {
+ t.Error("should not have callee_names without include_neighbors")
+ }
+ // But should still have counts
+ if data["callers"] == nil || data["callees"] == nil {
+ t.Error("expected callers/callees counts")
+ }
+}
+
+func TestSnippet_IncludeNeighbors_Enabled(t *testing.T) {
+ srv := testSnippetServer(t)
+ data := callSnippetWithOpts(t, srv, map[string]any{
+ "qualified_name": "test-project.cmd.server.main.HandleRequest",
+ "include_neighbors": true,
+ })
+
+ if data["source"] == nil || data["source"] == "" {
+ t.Fatal("expected source")
+ }
+ // HandleRequest has 0 callers and 2 callees (ProcessOrder, Run)
+ if data["caller_names"] != nil {
+ t.Errorf("expected nil caller_names (0 callers), got %v", data["caller_names"])
+ }
+ calleeNames, ok := data["callee_names"].([]any)
+ if !ok {
+ t.Fatalf("expected callee_names array, got %T (%v)", data["callee_names"], data["callee_names"])
+ }
+ if len(calleeNames) != 2 {
+ t.Errorf("expected 2 callee names, got %d", len(calleeNames))
+ }
+ // Verify the names are present (sorted alphabetically by SQL ORDER BY)
+ names := make(map[string]bool)
+ for _, n := range calleeNames {
+ s, ok := n.(string)
+ if !ok {
+ t.Fatalf("expected string callee name, got %T", n)
+ }
+ names[s] = true
+ }
+ if !names["ProcessOrder"] {
+ t.Error("expected ProcessOrder in callee_names")
+ }
+ if !names["Run"] {
+ t.Error("expected Run in callee_names")
+ }
+}
diff --git a/internal/tools/tools.go b/internal/tools/tools.go
index 155cc163a..378b55e06 100644
--- a/internal/tools/tools.go
+++ b/internal/tools/tools.go
@@ -23,7 +23,7 @@ import (
)
// Version is the current release version, referenced by MCP handshake and update checker.
-const Version = "0.3.1"
+const Version = "0.3.2"
// releaseURL is the GitHub API endpoint for latest release. Package-level var for test injection.
var releaseURL = "https://api.github.com/repos/DeusData/codebase-memory-mcp/releases/latest"
@@ -473,6 +473,10 @@ func (s *Server) registerIndexAndTraceTool() {
"type": "boolean",
"description": "Add risk classification (CRITICAL/HIGH/MEDIUM/LOW) based on hop depth. Hop 1=CRITICAL, 2=HIGH, 3=MEDIUM, 4+=LOW. Includes impact_summary with counts. Default false."
},
+ "min_confidence": {
+ "type": "number",
+ "description": "Minimum confidence threshold (0.0-1.0) for CALLS edges. Filters out low-confidence fuzzy matches. Bands: high (>=0.7), medium (>=0.45), speculative (<0.45). Default 0 (no filter)."
+ },
"project": {
"type": "string",
"description": "Project to trace in. Defaults to session project."
@@ -500,17 +504,25 @@ func (s *Server) registerSchemaAndSnippetTools() {
s.addTool(&mcp.Tool{
Name: "get_code_snippet",
- Description: "Retrieve source code for a function/class by qualified name. Reads directly from disk using the stored file path and line range. Returns the source code with line numbers.",
+ Description: "Retrieve source code for a function/class by name with rich metadata. Accepts exact qualified name ('myproject.cmd.server.main.HandleRequest'), partial QN suffix ('main.HandleRequest'), or short name ('HandleRequest'). Returns source code, signature, return type, complexity, decorators, docstring, and caller/callee counts. Returns suggestions with status='ambiguous' when multiple matches found (no 'error' key in disambiguation responses). Use auto_resolve=true to let the tool pick the best match from <=2 candidates (returns alternatives for correction). Use include_neighbors=true to get caller/callee names alongside counts.",
InputSchema: json.RawMessage(`{
"type": "object",
"properties": {
"qualified_name": {
"type": "string",
- "description": "Fully qualified name of the node (e.g. 'myproject.cmd.server.main.HandleRequest')"
+ "description": "Name or qualified name of the function/class. Exact QN for precision, short name for discovery. Returns suggestions if ambiguous."
},
"project": {
"type": "string",
"description": "Project to search in. Defaults to session project."
+ },
+ "auto_resolve": {
+ "type": "boolean",
+ "description": "When true and <=2 ambiguous candidates exist, auto-pick the best match (highest degree, prefer non-test). Returns source with match_method='auto_best' and alternatives list. Default: false."
+ },
+ "include_neighbors": {
+ "type": "boolean",
+ "description": "When true, include caller_names and callee_names arrays (up to 10 each) alongside the counts. Default: false."
}
},
"required": ["qualified_name"]
@@ -778,6 +790,19 @@ func getMapStringArg(args map[string]any, key string) map[string]string {
}
// getBoolArg extracts a boolean argument from parsed args.
+// getFloatArg extracts a float64 argument with a default value.
+func getFloatArg(args map[string]any, key string, defaultVal float64) float64 {
+ v, ok := args[key]
+ if !ok {
+ return defaultVal
+ }
+ f, ok := v.(float64)
+ if !ok {
+ return defaultVal
+ }
+ return f
+}
+
func getBoolArg(args map[string]any, key string) bool {
v, ok := args[key]
if !ok {
@@ -823,37 +848,3 @@ func (s *Server) findNodeAcrossProjects(name string, projectFilter ...string) (*
}
return nil, "", fmt.Errorf("node not found: %s", name)
}
-
-// findNodeByQNAcrossProjects searches for a node by qualified name in the specified project.
-// Falls back to the session project if no filter is given.
-func (s *Server) findNodeByQNAcrossProjects(qn string, projectFilter ...string) (*store.Node, string, error) {
- filter := s.sessionProject
- if len(projectFilter) > 0 && projectFilter[0] != "" {
- if projectFilter[0] == "*" || projectFilter[0] == "all" {
- return nil, "", fmt.Errorf("cross-project queries are not supported; use list_projects to find a specific project name, or omit the project parameter to use the current session project")
- }
- filter = projectFilter[0]
- }
- if filter == "" {
- return nil, "", fmt.Errorf("no project specified and no session project detected")
- }
- if !s.router.HasProject(filter) {
- return nil, "", fmt.Errorf("project %q not found; use list_projects to see available projects", filter)
- }
-
- st, err := s.router.ForProject(filter)
- if err != nil {
- return nil, "", err
- }
- projects, _ := st.ListProjects()
- for _, p := range projects {
- node, findErr := st.FindNodeByQN(p.Name, qn)
- if findErr != nil {
- continue
- }
- if node != nil {
- return node, p.Name, nil
- }
- }
- return nil, "", fmt.Errorf("node not found: %s", qn)
-}
diff --git a/internal/tools/trace.go b/internal/tools/trace.go
index 57d24e1af..8633dc717 100644
--- a/internal/tools/trace.go
+++ b/internal/tools/trace.go
@@ -35,6 +35,7 @@ func (s *Server) handleTraceCallPath(_ context.Context, req *mcp.CallToolRequest
}
riskLabels := getBoolArg(args, "risk_labels")
+ minConfidence := getFloatArg(args, "min_confidence", 0)
project := getStringArg(args, "project")
effectiveProject := s.resolveProjectName(project)
@@ -57,7 +58,8 @@ func (s *Server) handleTraceCallPath(_ context.Context, req *mcp.CallToolRequest
}
}
return jsonResult(map[string]any{
- "error": fmt.Sprintf("function not found: %s", funcName),
+ "status": "not_found",
+ "message": fmt.Sprintf("function not found: %s — use a name from the suggestions below", funcName),
"suggestions": suggList,
}), nil
}
@@ -72,7 +74,7 @@ func (s *Server) handleTraceCallPath(_ context.Context, req *mcp.CallToolRequest
edgeTypes := []string{"CALLS", "HTTP_CALLS", "ASYNC_CALLS"}
- allVisited, allEdges, bfsErr := runTraceBFS(st, rootNode.ID, direction, edgeTypes, depth)
+ allVisited, allEdges, bfsErr := runTraceBFS(st, rootNode.ID, direction, edgeTypes, depth, minConfidence)
if bfsErr != nil {
return errResult(fmt.Sprintf("bfs err: %v", bfsErr)), nil
}
@@ -100,7 +102,7 @@ func (s *Server) handleTraceCallPath(_ context.Context, req *mcp.CallToolRequest
return result, nil
}
-func runTraceBFS(st *store.Store, rootID int64, direction string, edgeTypes []string, depth int) ([]*store.NodeHop, []store.EdgeInfo, error) {
+func runTraceBFS(st *store.Store, rootID int64, direction string, edgeTypes []string, depth int, minConfidence float64) ([]*store.NodeHop, []store.EdgeInfo, error) {
if direction == "both" {
var allVisited []*store.NodeHop
var allEdges []store.EdgeInfo
@@ -114,13 +116,32 @@ func runTraceBFS(st *store.Store, rootID int64, direction string, edgeTypes []st
allVisited = append(allVisited, inResult.Visited...)
allEdges = append(allEdges, inResult.Edges...)
}
+ if minConfidence > 0 {
+ allEdges = filterEdgesByConfidence(allEdges, minConfidence)
+ }
return allVisited, allEdges, nil
}
result, err := st.BFS(rootID, direction, edgeTypes, depth, 200)
if err != nil {
return nil, nil, err
}
- return result.Visited, result.Edges, nil
+ edges := result.Edges
+ if minConfidence > 0 {
+ edges = filterEdgesByConfidence(edges, minConfidence)
+ }
+ return result.Visited, edges, nil
+}
+
+// filterEdgesByConfidence removes edges below the threshold.
+// Edges with confidence=0 (no confidence set, e.g. HTTP_CALLS) are kept.
+func filterEdgesByConfidence(edges []store.EdgeInfo, minConfidence float64) []store.EdgeInfo {
+ filtered := make([]store.EdgeInfo, 0, len(edges))
+ for _, e := range edges {
+ if e.Confidence == 0 || e.Confidence >= minConfidence {
+ filtered = append(filtered, e)
+ }
+ }
+ return filtered
}
func buildTraceResponse(st *store.Store, rootNode *store.Node, project string, hops []hopEntry, visited []*store.NodeHop, edges []store.EdgeInfo) map[string]any {
@@ -272,11 +293,15 @@ func (s *Server) findSimilarNodes(name, project string, limit int) []*store.Node
func buildEdgeList(edges []store.EdgeInfo) []map[string]any {
result := make([]map[string]any, 0, len(edges))
for _, e := range edges {
- result = append(result, map[string]any{
+ entry := map[string]any{
"from": e.FromName,
"to": e.ToName,
"type": e.Type,
- })
+ }
+ if e.Confidence > 0 {
+ entry["confidence"] = e.Confidence
+ }
+ result = append(result, entry)
}
return result
}