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.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
v0.2.0: Multi-DB router, enrichment pipeline, update-available notification, enhanced language support
Martin Vogelfb30ca61d666
diff --git a/cmd/ast_debug/main.go b/cmd/ast_debug/main.gonew file mode 100644index 000000000..679f9e0db--- /dev/null+++ b/cmd/ast_debug/main.go@@ -0,0 +1,85 @@+package main++import (+ "fmt"+ "os"++ "github.com/DeusData/codebase-memory-mcp/internal/lang"+ "github.com/DeusData/codebase-memory-mcp/internal/parser"++ tree_sitter "github.com/tree-sitter/go-tree-sitter"+)++func printAST(node *tree_sitter.Node, source []byte, indent int) {+ if node == nil {+ return+ }+ prefix := ""+ for i := 0; i < indent; i++ {+ prefix += " "+ }+ parentKind := "nil"+ if node.Parent() != nil {+ parentKind = node.Parent().Kind()+ }+ text := string(source[node.StartByte():node.EndByte()])+ if len(text) > 60 {+ text = text[:60] + "..."+ }+ fmt.Printf("%s%s (parent=%s) %q\n", prefix, node.Kind(), parentKind, text)+ for i := uint(0); i < node.ChildCount(); i++ {+ printAST(node.Child(i), source, indent+1)+ }+}++func main() {+ // Test Go - check if var groups have wrapping+ goCode := []byte("package main\n\nvar globalVar = 42\n\nvar (\n\ta = 1\n\tb = 2\n)\n")+ fmt.Println("=== GO AST ===")+ tree, err := parser.Parse(lang.Go, goCode)+ if err != nil {+ fmt.Println("Error:", err)+ }+ if tree != nil {+ printAST(tree.RootNode(), goCode, 0)+ tree.Close()+ }++ // Test Rust+ rustCode := []byte("pub static X: i32 = 5;\nconst Y: &str = \"hello\";\n")+ fmt.Println("\n=== RUST AST ===")+ tree2, err := parser.Parse(lang.Rust, rustCode)+ if err != nil {+ fmt.Println("Error:", err)+ }+ if tree2 != nil {+ printAST(tree2.RootNode(), rustCode, 0)+ tree2.Close()+ }++ // Test Python decorated function+ pyCode := []byte("@app.route('/api')\ndef handler():\n pass\n")+ fmt.Println("\n=== PYTHON DECORATED FUNC ===")+ tree3, err := parser.Parse(lang.Python, pyCode)+ if err != nil {+ fmt.Println("Error:", err)+ }+ if tree3 != nil {+ printAST(tree3.RootNode(), pyCode, 0)+ tree3.Close()+ }++ // Test Python with type annotation assignment+ pyCode2 := []byte("x: int = 5\nlogger: Logger = get_logger()\n")+ fmt.Println("\n=== PYTHON TYPE ANNOTATED ASSIGNMENT ===")+ tree4, err := parser.Parse(lang.Python, pyCode2)+ if err != nil {+ fmt.Println("Error:", err)+ }+ if tree4 != nil {+ printAST(tree4.RootNode(), pyCode2, 0)+ tree4.Close()+ }++ os.Exit(0)+}diff --git a/cmd/codebase-memory-mcp/main.go b/cmd/codebase-memory-mcp/main.goindex 874a2c4b1..150af79ac 100644--- a/cmd/codebase-memory-mcp/main.go+++ b/cmd/codebase-memory-mcp/main.go@@ -6,6 +6,7 @@ import ("fmt""log""os"+ "path/filepath""strings""github.com/DeusData/codebase-memory-mcp/internal/store"@@ -25,19 +26,19 @@ func main() {os.Exit(runCLI(os.Args[2:]))}- s, err := store.Open("codebase-memory")+ router, err := store.NewRouter()if err != nil {- log.Fatalf("store open err=%v", err)+ log.Fatalf("store router err=%v", err)}- srv := tools.NewServer(s)+ srv := tools.NewServer(router)ctx, cancel := context.WithCancel(context.Background())srv.StartWatcher(ctx)runErr := srv.MCPServer().Run(ctx, &mcp.StdioTransport{})cancel()- s.Close()+ router.CloseAll()if runErr != nil {log.Fatalf("server err=%v", runErr)}@@ -56,14 +57,15 @@ func runCLI(args []string) int {}}+ router, err := store.NewRouter()+ if err != nil {+ fmt.Fprintf(os.Stderr, "error: %v\n", err)+ return 1+ }+ defer router.CloseAll()+if len(positional) == 0 || positional[0] == "--help" || positional[0] == "-h" {- s, err := store.Open("codebase-memory")- if err != nil {- fmt.Fprintf(os.Stderr, "error: %v\n", err)- return 1- }- srv := tools.NewServer(s)- s.Close()+ srv := tools.NewServer(router)fmt.Fprintf(os.Stderr, "Usage: codebase-memory-mcp cli [--raw] <tool_name> [json_args]\n\n")fmt.Fprintf(os.Stderr, "Flags:\n --raw Print full JSON output (default: human-friendly summary)\n\n")fmt.Fprintf(os.Stderr, "Available tools:\n %s\n", strings.Join(srv.ToolNames(), "\n "))@@ -72,14 +74,12 @@ func runCLI(args []string) int {toolName := positional[0]- s, err := store.Open("codebase-memory")- if err != nil {- fmt.Fprintf(os.Stderr, "error: %v\n", err)- return 1- }- defer s.Close()+ srv := tools.NewServer(router)- srv := tools.NewServer(s)+ // In CLI mode, try to set session root from cwd+ if cwd, cwdErr := os.Getwd(); cwdErr == nil {+ srv.SetSessionRoot(cwd)+ }var argsJSON json.RawMessageif len(positional) > 1 {@@ -116,7 +116,8 @@ func runCLI(args []string) int {}// Summary mode (default): print a human-friendly summary- printSummary(toolName, text, s.DBPath())+ dbPath := filepath.Join(router.Dir(), srv.SessionProject()+".db")+ printSummary(toolName, text, dbPath)return 0}@@ -170,6 +171,8 @@ func printSummary(toolName, text, dbPath string) {printListDirSummary(data)case "ingest_traces":printIngestSummary(data, dbPath)+ case "index_status":+ printIndexStatusSummary(data)default:// Fallback: pretty-print the JSONprintRawJSON(text)@@ -181,7 +184,7 @@ func printArraySummary(toolName string, arr []any, dbPath string) {case "list_projects":if len(arr) == 0 {fmt.Println("No projects indexed.")- fmt.Printf(" db: %s\n", dbPath)+ fmt.Printf(" db_dir: %s\n", filepath.Dir(dbPath))return}fmt.Printf("%d project(s) indexed:\n", len(arr))@@ -195,12 +198,19 @@ func printArraySummary(toolName string, arr []any, dbPath string) {edges := jsonInt(m["edges"])indexedAt, _ := m["indexed_at"].(string)rootPath, _ := m["root_path"].(string)- fmt.Printf(" %-30s %d nodes, %d edges (indexed %s)\n", name, nodes, edges, indexedAt)+ isSession, _ := m["is_session_project"].(bool)+ sessionMarker := ""+ if isSession {+ sessionMarker = " *"+ }+ fmt.Printf(" %-30s %d nodes, %d edges (indexed %s)%s\n", name, nodes, edges, indexedAt, sessionMarker)if rootPath != "" {fmt.Printf(" %-30s %s\n", "", rootPath)}+ if dbp, ok := m["db_path"].(string); ok {+ fmt.Printf(" %-30s %s\n", "", dbp)+ }}- fmt.Printf("\n db: %s\n", dbPath)default:fmt.Printf("%d result(s)\n", len(arr))printRawJSON(mustJSON(arr))@@ -424,6 +434,49 @@ func printIngestSummary(data map[string]any, dbPath string) {fmt.Printf(" db: %s\n", dbPath)}+func printIndexStatusSummary(data map[string]any) {+ project, _ := data["project"].(string)+ status, _ := data["status"].(string)++ switch status {+ case "no_session":+ msg, _ := data["message"].(string)+ fmt.Println(msg)+ case "not_indexed":+ fmt.Printf("Project %q: not indexed\n", project)+ if dbPath, ok := data["db_path"].(string); ok {+ fmt.Printf(" expected db: %s\n", dbPath)+ }+ case "partial":+ fmt.Printf("Project %q: partially indexed (metadata missing)\n", project)+ case "indexing":+ fmt.Printf("Project %q: indexing in progress\n", project)+ if elapsed, ok := data["index_elapsed_seconds"]; ok {+ fmt.Printf(" elapsed: %ds\n", jsonInt(elapsed))+ }+ if indexType, ok := data["index_type"].(string); ok {+ fmt.Printf(" type: %s\n", indexType)+ }+ case "ready":+ nodes := jsonInt(data["nodes"])+ edges := jsonInt(data["edges"])+ indexedAt, _ := data["indexed_at"].(string)+ indexType, _ := data["index_type"].(string)+ isSession, _ := data["is_session_project"].(bool)+ fmt.Printf("Project %q: ready (%d nodes, %d edges)\n", project, nodes, edges)+ fmt.Printf(" indexed_at: %s\n", indexedAt)+ fmt.Printf(" index_type: %s\n", indexType)+ if isSession {+ fmt.Printf(" session_project: true\n")+ }+ if dbPath, ok := data["db_path"].(string); ok {+ fmt.Printf(" db: %s\n", dbPath)+ }+ default:+ printRawJSON(mustJSON(data))+ }+}+// jsonInt extracts an integer from a JSON-decoded value (float64 or int).func jsonInt(v any) int {switch n := v.(type) {diff --git a/go.mod b/go.modindex 4f340a0a3..0998db704 100644--- a/go.mod+++ b/go.mod@@ -32,3 +32,5 @@ require (golang.org/x/sys v0.37.0 // indirectgolang.org/x/tools v0.38.0 // indirect)++replace github.com/tree-sitter/go-tree-sitter => github.com/DeusData/go-tree-sitter v0.26.0-deusdata.1diff --git a/go.sum b/go.sumindex c4e451f0e..c8d1f01ac 100644--- a/go.sum+++ b/go.sum@@ -1,3 +1,5 @@+github.com/DeusData/go-tree-sitter v0.26.0-deusdata.1 h1:/cTwrXEE/3t6HYOvnHzgSZpO8MOwxFFFlz65Cc9xf9U=+github.com/DeusData/go-tree-sitter v0.26.0-deusdata.1/go.mod h1:r77ig7BikoZhHrrsjAnv8RqGti5rtSyvDHPzgTPsUuU=github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=github.com/golang-jwt/jwt/v5 v5.2.2 h1:Rl4B7itRWVtYIHFrSNd7vhTiz9UpLdi6gZhZ3wEeDy8=@@ -24,8 +26,6 @@ github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfgithub.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=github.com/tree-sitter-grammars/tree-sitter-lua v0.4.1 h1:DOxLDVTEmkLuoIHXJ65h5oyHcEK89mn9DOhlnPQRAmQ=github.com/tree-sitter-grammars/tree-sitter-lua v0.4.1/go.mod h1:hIOfn+lxpU4SRrtejLVrU2+8SAoRwNC01m3XaR/Cw0A=-github.com/tree-sitter/go-tree-sitter v0.25.0 h1:sx6kcg8raRFCvc9BnXglke6axya12krCJF5xJ2sftRU=-github.com/tree-sitter/go-tree-sitter v0.25.0/go.mod h1:r77ig7BikoZhHrrsjAnv8RqGti5rtSyvDHPzgTPsUuU=github.com/tree-sitter/tree-sitter-c v0.23.4 h1:nBPH3FV07DzAD7p0GfNvXM+Y7pNIoPenQWBpvM++t4c=github.com/tree-sitter/tree-sitter-c v0.23.4/go.mod h1:MkI5dOiIpeN94LNjeCp8ljXN/953JCwAby4bClMr6bw=github.com/tree-sitter/tree-sitter-cpp v0.23.4 h1:LaWZsiqQKvR65yHgKmnaqA+uz6tlDJTJFCyFIeZU/8w=diff --git a/internal/cypher/executor.go b/internal/cypher/executor.goindex 6a486256f..aa637259b 100644--- a/internal/cypher/executor.go+++ b/internal/cypher/executor.go@@ -87,92 +87,137 @@ func (e *Executor) tryAggregateSQL(plan *Plan) (*Result, bool) {return nil, false}- // Must have COUNT in return- var countItem *ReturnItem- var groupItems []ReturnItem- for i := range plan.ReturnSpec.Items {- item := &plan.ReturnSpec.Items[i]+ countItem, groupItems := classifyCountItems(plan.ReturnSpec.Items)+ if countItem == nil {+ return nil, false+ }++ scan, expand, filter, ok := parseFusibleSteps(plan.Steps)+ if !ok {+ return nil, false+ }++ if !validatePushability(scan, expand, filter, groupItems) {+ return nil, false+ }++ projects, err := e.Store.ListProjects()+ if err != nil {+ return nil, false+ }++ sqlCtx := newAggregateSQLContext(scan, expand, groupItems)+ cols := buildColumnNames(plan.ReturnSpec.Items)+ countCol := cols[len(cols)-1] // COUNT column is last++ allRows := make([]map[string]any, 0)+ for _, proj := range projects {+ projRows := e.executeAggregateForProject(proj.Name, &sqlCtx, scan, expand, filter, groupItems, countCol)+ allRows = append(allRows, projRows...)+ }++ // ORDER BY+ if plan.ReturnSpec.OrderBy != "" {+ orderCol := resolveOrderColumn(plan.ReturnSpec.OrderBy, plan.ReturnSpec.Items, cols)+ sortRows(allRows, orderCol, plan.ReturnSpec.OrderDir)+ }++ // LIMIT+ allRows = applyLimit(allRows, plan.ReturnSpec.Limit)++ return &Result{Columns: cols, Rows: allRows}, true+}++// classifyCountItems separates return items into the COUNT item and group-by items.+func classifyCountItems(items []ReturnItem) (countItem *ReturnItem, groupItems []ReturnItem) {+ for i := range items {+ item := &items[i]if item.Func == "COUNT" {countItem = item} else {groupItems = append(groupItems, *item)}}- if countItem == nil {- return nil, false- }-- // Identify the fusible step pattern: optional FilterWhere between Scan and Expand- steps := plan.Steps- var scan *ScanNodes- var expand *ExpandRelationship- var filter *FilterWhere+ return+}+// parseFusibleSteps identifies the ScanNodes + optional FilterWhere + ExpandRelationship+// pattern from plan steps. Returns (nil, nil, nil, false) if the pattern is not fusible.+func parseFusibleSteps(steps []PlanStep) (*ScanNodes, *ExpandRelationship, *FilterWhere, bool) {switch len(steps) {case 2:s, ok1 := steps[0].(*ScanNodes)ex, ok2 := steps[1].(*ExpandRelationship)if !ok1 || !ok2 {- return nil, false+ return nil, nil, nil, false}- scan, expand = s, ex+ return s, ex, nil, truecase 3:s, ok1 := steps[0].(*ScanNodes)f, ok2 := steps[1].(*FilterWhere)ex, ok3 := steps[2].(*ExpandRelationship)if !ok1 || !ok3 {- return nil, false+ return nil, nil, nil, false}- scan, expand = s, ex+ var filter *FilterWhereif ok2 {filter = f}+ return s, ex, filter, truedefault:- return nil, false+ return nil, nil, nil, false}+}- // Must be fixed-length (1 hop)+// validatePushability checks if the scan/expand/filter/group combination+// can be pushed entirely to SQL.+func validatePushability(scan *ScanNodes, expand *ExpandRelationship, filter *FilterWhere, groupItems []ReturnItem) bool {if expand.MinHops != 1 || expand.MaxHops != 1 {- return nil, false+ return false}if len(expand.EdgeTypes) == 0 {- return nil, false+ return false}if len(scan.Props) > 0 || len(expand.ToProps) > 0 {- return nil, false // inline property filters not supported in SQL push-down+ return false}- // All group-by items must reference SQL-pushable columnsfor _, gi := range groupItems {if gi.Property == "" {- return nil, false+ return false}if _, ok := sqlPushableColumns[gi.Property]; !ok {- return nil, false+ return false}}- // Filter conditions must all be pushableif filter != nil {for _, c := range filter.Conditions {if _, ok := sqlPushableColumns[c.Property]; !ok {- return nil, false+ return false}switch c.Operator {case "=", "CONTAINS", "STARTS WITH":// OKdefault:- return nil, false // regex, numeric not pushable+ return false}}}+ return true+}- // Build the SQL query- projects, err := e.Store.ListProjects()- if err != nil {- return nil, false- }+// aggregateSQLContext holds pre-computed SQL fragments for aggregate queries.+type aggregateSQLContext struct {+ srcCol, tgtCol string+ selectParts []string+ groupByParts []string+ srcAlias, tgtAlias string+}+// newAggregateSQLContext pre-computes direction-dependent columns and+// SELECT/GROUP BY parts for the aggregate SQL query.+func newAggregateSQLContext(scan *ScanNodes, expand *ExpandRelationship, groupItems []ReturnItem) aggregateSQLContext {dir := expand.Directionif dir == "" {dir = "outbound"@@ -184,139 +229,139 @@ func (e *Executor) tryAggregateSQL(plan *Plan) (*Result, bool) {srcCol, tgtCol = "target_id", "source_id"}- // Map variable names to table aliases- srcAlias := "src" // scan variable- tgtAlias := "tgt" // expand target variable-- // Build SELECT columns for group-by items+ srcAlias, tgtAlias := "src", "tgt"selectParts := make([]string, 0, len(groupItems)+1)groupByParts := make([]string, 0, len(groupItems))for _, gi := range groupItems {col := sqlPushableColumns[gi.Property]- var alias string+ alias := tgtAliasif gi.Variable == scan.Variable {alias = srcAlias- } else {- alias = tgtAlias}selectParts = append(selectParts, alias+"."+col)groupByParts = append(groupByParts, alias+"."+col)}selectParts = append(selectParts, "COUNT(*) as cnt")- // Accumulate results across all projects- cols := buildColumnNames(plan.ReturnSpec.Items)- countCol := cols[len(cols)-1] // COUNT column is last+ return aggregateSQLContext{+ srcCol: srcCol, tgtCol: tgtCol,+ selectParts: selectParts, groupByParts: groupByParts,+ srcAlias: srcAlias, tgtAlias: tgtAlias,+ }+}- allRows := make([]map[string]any, 0)+// executeAggregateForProject runs the aggregate SQL query for a single project.+func (e *Executor) executeAggregateForProject(+ project string, ctx *aggregateSQLContext,+ scan *ScanNodes, expand *ExpandRelationship, filter *FilterWhere,+ groupItems []ReturnItem, countCol string,+) []map[string]any {+ query, args := buildProjectAggregateSQL(project, ctx, scan, expand, filter)- for _, proj := range projects {- var sb strings.Builder- args := make([]any, 0, 10)-- sb.WriteString("SELECT ")- sb.WriteString(strings.Join(selectParts, ", "))- sb.WriteString(" FROM edges e")- sb.WriteString(fmt.Sprintf(" JOIN nodes %s ON %s.id = e.%s", srcAlias, srcAlias, srcCol))- sb.WriteString(fmt.Sprintf(" JOIN nodes %s ON %s.id = e.%s", tgtAlias, tgtAlias, tgtCol))- sb.WriteString(" WHERE e.project = ?")- args = append(args, proj.Name)-- // Edge type filter- typePlaceholders := make([]string, len(expand.EdgeTypes))- for i, et := range expand.EdgeTypes {- typePlaceholders[i] = "?"- args = append(args, et)- }- sb.WriteString(" AND e.type IN (" + strings.Join(typePlaceholders, ",") + ")")-- // Label filters- if scan.Label != "" {- sb.WriteString(fmt.Sprintf(" AND %s.label = ?", srcAlias))- args = append(args, scan.Label)- }- if expand.ToLabel != "" {- sb.WriteString(fmt.Sprintf(" AND %s.label = ?", tgtAlias))- args = append(args, expand.ToLabel)- }-- // Push-down WHERE conditions- if filter != nil {- for _, c := range filter.Conditions {- col := sqlPushableColumns[c.Property]- var alias string- if c.Variable == scan.Variable {- alias = srcAlias- } else {- alias = tgtAlias- }- switch c.Operator {- case "=":- sb.WriteString(fmt.Sprintf(" AND %s.%s = ?", alias, col))- args = append(args, c.Value)- case "CONTAINS":- sb.WriteString(fmt.Sprintf(" AND %s.%s LIKE ?", alias, col))- args = append(args, "%"+c.Value+"%")- case "STARTS WITH":- sb.WriteString(fmt.Sprintf(" AND %s.%s LIKE ?", alias, col))- args = append(args, c.Value+"%")- }- }- }-- sb.WriteString(" GROUP BY " + strings.Join(groupByParts, ", "))+ rows, qErr := e.Store.DB().Query(query, args...)+ if qErr != nil {+ return nil+ }+ defer rows.Close()- rows, qErr := e.Store.DB().Query(sb.String(), args...)- if qErr != nil {+ var result []map[string]any+ for rows.Next() {+ vals := make([]any, len(groupItems)+1)+ ptrs := make([]any, len(groupItems)+1)+ for i := range vals {+ ptrs[i] = &vals[i]+ }+ if sErr := rows.Scan(ptrs...); sErr != nil {continue}-- for rows.Next() {- // Scan group-by values + count- vals := make([]any, len(groupItems)+1)- ptrs := make([]any, len(groupItems)+1)- for i := range vals {- ptrs[i] = &vals[i]- }- if sErr := rows.Scan(ptrs...); sErr != nil {- rows.Close()- continue- }- row := make(map[string]any)- for i, gi := range groupItems {- col := gi.Variable + "." + gi.Property- if gi.Alias != "" {- col = gi.Alias- }- // Normalize []byte to string (mattn returns []byte for TEXT cols)- if b, ok := vals[i].([]byte); ok {- row[col] = string(b)- } else {- row[col] = vals[i]- }+ row := make(map[string]any)+ for i, gi := range groupItems {+ col := gi.Variable + "." + gi.Property+ if gi.Alias != "" {+ col = gi.Alias}- // Normalize COUNT to int for consistency with Go-side aggregation- switch v := vals[len(vals)-1].(type) {- case int64:- row[countCol] = int(v)- default:- row[countCol] = v+ if b, ok := vals[i].([]byte); ok {+ row[col] = string(b)+ } else {+ row[col] = vals[i]}- allRows = append(allRows, row)}- rows.Close()+ switch v := vals[len(vals)-1].(type) {+ case int64:+ row[countCol] = int(v)+ default:+ row[countCol] = v+ }+ result = append(result, row)}+ _ = rows.Err()+ return result+}- // ORDER BY- if plan.ReturnSpec.OrderBy != "" {- orderCol := resolveOrderColumn(plan.ReturnSpec.OrderBy, plan.ReturnSpec.Items, cols)- sortRows(allRows, orderCol, plan.ReturnSpec.OrderDir)+// buildProjectAggregateSQL constructs the SQL query and args for one project.+func buildProjectAggregateSQL(+ project string, ctx *aggregateSQLContext,+ scan *ScanNodes, expand *ExpandRelationship, filter *FilterWhere,+) (query string, args []any) {+ var sb strings.Builder+ args = make([]any, 0, 10)++ sb.WriteString("SELECT ")+ sb.WriteString(strings.Join(ctx.selectParts, ", "))+ sb.WriteString(" FROM edges e")+ fmt.Fprintf(&sb, " JOIN nodes %s ON %s.id = e.%s", ctx.srcAlias, ctx.srcAlias, ctx.srcCol)+ fmt.Fprintf(&sb, " JOIN nodes %s ON %s.id = e.%s", ctx.tgtAlias, ctx.tgtAlias, ctx.tgtCol)+ sb.WriteString(" WHERE e.project = ?")+ args = append(args, project)++ // Edge type filter+ typePlaceholders := make([]string, len(expand.EdgeTypes))+ for i, et := range expand.EdgeTypes {+ typePlaceholders[i] = "?"+ args = append(args, et)}+ sb.WriteString(" AND e.type IN (" + strings.Join(typePlaceholders, ",") + ")")- // LIMIT- allRows = applyLimit(allRows, plan.ReturnSpec.Limit)+ // Label filters+ if scan.Label != "" {+ fmt.Fprintf(&sb, " AND %s.label = ?", ctx.srcAlias)+ args = append(args, scan.Label)+ }+ if expand.ToLabel != "" {+ fmt.Fprintf(&sb, " AND %s.label = ?", ctx.tgtAlias)+ args = append(args, expand.ToLabel)+ }- return &Result{Columns: cols, Rows: allRows}, true+ // Push-down WHERE conditions+ if filter != nil {+ appendFilterConditions(&sb, &args, filter, scan.Variable, ctx.srcAlias, ctx.tgtAlias)+ }++ sb.WriteString(" GROUP BY " + strings.Join(ctx.groupByParts, ", "))+ query = sb.String()+ return+}++// appendFilterConditions appends WHERE conditions to the SQL query builder.+func appendFilterConditions(sb *strings.Builder, args *[]any, filter *FilterWhere, scanVar, srcAlias, tgtAlias string) {+ for _, c := range filter.Conditions {+ col := sqlPushableColumns[c.Property]+ alias := tgtAlias+ if c.Variable == scanVar {+ alias = srcAlias+ }+ switch c.Operator {+ case "=":+ fmt.Fprintf(sb, " AND %s.%s = ?", alias, col)+ *args = append(*args, c.Value)+ case "CONTAINS":+ fmt.Fprintf(sb, " AND %s.%s LIKE ?", alias, col)+ *args = append(*args, "%"+c.Value+"%")+ case "STARTS WITH":+ fmt.Fprintf(sb, " AND %s.%s LIKE ?", alias, col)+ *args = append(*args, c.Value+"%")+ }+ }}//nolint:gocognit // step dispatch with fusion/push-down is inherently branchy@@ -639,11 +684,35 @@ func (e *Executor) execExpand(s *ExpandRelationship, bindings []binding) ([]bind// expandFixedLengthBatch performs fixed-length (1 hop) expansion for all bindings// in just 2 SQL queries: one for edges, one for target nodes.func (e *Executor) expandFixedLengthBatch(s *ExpandRelationship, bindings []binding) ([]binding, error) {- // Collect all unique source node IDs+ sourceIDs := collectSourceIDs(s.FromVar, bindings)+ if len(sourceIDs) == 0 {+ return nil, nil+ }++ direction := s.Direction+ if direction == "" {+ direction = "outbound"+ }++ edgesByNode, err := e.fetchEdgesForDirection(sourceIDs, s.EdgeTypes, direction)+ if err != nil {+ return nil, err+ }++ nodeMap, err := e.Store.FindNodesByIDs(collectTargetIDs(edgesByNode, direction))+ if err != nil {+ return nil, err+ }++ return buildExpandedBindings(bindings, s, edgesByNode, nodeMap, direction), nil+}++// collectSourceIDs extracts unique node IDs from bindings for the given variable.+func collectSourceIDs(fromVar string, bindings []binding) []int64 {sourceIDs := make([]int64, 0, len(bindings))idSeen := make(map[int64]bool, len(bindings))for _, b := range bindings {- fromNode, ok := b.nodes[s.FromVar]+ fromNode, ok := b.nodes[fromVar]if !ok {continue}@@ -652,55 +721,42 @@ func (e *Executor) expandFixedLengthBatch(s *ExpandRelationship, bindings []bindsourceIDs = append(sourceIDs, fromNode.ID)}}+ return sourceIDs+}- if len(sourceIDs) == 0 {- return nil, nil- }-- direction := s.Direction- if direction == "" {- direction = "outbound"- }-- // Batch 1: fetch all edges for all source IDs- var edgesByNode map[int64][]*store.Edge- var err error+// fetchEdgesForDirection fetches edges for the given source IDs and direction.+func (e *Executor) fetchEdgesForDirection(sourceIDs []int64, edgeTypes []string, direction string) (map[int64][]*store.Edge, error) {switch direction {- case "outbound":- edgesByNode, err = e.Store.FindEdgesBySourceIDs(sourceIDs, s.EdgeTypes)case "inbound":- edgesByNode, err = e.Store.FindEdgesByTargetIDs(sourceIDs, s.EdgeTypes)+ return e.Store.FindEdgesByTargetIDs(sourceIDs, edgeTypes)case "any":- outEdges, outErr := e.Store.FindEdgesBySourceIDs(sourceIDs, s.EdgeTypes)- if outErr != nil {- return nil, outErr+ outEdges, err := e.Store.FindEdgesBySourceIDs(sourceIDs, edgeTypes)+ if err != nil {+ return nil, err}- inEdges, inErr := e.Store.FindEdgesByTargetIDs(sourceIDs, s.EdgeTypes)- if inErr != nil {- return nil, inErr+ inEdges, err := e.Store.FindEdgesByTargetIDs(sourceIDs, edgeTypes)+ if err != nil {+ return nil, err}- edgesByNode = outEdgesfor id, edges := range inEdges {- edgesByNode[id] = append(edgesByNode[id], edges...)+ outEdges[id] = append(outEdges[id], edges...)}- default:- edgesByNode, err = e.Store.FindEdgesBySourceIDs(sourceIDs, s.EdgeTypes)- }- if err != nil {- return nil, err+ return outEdges, nil+ default: // "outbound" or unspecified+ return e.Store.FindEdgesBySourceIDs(sourceIDs, edgeTypes)}+}- // Collect all target node IDs+// collectTargetIDs extracts all target node IDs from edge batches.+func collectTargetIDs(edgesByNode map[int64][]*store.Edge, direction string) []int64 {targetIDSet := make(map[int64]bool)for _, edges := range edgesByNode {for _, edge := range edges {- tid := edgeTargetID(edge, 0, direction)if direction == "any" {- // For "any", we need to check per-sourcetargetIDSet[edge.SourceID] = truetargetIDSet[edge.TargetID] = true} else {- targetIDSet[tid] = true+ targetIDSet[edgeTargetID(edge, 0, direction)] = true}}}@@ -708,14 +764,11 @@ func (e *Executor) expandFixedLengthBatch(s *ExpandRelationship, bindings []bindfor id := range targetIDSet {targetIDs = append(targetIDs, id)}+ return targetIDs+}- // Batch 2: fetch all target nodes- nodeMap, err := e.Store.FindNodesByIDs(targetIDs)- if err != nil {- return nil, err- }-- // Build results per binding+// buildExpandedBindings creates result bindings by matching edges to target nodes.+func buildExpandedBindings(bindings []binding, s *ExpandRelationship, edgesByNode map[int64][]*store.Edge, nodeMap map[int64]*store.Node, direction string) []binding {result := make([]binding, 0, len(bindings))for _, b := range bindings {fromNode, ok := b.nodes[s.FromVar]@@ -733,10 +786,7 @@ func (e *Executor) expandFixedLengthBatch(s *ExpandRelationship, bindings []bindseen[targetID] = truenode, exists := nodeMap[targetID]- if !exists {- continue- }- if s.ToLabel != "" && node.Label != s.ToLabel {+ if !exists || (s.ToLabel != "" && node.Label != s.ToLabel) {continue}if len(s.ToProps) > 0 && !nodeMatchesProps(node, s.ToProps) {@@ -757,7 +807,7 @@ func (e *Executor) expandFixedLengthBatch(s *ExpandRelationship, bindings []bindbreak}}- return result, nil+ return result}func (e *Executor) expandVariableLength(b binding, fromNode *store.Node, s *ExpandRelationship) ([]binding, error) {@@ -805,7 +855,6 @@ func (e *Executor) expandVariableLength(b binding, fromNode *store.Node, s *Expareturn result, nil}-// edgeTargetID returns the ID of the node on the "other end" of the edge relative to nodeID.func edgeTargetID(edge *store.Edge, nodeID int64, direction string) int64 {switch direction {@@ -1171,11 +1220,31 @@ func resolveEdgeItemValue(edge *store.Edge, property string) any {// resolveOrderColumn maps an ORDER BY field to the actual column name.func resolveOrderColumn(orderBy string, items []ReturnItem, cols []string) string {+ // 1. Try alias matchfor i, item := range items {if item.Alias == orderBy {return cols[i]}}+ // 2. Try matching aggregate expression (e.g. "COUNT(r)")+ for i, item := range items {+ if item.Func == "COUNT" {+ expr := "COUNT(" + item.Variable + ")"+ if orderBy == expr {+ return cols[i]+ }+ }+ }+ // 3. Try matching variable.property to column name+ for i, item := range items {+ varProp := item.Variable+ if item.Property != "" {+ varProp += "." + item.Property+ }+ if orderBy == varProp {+ return cols[i]+ }+ }return orderBy}@@ -1213,7 +1282,8 @@ func (e *Executor) aggregateResults(bindings []binding, ret *ReturnClause) (*Res// ORDER BYif ret.OrderBy != "" {- sortRows(rows, ret.OrderBy, ret.OrderDir)+ orderCol := resolveOrderColumn(ret.OrderBy, ret.Items, cols)+ sortRows(rows, orderCol, ret.OrderDir)}// LIMITdiff --git a/internal/cypher/parser.go b/internal/cypher/parser.goindex 1d87e97e0..184192d81 100644--- a/internal/cypher/parser.go+++ b/internal/cypher/parser.go@@ -469,30 +469,12 @@ func (p *Parser) parseReturn() (*ReturnClause, error) {// Optional ORDER BYif p.peek().Type == TokOrder {- p.advance() // consume ORDER- if err := p.expect(TokBy); err != nil {- return nil, fmt.Errorf("expected BY after ORDER: %w", err)- }- orderTok := p.advance()- if orderTok.Type != TokIdent {- return nil, fmt.Errorf("expected field name for ORDER BY, got %q", orderTok.Value)- }- orderField := orderTok.Value- if p.peek().Type == TokDot {- p.advance() // consume .- propTok := p.advance()- orderField = orderField + "." + propTok.Value- }- r.OrderBy = orderField-- // Optional ASC/DESC- if p.peek().Type == TokAsc {- r.OrderDir = "ASC"- p.advance()- } else if p.peek().Type == TokDesc {- r.OrderDir = "DESC"- p.advance()+ orderBy, orderDir, err := p.parseOrderBy()+ if err != nil {+ return nil, err}+ r.OrderBy = orderBy+ r.OrderDir = orderDir}// Optional LIMIT@@ -575,3 +557,57 @@ func (p *Parser) parseCountItem() (ReturnItem, error) {return item, nil}++// parseOrderBy parses ORDER BY <field|COUNT(var)> [ASC|DESC].+func (p *Parser) parseOrderBy() (orderBy, orderDir string, err error) {+ p.advance() // consume ORDER+ if err := p.expect(TokBy); err != nil {+ return "", "", fmt.Errorf("expected BY after ORDER: %w", err)+ }++ orderField, err := p.parseOrderField()+ if err != nil {+ return "", "", err+ }++ // Optional ASC/DESC+ dir := ""+ if p.peek().Type == TokAsc {+ dir = "ASC"+ p.advance()+ } else if p.peek().Type == TokDesc {+ dir = "DESC"+ p.advance()+ }+ return orderField, dir, nil+}++// parseOrderField parses the field expression in ORDER BY: either COUNT(var) or var[.prop].+func (p *Parser) parseOrderField() (string, error) {+ if p.peek().Type == TokCount {+ p.advance() // consume COUNT+ if err := p.expect(TokLParen); err != nil {+ return "", fmt.Errorf("expected '(' after COUNT in ORDER BY: %w", err)+ }+ varTok := p.advance()+ if varTok.Type != TokIdent {+ return "", fmt.Errorf("expected variable in COUNT(), got %q", varTok.Value)+ }+ if err := p.expect(TokRParen); err != nil {+ return "", fmt.Errorf("expected ')' after COUNT variable in ORDER BY: %w", err)+ }+ return "COUNT(" + varTok.Value + ")", nil+ }++ orderTok := p.advance()+ if orderTok.Type != TokIdent {+ return "", fmt.Errorf("expected field name for ORDER BY, got %q", orderTok.Value)+ }+ field := orderTok.Value+ if p.peek().Type == TokDot {+ p.advance() // consume .+ propTok := p.advance()+ field += "." + propTok.Value+ }+ return field, nil+}diff --git a/internal/httplink/httplink.go b/internal/httplink/httplink.goindex e22826552..11b1b56a6 100644--- a/internal/httplink/httplink.go+++ b/internal/httplink/httplink.go@@ -86,6 +86,10 @@ var (// Express.js routes: app.get("/path", router.post("/path"expressRouteRe = regexp.MustCompile(`\w+\.(get|post|put|delete|patch)\(\s*["'` + "`" + `]([^"'` + "`" + `]+)["'` + "`" + `]`)+ // Express.js handler reference: captures last named argument (handler, not middleware)+ // app.get("/path", handler) or app.get("/path", middleware, handler)+ expressHandlerRe = regexp.MustCompile(`\w+\.(get|post|put|delete|patch)\(\s*["'` + "`" + `][^"'` + "`" + `]+["'` + "`" + `]\s*(?:,\s*[\w.]+)*,\s*([\w.]+)\s*\)`)+// Java Spring annotations: @GetMapping("/path"), @PostMapping, @RequestMappingspringMappingRe = regexp.MustCompile(`@(Get|Post|Put|Delete|Patch|Request)Mapping\(\s*(?:value\s*=\s*)?["']([^"']+)["']`)@@ -95,6 +99,10 @@ var (// PHP Laravel routes: Route::get("/path", Route::post("/path"laravelRouteRe = regexp.MustCompile(`Route::(get|post|put|delete|patch)\(\s*["']([^"']+)["']`)+ // Laravel handler: Route::get("/path", [Controller::class, "method"]) or "Controller@method"+ laravelHandlerArrayRe = regexp.MustCompile(`Route::(get|post|put|delete|patch)\(\s*["'][^"']+["']\s*,\s*\[(\w+)::class\s*,\s*["'](\w+)["']\]`)+ laravelHandlerAtRe = regexp.MustCompile(`Route::(get|post|put|delete|patch)\(\s*["'][^"']+["']\s*,\s*["'](\w+)@(\w+)["']`)+// URL patterns in source: https://host/path or http://host/path — captures domain and pathurlRe = regexp.MustCompile(`https?://([a-zA-Z0-9.\-]+)(/[a-zA-Z0-9_/:.\-]+)`)@@ -201,7 +209,8 @@ func (l *Linker) insertRouteNodes(routes []RouteHandler) {TargetID: routeID,Type: "HANDLES",}); edgeErr != nil {- slog.Warn("httplink.handles_edge.err", "err", edgeErr)+ // FK failures expected: LastInsertId() can return stale IDs for upserted Route nodes+ slog.Info("httplink.handles_edge.skip", "route", routeQN)}// Mark handler as entry point (for dead code detection)@@ -367,14 +376,35 @@ func resolveGroupPrefix(line, method, path string, groupPrefixes map[string]stri// extractExpressRoutes extracts route registrations from JS/TS source (Express/Koa patterns).func extractExpressRoutes(f *store.Node, source string) []RouteHandler {- matches := expressRouteRe.FindAllStringSubmatch(source, -1)- routes := make([]RouteHandler, 0, len(matches))- for _, m := range matches {+ // Build a per-line handler ref map for quick lookup+ handlerRefs := map[string]string{} // "METHOD path" → handler ref+ for _, line := range strings.Split(source, "\n") {+ hm := expressHandlerRe.FindStringSubmatch(line)+ if hm != nil {+ key := strings.ToUpper(hm[1]) + " " + hm[0] // unique enough per line+ handlerRefs[key] = hm[2]+ }+ }++ routes := make([]RouteHandler, 0, 4)+ for _, line := range strings.Split(source, "\n") {+ rm := expressRouteRe.FindStringSubmatch(line)+ if rm == nil {+ continue+ }++ var handlerRef string+ hm := expressHandlerRe.FindStringSubmatch(line)+ if hm != nil {+ handlerRef = hm[2]+ }+routes = append(routes, RouteHandler{- Path: m[2],- Method: strings.ToUpper(m[1]),+ Path: rm[2],+ Method: strings.ToUpper(rm[1]),FunctionName: f.Name,QualifiedName: f.QualifiedName,+ HandlerRef: handlerRef,})}return routes@@ -444,14 +474,27 @@ func extractRustRoutes(f *store.Node) []RouteHandler {// extractLaravelRoutes extracts route registrations from PHP Laravel source.func extractLaravelRoutes(f *store.Node, source string) []RouteHandler {- matches := laravelRouteRe.FindAllStringSubmatch(source, -1)- routes := make([]RouteHandler, 0, len(matches))- for _, m := range matches {+ routes := make([]RouteHandler, 0, 4)+ for _, line := range strings.Split(source, "\n") {+ rm := laravelRouteRe.FindStringSubmatch(line)+ if rm == nil {+ continue+ }++ // Try to extract handler reference from [Controller::class, "method"] or "Controller@method"+ var handlerRef string+ if am := laravelHandlerArrayRe.FindStringSubmatch(line); am != nil {+ handlerRef = am[3] // method name from [Controller::class, "method"]+ } else if atm := laravelHandlerAtRe.FindStringSubmatch(line); atm != nil {+ handlerRef = atm[3] // method name from "Controller@method"+ }+routes = append(routes, RouteHandler{- Path: m[2],- Method: strings.ToUpper(m[1]),+ Path: rm[2],+ Method: strings.ToUpper(rm[1]),FunctionName: f.Name,QualifiedName: f.QualifiedName,+ HandlerRef: handlerRef,})}return routesdiff --git a/internal/lang/cpp.go b/internal/lang/cpp.goindex 71ea8075f..26b6a1cca 100644--- a/internal/lang/cpp.go+++ b/internal/lang/cpp.go@@ -37,5 +37,7 @@ func init() {ImportNodeTypes: []string{"preproc_include", "template_function", "declaration"},ImportFromTypes: []string{"preproc_include", "template_function", "declaration"},PackageIndicators: []string{"CMakeLists.txt", "Makefile", "*.vcxproj", "conanfile.txt"},++ BranchingNodeTypes: []string{"if_statement", "for_statement", "for_range_loop", "while_statement", "switch_statement", "case_statement", "try_statement", "catch_clause"},})}diff --git a/internal/lang/csharp.go b/internal/lang/csharp.goindex 18583daa7..314395d82 100644--- a/internal/lang/csharp.go+++ b/internal/lang/csharp.go@@ -23,5 +23,10 @@ func init() {CallNodeTypes: []string{"invocation_expression"},ImportNodeTypes: []string{"using_directive"},ImportFromTypes: []string{"using_directive"},++ BranchingNodeTypes: []string{"if_statement", "for_statement", "foreach_statement", "while_statement", "switch_statement", "case_switch_label", "try_statement", "catch_clause"},+ AssignmentNodeTypes: []string{"assignment_expression"},+ ThrowNodeTypes: []string{"throw_statement", "throw_expression"},+ DecoratorNodeTypes: []string{"attribute"},})}diff --git a/internal/lang/go_lang.go b/internal/lang/go_lang.goindex 8d0dd5ea6..00dac99eb 100644--- a/internal/lang/go_lang.go+++ b/internal/lang/go_lang.go@@ -11,5 +11,10 @@ func init() {CallNodeTypes: []string{"call_expression"},ImportNodeTypes: []string{"import_declaration"},ImportFromTypes: []string{"import_declaration"},++ BranchingNodeTypes: []string{"if_statement", "for_statement", "switch_expression", "select_statement", "case_clause", "default_clause"},+ VariableNodeTypes: []string{"var_declaration", "const_declaration"},+ AssignmentNodeTypes: []string{"assignment_statement", "short_var_declaration"},+ EnvAccessFunctions: []string{"os.Getenv", "os.LookupEnv"},})}diff --git a/internal/lang/java.go b/internal/lang/java.goindex 630f64143..3674b3dc6 100644--- a/internal/lang/java.go+++ b/internal/lang/java.go@@ -12,10 +12,17 @@ func init() {"annotation_type_declaration","record_declaration",},- FieldNodeTypes: []string{"field_declaration"},+ FieldNodeTypes: []string{"field_declaration"},ModuleNodeTypes: []string{"program"},CallNodeTypes: []string{"method_invocation"},ImportNodeTypes: []string{"import_declaration"},ImportFromTypes: []string{"import_declaration"},++ BranchingNodeTypes: []string{"if_statement", "for_statement", "enhanced_for_statement", "while_statement", "switch_expression", "switch_block_statement_group", "try_statement", "catch_clause"},+ AssignmentNodeTypes: []string{"assignment_expression"},+ ThrowNodeTypes: []string{"throw_statement"},+ ThrowsClauseField: "throws",+ DecoratorNodeTypes: []string{"marker_annotation", "annotation"},+ EnvAccessFunctions: []string{"System.getenv", "System.getProperty"},})}diff --git a/internal/lang/javascript.go b/internal/lang/javascript.goindex 124346ffc..e2d9dddb6 100644--- a/internal/lang/javascript.go+++ b/internal/lang/javascript.go@@ -16,5 +16,11 @@ func init() {CallNodeTypes: []string{"call_expression"},ImportNodeTypes: []string{"import_statement", "lexical_declaration", "export_statement"},ImportFromTypes: []string{"import_statement", "lexical_declaration", "export_statement"},++ BranchingNodeTypes: []string{"if_statement", "for_statement", "for_in_statement", "while_statement", "switch_statement", "case_clause", "try_statement", "catch_clause"},+ VariableNodeTypes: []string{"lexical_declaration", "variable_declaration"},+ AssignmentNodeTypes: []string{"assignment_expression", "augmented_assignment_expression"},+ ThrowNodeTypes: []string{"throw_statement"},+ EnvAccessMemberPatterns: []string{"process.env"},})}diff --git a/internal/lang/lang.go b/internal/lang/lang.goindex b0caec89d..8ffb89219 100644--- a/internal/lang/lang.go+++ b/internal/lang/lang.go@@ -36,6 +36,23 @@ type LanguageSpec struct {ImportNodeTypes []stringImportFromTypes []stringPackageIndicators []string++ // BranchingNodeTypes lists AST node kinds counted for complexity metric.+ BranchingNodeTypes []string+ // VariableNodeTypes lists module-level variable declaration node kinds.+ VariableNodeTypes []string+ // AssignmentNodeTypes lists assignment expression/statement node kinds.+ AssignmentNodeTypes []string+ // ThrowNodeTypes lists throw/raise statement node kinds.+ ThrowNodeTypes []string+ // ThrowsClauseField is the field name for declared throws (e.g. Java "throws").+ ThrowsClauseField string+ // DecoratorNodeTypes lists decorator/annotation node kinds.+ DecoratorNodeTypes []string+ // EnvAccessFunctions lists function names used to read env vars (e.g. "os.Getenv").+ EnvAccessFunctions []string+ // EnvAccessMemberPatterns lists member access patterns for env vars (e.g. "process.env").+ EnvAccessMemberPatterns []string}// registry maps file extensions to language specs.diff --git a/internal/lang/lua.go b/internal/lang/lua.goindex 9bf8b1bad..d01e21561 100644--- a/internal/lang/lua.go+++ b/internal/lang/lua.go@@ -9,5 +9,7 @@ func init() {ModuleNodeTypes: []string{"chunk"},CallNodeTypes: []string{"function_call"},ImportNodeTypes: []string{"function_call"},++ BranchingNodeTypes: []string{"if_statement", "for_statement", "for_in_statement", "while_statement", "repeat_statement"},})}diff --git a/internal/lang/php.go b/internal/lang/php.goindex bdc5cfd05..c1be1e863 100644--- a/internal/lang/php.go+++ b/internal/lang/php.go@@ -23,5 +23,8 @@ func init() {"function_call_expression","nullsafe_member_call_expression",},++ BranchingNodeTypes: []string{"if_statement", "for_statement", "foreach_statement", "while_statement", "switch_statement", "case_statement", "try_statement", "catch_clause"},+ ThrowNodeTypes: []string{"throw_expression"},})}diff --git a/internal/lang/python.go b/internal/lang/python.goindex f265fd1ea..633a8d70e 100644--- a/internal/lang/python.go+++ b/internal/lang/python.go@@ -11,5 +11,13 @@ func init() {ImportNodeTypes: []string{"import_statement"},ImportFromTypes: []string{"import_from_statement"},PackageIndicators: []string{"__init__.py"},++ BranchingNodeTypes: []string{"if_statement", "for_statement", "while_statement", "try_statement", "except_clause", "with_statement", "elif_clause"},+ VariableNodeTypes: []string{"assignment", "augmented_assignment"},+ AssignmentNodeTypes: []string{"assignment", "augmented_assignment"},+ ThrowNodeTypes: []string{"raise_statement"},+ DecoratorNodeTypes: []string{"decorator"},+ EnvAccessFunctions: []string{"os.getenv", "os.environ.get"},+ EnvAccessMemberPatterns: []string{"os.environ"},})}diff --git a/internal/lang/rust.go b/internal/lang/rust.goindex b6438d658..a2a3509d4 100644--- a/internal/lang/rust.go+++ b/internal/lang/rust.go@@ -17,11 +17,16 @@ func init() {"impl_item","type_item",},- FieldNodeTypes: []string{"field_declaration"},+ FieldNodeTypes: []string{"field_declaration"},ModuleNodeTypes: []string{"source_file", "mod_item"},CallNodeTypes: []string{"call_expression", "macro_invocation"},ImportNodeTypes: []string{"use_declaration", "extern_crate_declaration"},ImportFromTypes: []string{"use_declaration"},PackageIndicators: []string{"Cargo.toml"},++ BranchingNodeTypes: []string{"if_expression", "for_expression", "while_expression", "loop_expression", "match_expression", "match_arm"},+ VariableNodeTypes: []string{"static_item", "const_item"},+ AssignmentNodeTypes: []string{"assignment_expression", "compound_assignment_expr"},+ EnvAccessFunctions: []string{"env::var", "std::env::var"},})}diff --git a/internal/lang/scala.go b/internal/lang/scala.goindex e59a33fec..4aa5c66d3 100644--- a/internal/lang/scala.go+++ b/internal/lang/scala.go@@ -19,5 +19,8 @@ func init() {},ImportNodeTypes: []string{"import_declaration"},ImportFromTypes: []string{"import_declaration"},++ BranchingNodeTypes: []string{"if_expression", "for_expression", "while_expression", "match_expression", "case_clause", "try_expression", "catch_clause"},+ ThrowNodeTypes: []string{"throw_expression"},})}diff --git a/internal/lang/tsx.go b/internal/lang/tsx.goindex 14c005cd6..1461cae07 100644--- a/internal/lang/tsx.go+++ b/internal/lang/tsx.go@@ -25,5 +25,12 @@ func init() {CallNodeTypes: []string{"call_expression"},ImportNodeTypes: []string{"import_statement", "lexical_declaration", "export_statement"},ImportFromTypes: []string{"import_statement", "lexical_declaration", "export_statement"},++ BranchingNodeTypes: []string{"if_statement", "for_statement", "for_in_statement", "while_statement", "switch_statement", "case_clause", "try_statement", "catch_clause"},+ VariableNodeTypes: []string{"lexical_declaration", "variable_declaration"},+ AssignmentNodeTypes: []string{"assignment_expression", "augmented_assignment_expression"},+ ThrowNodeTypes: []string{"throw_statement"},+ DecoratorNodeTypes: []string{"decorator"},+ EnvAccessMemberPatterns: []string{"process.env"},})}diff --git a/internal/lang/typescript.go b/internal/lang/typescript.goindex cb3a9a220..f93cde1ff 100644--- a/internal/lang/typescript.go+++ b/internal/lang/typescript.go@@ -25,5 +25,12 @@ func init() {CallNodeTypes: []string{"call_expression"},ImportNodeTypes: []string{"import_statement", "lexical_declaration", "export_statement"},ImportFromTypes: []string{"import_statement", "lexical_declaration", "export_statement"},++ BranchingNodeTypes: []string{"if_statement", "for_statement", "for_in_statement", "while_statement", "switch_statement", "case_clause", "try_statement", "catch_clause"},+ VariableNodeTypes: []string{"lexical_declaration", "variable_declaration"},+ AssignmentNodeTypes: []string{"assignment_expression", "augmented_assignment_expression"},+ ThrowNodeTypes: []string{"throw_statement"},+ DecoratorNodeTypes: []string{"decorator"},+ EnvAccessMemberPatterns: []string{"process.env"},})}diff --git a/internal/parser/parser.go b/internal/parser/parser.goindex e8a2529e2..8a23e7419 100644--- a/internal/parser/parser.go+++ b/internal/parser/parser.go@@ -23,6 +23,7 @@ import (var (languagesOnce sync.Oncelanguages map[lang.Language]*tree_sitter.Language+ parserPools map[lang.Language]*sync.Pool)func initLanguages() {@@ -41,6 +42,20 @@ func initLanguages() {lang.Lua: tree_sitter.NewLanguage(tree_sitter_lua.Language()),lang.Scala: tree_sitter.NewLanguage(tree_sitter_scala.Language()),}++ parserPools = make(map[lang.Language]*sync.Pool, len(languages))+ for l, tsLang := range languages {+ tsLang := tsLang+ parserPools[l] = &sync.Pool{+ New: func() any {+ p := tree_sitter.NewParser()+ if err := p.SetLanguage(tsLang); err != nil {+ panic(fmt.Sprintf("set language: %v", err))+ }+ return p+ },+ }+ }})}@@ -56,20 +71,22 @@ func GetLanguage(l lang.Language) (*tree_sitter.Language, error) {// Parse parses source code into a tree-sitter AST Tree.// The caller must call tree.Close() when done.+// Parsers are pooled per language via sync.Pool to avoid per-file allocation.func Parse(l lang.Language, source []byte) (*tree_sitter.Tree, error) {- tsLang, err := GetLanguage(l)- if err != nil {- return nil, err- }-- p := tree_sitter.NewParser()- defer p.Close()+ initLanguages()- if err := p.SetLanguage(tsLang); err != nil {- return nil, fmt.Errorf("set language %s: %w", l, err)+ pool, ok := parserPools[l]+ if !ok {+ return nil, fmt.Errorf("unsupported language: %s", l)}+ p, _ := pool.Get().(*tree_sitter.Parser)+ if p == nil {+ return nil, fmt.Errorf("failed to get parser for language %s", l)+ }tree := p.Parse(source, nil)+ pool.Put(p)+if tree == nil {return nil, fmt.Errorf("parse failed for language %s", l)}diff --git a/internal/pipeline/communities.go b/internal/pipeline/communities.gonew file mode 100644index 000000000..606403ce1--- /dev/null+++ b/internal/pipeline/communities.go@@ -0,0 +1,301 @@+package pipeline++import (+ "fmt"+ "log/slog"+ "math"+ "sort"++ "github.com/DeusData/codebase-memory-mcp/internal/store"+)++// passCommunities runs Leiden-style community detection on the CALLS graph+// and creates Community nodes + MEMBER_OF edges.+func (p *Pipeline) passCommunities() {+ slog.Info("pass.communities")++ // Load CALLS edges+ callEdges, err := p.Store.FindEdgesByType(p.ProjectName, "CALLS")+ if err != nil || len(callEdges) == 0 {+ slog.Info("pass.communities.skip", "reason", "no_calls")+ return+ }++ // Build adjacency list (undirected for community detection)+ adj := make(map[int64]map[int64]bool)+ allNodes := make(map[int64]bool)+ for _, e := range callEdges {+ allNodes[e.SourceID] = true+ allNodes[e.TargetID] = true+ if adj[e.SourceID] == nil {+ adj[e.SourceID] = make(map[int64]bool)+ }+ if adj[e.TargetID] == nil {+ adj[e.TargetID] = make(map[int64]bool)+ }+ adj[e.SourceID][e.TargetID] = true+ adj[e.TargetID][e.SourceID] = true+ }++ // Run Louvain/Leiden community detection+ communities := louvainCommunities(adj, allNodes)++ // Create Community nodes + MEMBER_OF edges+ communityCount, memberOfCount := p.storeCommunities(communities)+ slog.Info("pass.communities.done", "communities", communityCount, "member_of", memberOfCount)+}++// louvainCommunities implements a simplified Louvain algorithm for community detection.+// Returns a map of community_id → []node_id.+func louvainCommunities(adj map[int64]map[int64]bool, allNodes map[int64]bool) map[int][]int64 {+ nodeCommunity := make(map[int64]int, len(allNodes))+ communityID := 0+ for nodeID := range allNodes {+ nodeCommunity[nodeID] = communityID+ communityID+++ }++ totalEdges := 0+ for _, neighbors := range adj {+ totalEdges += len(neighbors)+ }+ m := float64(totalEdges) / 2.0+ if m == 0 {+ m = 1+ }++ improved := true+ for iteration := 0; improved && iteration < 50; iteration++ {+ improved = louvainIteration(adj, allNodes, nodeCommunity, m)+ }++ return groupAndFilter(nodeCommunity)+}++// louvainIteration runs one pass of greedy modularity optimization.+// Returns true if any node changed community.+func louvainIteration(adj map[int64]map[int64]bool, allNodes map[int64]bool, nodeCommunity map[int64]int, m float64) bool {+ improved := false+ for nodeID := range allNodes {+ currentComm := nodeCommunity[nodeID]++ neighborComms := make(map[int]bool)+ for neighborID := range adj[nodeID] {+ neighborComms[nodeCommunity[neighborID]] = true+ }++ bestComm, bestGain := currentComm, 0.0+ ki := float64(len(adj[nodeID]))++ for comm := range neighborComms {+ if comm == currentComm {+ continue+ }+ gain := modularityGain(nodeID, comm, adj, nodeCommunity, ki, m)+ if gain > bestGain {+ bestGain = gain+ bestComm = comm+ }+ }++ if bestComm != currentComm && bestGain > 1e-10 {+ nodeCommunity[nodeID] = bestComm+ improved = true+ }+ }+ return improved+}++// modularityGain calculates the gain from moving nodeID to targetComm.+func modularityGain(nodeID int64, targetComm int, adj map[int64]map[int64]bool, nodeCommunity map[int64]int, ki, m float64) float64 {+ kiIn := 0.0+ sumTot := 0.0+ for otherID, otherComm := range nodeCommunity {+ if otherComm != targetComm {+ continue+ }+ if adj[nodeID][otherID] {+ kiIn+++ }+ sumTot += float64(len(adj[otherID]))+ }+ return kiIn/m - ki*sumTot/(2*m*m)+}++// groupAndFilter groups nodes by community and filters out singletons.+func groupAndFilter(nodeCommunity map[int64]int) map[int][]int64 {+ communities := make(map[int][]int64)+ for nodeID, comm := range nodeCommunity {+ communities[comm] = append(communities[comm], nodeID)+ }++ filtered := make(map[int][]int64)+ idx := 0+ for _, members := range communities {+ if len(members) >= 2 {+ filtered[idx] = members+ idx+++ }+ }+ return filtered+}++// storeCommunities creates Community nodes and MEMBER_OF edges in the database.+func (p *Pipeline) storeCommunities(communities map[int][]int64) (communityCount, memberOfCount int) {+ if len(communities) == 0 {+ return 0, 0+ }++ // Collect all member node IDs for batch lookup+ var allMemberIDs []int64+ for _, members := range communities {+ allMemberIDs = append(allMemberIDs, members...)+ }+ nodeMap, _ := p.Store.FindNodesByIDs(allMemberIDs)++ communityNodes := make([]*store.Node, 0, len(communities))+ memberEdges := make([]pendingEdge, 0, len(allMemberIDs))++ for commIdx, memberIDs := range communities {+ // Find top symbols by name for labeling+ topNames := topMemberNames(memberIDs, nodeMap, 5)++ commName := fmt.Sprintf("community_%d", commIdx)+ if len(topNames) > 0 {+ commName = topNames[0] + "_cluster"+ }++ commQN := fmt.Sprintf("%s.__community__.%d", p.ProjectName, commIdx)++ // Calculate cohesion: ratio of internal edges to possible edges+ cohesion := communityCohesion(memberIDs, nodeMap)++ communityNodes = append(communityNodes, &store.Node{+ Project: p.ProjectName,+ Label: "Community",+ Name: commName,+ QualifiedName: commQN,+ Properties: map[string]any{+ "cohesion": math.Round(cohesion*100) / 100,+ "symbol_count": len(memberIDs),+ "top_symbols": topNames,+ },+ })++ for _, memberID := range memberIDs {+ memberNode := nodeMap[memberID]+ if memberNode == nil {+ continue+ }+ memberEdges = append(memberEdges, pendingEdge{+ SourceQN: memberNode.QualifiedName,+ TargetQN: commQN,+ Type: "MEMBER_OF",+ })++ // Also store community_id on the member node (via properties update)+ if memberNode.Properties == nil {+ memberNode.Properties = make(map[string]any)+ }+ memberNode.Properties["community_id"] = commIdx+ }+ }++ // Batch insert community nodes+ idMap, err := p.Store.UpsertNodeBatch(communityNodes)+ if err != nil {+ slog.Warn("pass.communities.upsert.err", "err", err)+ return 0, 0+ }++ // Resolve and insert MEMBER_OF edges+ var edges []*store.Edge+ for _, pe := range memberEdges {+ srcQN := pe.SourceQN+ tgtQN := pe.TargetQN++ srcNode, _ := p.Store.FindNodeByQN(p.ProjectName, srcQN)+ tgtID, tgtOK := idMap[tgtQN]++ if srcNode != nil && tgtOK {+ edges = append(edges, &store.Edge{+ Project: p.ProjectName,+ SourceID: srcNode.ID,+ TargetID: tgtID,+ Type: "MEMBER_OF",+ })+ }+ }++ if len(edges) > 0 {+ if err := p.Store.InsertEdgeBatch(edges); err != nil {+ slog.Warn("pass.communities.edges.err", "err", err)+ }+ }++ return len(communityNodes), len(edges)+}++func topMemberNames(memberIDs []int64, nodeMap map[int64]*store.Node, limit int) []string {+ type entry struct {+ name string+ label string+ }+ var entries []entry+ for _, id := range memberIDs {+ n := nodeMap[id]+ if n != nil {+ entries = append(entries, entry{n.Name, n.Label})+ }+ }++ // Sort: Classes first, then Functions, alphabetical+ sort.Slice(entries, func(i, j int) bool {+ if entries[i].label != entries[j].label {+ // Prefer Class/Interface over Function/Method+ return labelPriority(entries[i].label) < labelPriority(entries[j].label)+ }+ return entries[i].name < entries[j].name+ })++ names := make([]string, 0, limit)+ for i, e := range entries {+ if i >= limit {+ break+ }+ names = append(names, e.name)+ }+ return names+}++func labelPriority(label string) int {+ switch label {+ case "Class":+ return 0+ case "Interface":+ return 1+ case "Type":+ return 2+ case "Function":+ return 3+ case "Method":+ return 4+ default:+ return 5+ }+}++func communityCohesion(memberIDs []int64, nodeMap map[int64]*store.Node) float64 {+ n := len(memberIDs)+ if n < 2 {+ return 1.0+ }+ // Simplified cohesion: proportion of members with known types+ knownCount := 0+ for _, id := range memberIDs {+ if nodeMap[id] != nil {+ knownCount+++ }+ }+ return float64(knownCount) / float64(n)+}diff --git a/internal/pipeline/configures.go b/internal/pipeline/configures.gonew file mode 100644index 000000000..608283e3b--- /dev/null+++ b/internal/pipeline/configures.go@@ -0,0 +1,256 @@+package pipeline++import (+ "log/slog"+ "runtime"+ "strings"++ tree_sitter "github.com/tree-sitter/go-tree-sitter"+ "golang.org/x/sync/errgroup"++ "github.com/DeusData/codebase-memory-mcp/internal/fqn"+ "github.com/DeusData/codebase-memory-mcp/internal/lang"+ "github.com/DeusData/codebase-memory-mcp/internal/parser"+)++// passConfigures creates CONFIGURES edges from functions that read env vars+// to config Module nodes that define them.+func (p *Pipeline) passConfigures() {+ slog.Info("pass.configures")++ // Stage 1: Build env key → module QN index from Module constants+ envIndex := p.buildEnvIndex()+ if len(envIndex) == 0 {+ slog.Info("pass.configures.skip", "reason", "no_env_bindings")+ return+ }++ // Stage 2: Parallel per-file AST walk for env access calls+ type fileEntry struct {+ relPath string+ cached *cachedAST+ }+ files := make([]fileEntry, 0, len(p.astCache))+ for relPath, cached := range p.astCache {+ spec := lang.ForLanguage(cached.Language)+ if spec == nil {+ continue+ }+ if len(spec.EnvAccessFunctions) == 0 && len(spec.EnvAccessMemberPatterns) == 0 {+ continue+ }+ files = append(files, fileEntry{relPath, cached})+ }++ if len(files) == 0 {+ return+ }++ results := make([][]resolvedEdge, len(files))+ numWorkers := runtime.NumCPU()+ if numWorkers > len(files) {+ numWorkers = len(files)+ }++ g := new(errgroup.Group)+ g.SetLimit(numWorkers)+ for i, fe := range files {+ g.Go(func() error {+ results[i] = p.resolveFileConfigures(fe.relPath, fe.cached, envIndex)+ return nil+ })+ }+ _ = g.Wait()++ // Stage 3: Batch write+ p.flushResolvedEdges(results)++ total := 0+ for _, r := range results {+ total += len(r)+ }+ slog.Info("pass.configures.done", "edges", total)+}++// buildEnvIndex creates a mapping from env var key → module QN+// by scanning Module node constants for KEY = VALUE patterns.+func (p *Pipeline) buildEnvIndex() map[string]string {+ modules, err := p.Store.FindNodesByLabel(p.ProjectName, "Module")+ if err != nil {+ return nil+ }++ index := make(map[string]string)+ for _, m := range modules {+ constants, ok := m.Properties["constants"]+ if !ok {+ continue+ }+ constList, ok := constants.([]any)+ if !ok {+ continue+ }+ for _, c := range constList {+ constStr, ok := c.(string)+ if !ok {+ continue+ }+ parts := strings.SplitN(constStr, " = ", 2)+ if len(parts) == 2 {+ key := strings.TrimSpace(parts[0])+ if key != "" && isEnvVarName(key) {+ index[key] = m.QualifiedName+ }+ }+ }+ }+ return index+}++func (p *Pipeline) resolveFileConfigures(relPath string, cached *cachedAST, envIndex map[string]string) []resolvedEdge {+ spec := lang.ForLanguage(cached.Language)+ if spec == nil {+ return nil+ }++ moduleQN := fqn.ModuleQN(p.ProjectName, relPath)+ root := cached.Tree.RootNode()+ callTypes := toSet(spec.CallNodeTypes)++ var edges []resolvedEdge+ seen := make(map[[2]string]bool)++ envFuncs := toSet(spec.EnvAccessFunctions)+ envMembers := toSet(spec.EnvAccessMemberPatterns)++ parser.Walk(root, func(node *tree_sitter.Node) bool {+ kind := node.Kind()++ var envKey string+ switch {+ case callTypes[kind]:+ envKey = extractEnvKeyFromCall(node, cached.Source, envFuncs)+ case kind == "member_expression" || kind == "subscript" || kind == "attribute":+ envKey = extractEnvKeyFromMember(node, cached.Source, envMembers)+ default:+ return true+ }++ if envKey == "" {+ return false+ }++ targetModuleQN, ok := envIndex[envKey]+ if !ok {+ return false+ }++ funcQN := findEnclosingFunction(node, cached.Source, p.ProjectName, relPath, spec)+ if funcQN == "" {+ funcQN = moduleQN+ }++ key := [2]string{funcQN, envKey}+ if !seen[key] {+ seen[key] = true+ edges = append(edges, resolvedEdge{+ CallerQN: funcQN,+ TargetQN: targetModuleQN,+ Type: "CONFIGURES",+ Properties: map[string]any{+ "env_key": envKey,+ "direction": "reads",+ },+ })+ }+ return false+ })++ return edges+}++// extractEnvKeyFromCall extracts env var key from function calls like os.Getenv("KEY").+func extractEnvKeyFromCall(node *tree_sitter.Node, source []byte, envFuncs map[string]bool) string {+ funcNode := node.ChildByFieldName("function")+ if funcNode == nil {+ return ""+ }+ calleeName := parser.NodeText(funcNode, source)+ if !envFuncs[calleeName] {+ return ""+ }++ argsNode := node.ChildByFieldName("arguments")+ if argsNode == nil || argsNode.NamedChildCount() == 0 {+ return ""+ }+ firstArg := argsNode.NamedChild(0)+ if firstArg == nil {+ return ""+ }+ return unquote(parser.NodeText(firstArg, source))+}++// extractEnvKeyFromMember extracts env var key from member access like process.env.KEY.+func extractEnvKeyFromMember(node *tree_sitter.Node, source []byte, envMembers map[string]bool) string {+ text := parser.NodeText(node, source)++ for pattern := range envMembers {+ if key := matchEnvMemberPattern(text, pattern); key != "" {+ return key+ }+ }+ return ""+}++// matchEnvMemberPattern checks if text matches pattern.KEY or pattern["KEY"].+func matchEnvMemberPattern(text, pattern string) string {+ // Dot access: process.env.KEY+ prefix := pattern + "."+ if strings.HasPrefix(text, prefix) {+ key := text[len(prefix):]+ if key != "" && !strings.ContainsAny(key, ".[]()'\"") {+ return key+ }+ }++ // Subscript: os.environ["KEY"]+ bracketPrefix := pattern + "["+ if strings.HasPrefix(text, bracketPrefix) {+ inner := text[len(bracketPrefix):]+ inner = strings.TrimSuffix(inner, "]")+ return unquote(inner)+ }+ return ""+}++// isEnvVarName checks if a string looks like an environment variable name+// (uppercase with underscores).+func isEnvVarName(s string) bool {+ if len(s) < 2 {+ return false+ }+ hasUpper := false+ for _, c := range s {+ switch {+ case c >= 'A' && c <= 'Z':+ hasUpper = true+ case c == '_', c >= '0' && c <= '9':+ // ok+ default:+ return false+ }+ }+ return hasUpper+}++// unquote strips surrounding quotes from a string literal.+func unquote(s string) string {+ s = strings.TrimSpace(s)+ if len(s) >= 2 {+ if (s[0] == '"' && s[len(s)-1] == '"') || (s[0] == '\'' && s[len(s)-1] == '\'') || (s[0] == '`' && s[len(s)-1] == '`') {+ return s[1 : len(s)-1]+ }+ }+ return s+}diff --git a/internal/pipeline/decorates.go b/internal/pipeline/decorates.gonew file mode 100644index 000000000..fb75f5f71--- /dev/null+++ b/internal/pipeline/decorates.go@@ -0,0 +1,86 @@+package pipeline++import (+ "log/slog"+ "strings"++ "github.com/DeusData/codebase-memory-mcp/internal/store"+)++// passDecorates creates DECORATES edges from decorated functions/classes to+// the decorator function node (if it exists in the project).+func (p *Pipeline) passDecorates() {+ slog.Info("pass.decorates")++ count := 0+ for _, label := range []string{"Function", "Method", "Class"} {+ nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)+ if err != nil {+ continue+ }+ for _, n := range nodes {+ count += p.processNodeDecorators(n)+ }+ }++ slog.Info("pass.decorates.done", "edges", count)+}++// processNodeDecorators creates DECORATES edges for a single node's decorators.+func (p *Pipeline) processNodeDecorators(n *store.Node) int {+ decs, ok := n.Properties["decorators"]+ if !ok {+ return 0+ }+ decList, ok := decs.([]any)+ if !ok {+ return 0+ }++ moduleQN := qualifiedNamePrefix(n.QualifiedName)+ importMap := p.importMaps[moduleQN]+ count := 0++ for _, d := range decList {+ decStr, ok := d.(string)+ if !ok || decStr == "" {+ continue+ }++ funcName := decoratorFunctionName(decStr)+ if funcName == "" {+ continue+ }++ targetQN := p.registry.Resolve(funcName, moduleQN, importMap)+ if targetQN == "" {+ continue+ }+ targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetQN)+ if targetNode == nil {+ continue+ }++ _, _ = p.Store.InsertEdge(&store.Edge{+ Project: p.ProjectName,+ SourceID: n.ID,+ TargetID: targetNode.ID,+ Type: "DECORATES",+ Properties: map[string]any{"decorator": decStr},+ })+ count+++ }+ return count+}++// decoratorFunctionName extracts the function name from a decorator string.+// "@app.route('/api')" → "app.route"+// "@pytest.fixture" → "pytest.fixture"+// "@Override" → "Override"+func decoratorFunctionName(dec string) string {+ dec = strings.TrimPrefix(dec, "@")+ if idx := strings.Index(dec, "("); idx > 0 {+ dec = dec[:idx]+ }+ return strings.TrimSpace(dec)+}diff --git a/internal/pipeline/enrichment.go b/internal/pipeline/enrichment.gonew file mode 100644index 000000000..e66a909ac--- /dev/null+++ b/internal/pipeline/enrichment.go@@ -0,0 +1,508 @@+package pipeline++import (+ "strings"++ 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"+ "github.com/DeusData/codebase-memory-mcp/internal/store"+)++// countBranchingNodes counts branching AST nodes inside a function body+// as a proxy for cyclomatic complexity.+func countBranchingNodes(funcNode *tree_sitter.Node, branchingTypes []string) int {+ branchSet := toSet(branchingTypes)+ count := 0+ parser.Walk(funcNode, func(node *tree_sitter.Node) bool {+ if node.Id() == funcNode.Id() {+ return true // skip self, walk children+ }+ if branchSet[node.Kind()] {+ count+++ }+ return true+ })+ return count+}++// extractParamTypes extracts type names from a function's parameter list.+// Returns a slice of type name strings (e.g., ["Config", "string", "int"]).+func extractParamTypes(paramsNode *tree_sitter.Node, source []byte, language lang.Language) []string {+ var types []string+ seen := make(map[string]bool)++ addType := func(name string) {+ if name != "" && !isBuiltinType(name) && !seen[name] {+ seen[name] = true+ types = append(types, name)+ }+ }++ parser.Walk(paramsNode, func(node *tree_sitter.Node) bool {+ if node.Id() == paramsNode.Id() {+ return true+ }+ return extractParamType(node, source, language, addType)+ })+ return types+}++// extractParamType handles a single parameter node per language.+// Returns false to stop recursion when a param node is handled.+func extractParamType(node *tree_sitter.Node, source []byte, language lang.Language, addType func(string)) bool {+ switch language {+ case lang.Go:+ if node.Kind() == "parameter_declaration" {+ if typeNode := node.ChildByFieldName("type"); typeNode != nil {+ addType(cleanTypeName(parser.NodeText(typeNode, source)))+ }+ return false+ }+ case lang.Python:+ if node.Kind() == "typed_parameter" {+ if typeNode := node.ChildByFieldName("type"); typeNode != nil {+ addType(cleanTypeName(parser.NodeText(typeNode, source)))+ }+ return false+ }+ case lang.TypeScript, lang.TSX:+ if node.Kind() == "required_parameter" || node.Kind() == "optional_parameter" {+ if typeAnn := findChildByKind(node, "type_annotation"); typeAnn != nil {+ addType(extractTypeFromAnnotation(typeAnn, source))+ }+ return false+ }+ case lang.Java:+ if node.Kind() == "formal_parameter" || node.Kind() == "spread_parameter" {+ if typeNode := node.ChildByFieldName("type"); typeNode != nil {+ addType(cleanTypeName(parser.NodeText(typeNode, source)))+ }+ return false+ }+ case lang.Rust:+ if node.Kind() == "parameter" {+ if typeNode := node.ChildByFieldName("type"); typeNode != nil {+ addType(cleanTypeName(parser.NodeText(typeNode, source)))+ }+ return false+ }+ }+ return true+}++// extractReturnTypes extracts type names from a return type node.+func extractReturnTypes(retNode *tree_sitter.Node, source []byte, language lang.Language) []string {+ text := parser.NodeText(retNode, source)+ if text == "" {+ return nil+ }++ // For Go, the return type can be a parameter_list (multiple returns)+ if language == lang.Go && retNode.Kind() == "parameter_list" {+ return extractGoMultiReturnTypes(retNode, source)+ }++ // Single return type — extract the type name+ tn := cleanTypeName(text)+ if tn != "" && !isBuiltinType(tn) {+ return []string{tn}+ }+ return nil+}++// extractGoMultiReturnTypes extracts types from Go's (T1, T2, error) return.+func extractGoMultiReturnTypes(retNode *tree_sitter.Node, source []byte) []string {+ var types []string+ seen := make(map[string]bool)+ parser.Walk(retNode, func(node *tree_sitter.Node) bool {+ if node.Id() == retNode.Id() {+ return true+ }+ if node.Kind() == "parameter_declaration" {+ if typeNode := node.ChildByFieldName("type"); typeNode != nil {+ tn := cleanTypeName(parser.NodeText(typeNode, source))+ if tn != "" && !isBuiltinType(tn) && !seen[tn] {+ seen[tn] = true+ types = append(types, tn)+ }+ }+ return false+ }+ return true+ })+ return types+}++// extractBaseClasses extracts superclass names from a class definition.+func extractBaseClasses(node *tree_sitter.Node, source []byte, language lang.Language) []string {+ switch language {+ case lang.Python:+ return extractPythonBases(node, source)+ case lang.Java:+ return extractJavaBases(node, source)+ case lang.TypeScript, lang.TSX, lang.JavaScript:+ return extractTSBases(node, source)+ case lang.CPP:+ return extractCPPBases(node, source)+ case lang.Scala:+ return extractScalaBases(node, source)+ case lang.CSharp:+ return extractCSharpBases(node, source)+ case lang.PHP:+ return extractPHPBases(node, source)+ }+ return nil+}++func extractPythonBases(node *tree_sitter.Node, source []byte) []string {+ superNode := node.ChildByFieldName("superclasses")+ if superNode == nil {+ return nil+ }+ var bases []string+ for i := uint(0); i < superNode.NamedChildCount(); i++ {+ child := superNode.NamedChild(i)+ if child == nil || child.Kind() == "keyword_argument" {+ continue+ }+ if name := parser.NodeText(child, source); name != "" {+ bases = append(bases, name)+ }+ }+ return bases+}++func extractJavaBases(node *tree_sitter.Node, source []byte) []string {+ var bases []string+ if superNode := node.ChildByFieldName("superclass"); superNode != nil {+ if name := cleanTypeName(parser.NodeText(superNode, source)); name != "" {+ bases = append(bases, name)+ }+ }+ if implNode := node.ChildByFieldName("interfaces"); implNode != nil {+ 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)+ }+ }+ }+ return bases+}++func extractTSBases(node *tree_sitter.Node, source []byte) []string {+ var bases []string+ for i := uint(0); i < node.ChildCount(); i++ {+ child := node.Child(i)+ if child == nil || child.Kind() != "class_heritage" {+ continue+ }+ bases = append(bases, extractHeritageClauseNames(child, source)...)+ }+ return bases+}++// extractHeritageClauseNames extracts names from extends/implements clauses.+func extractHeritageClauseNames(heritage *tree_sitter.Node, source []byte) []string {+ var names []string+ for j := uint(0); j < heritage.ChildCount(); j++ {+ hChild := heritage.Child(j)+ if hChild == nil {+ continue+ }+ switch hChild.Kind() {+ case "extends_clause":+ names = append(names, extractExtendsNames(hChild, source)...)+ case "implements_clause":+ names = append(names, extractNamedChildTexts(hChild, source)...)+ }+ }+ return names+}++func extractExtendsNames(clause *tree_sitter.Node, source []byte) []string {+ if valNode := clause.ChildByFieldName("value"); valNode != nil {+ if name := parser.NodeText(valNode, source); name != "" {+ return []string{name}+ }+ return nil+ }+ // Fallback: iterate named children for identifiers+ var names []string+ for k := uint(0); k < clause.NamedChildCount(); k++ {+ ident := clause.NamedChild(k)+ if ident != nil && (ident.Kind() == "identifier" || ident.Kind() == "member_expression") {+ if name := parser.NodeText(ident, source); name != "" {+ names = append(names, name)+ }+ }+ }+ return names+}++func extractNamedChildTexts(node *tree_sitter.Node, source []byte) []string {+ var names []string+ for k := uint(0); k < node.NamedChildCount(); k++ {+ child := node.NamedChild(k)+ if child == nil {+ continue+ }+ if name := parser.NodeText(child, source); name != "" {+ names = append(names, name)+ }+ }+ return names+}++func extractCPPBases(node *tree_sitter.Node, source []byte) []string {+ var bases []string+ for i := uint(0); i < node.ChildCount(); i++ {+ child := node.Child(i)+ if child == nil || child.Kind() != "base_class_clause" {+ continue+ }+ for j := uint(0); j < child.NamedChildCount(); j++ {+ base := child.NamedChild(j)+ if base != nil && base.Kind() == "type_identifier" {+ if name := parser.NodeText(base, source); name != "" {+ bases = append(bases, name)+ }+ }+ }+ }+ return bases+}++func extractScalaBases(node *tree_sitter.Node, source []byte) []string {+ var bases []string+ for i := uint(0); i < node.ChildCount(); i++ {+ child := node.Child(i)+ if child == nil || child.Kind() != "extends_clause" {+ continue+ }+ for j := uint(0); j < child.NamedChildCount(); j++ {+ typeNode := child.NamedChild(j)+ if typeNode != nil && typeNode.Kind() == "type_identifier" {+ if name := parser.NodeText(typeNode, source); name != "" {+ bases = append(bases, name)+ }+ }+ }+ }+ return bases+}++func extractCSharpBases(node *tree_sitter.Node, source []byte) []string {+ baseList := node.ChildByFieldName("bases")+ if baseList == nil {+ return nil+ }+ var bases []string+ for i := uint(0); i < baseList.NamedChildCount(); i++ {+ child := baseList.NamedChild(i)+ if child == nil {+ continue+ }+ if name := cleanTypeName(parser.NodeText(child, source)); name != "" {+ bases = append(bases, name)+ }+ }+ return bases+}++func extractPHPBases(node *tree_sitter.Node, source []byte) []string {+ baseClause := node.ChildByFieldName("base_clause")+ if baseClause == nil {+ return nil+ }+ var bases []string+ for i := uint(0); i < baseClause.NamedChildCount(); i++ {+ child := baseClause.NamedChild(i)+ if child != nil && child.Kind() == "name" {+ if name := parser.NodeText(child, source); name != "" {+ bases = append(bases, name)+ }+ }+ }+ return bases+}++// isAbstractClass returns true if the class node has abstract modifiers.+func isAbstractClass(node *tree_sitter.Node, language lang.Language) bool {+ switch language {+ case lang.TypeScript, lang.TSX:+ return node.Kind() == "abstract_class_declaration"+ case lang.Java, lang.CSharp:+ // Check modifiers for "abstract" keyword+ mods := node.ChildByFieldName("modifiers")+ if mods == nil {+ return false+ }+ for i := uint(0); i < mods.ChildCount(); i++ {+ child := mods.Child(i)+ if child != nil && child.Kind() == "abstract" {+ return true+ }+ }+ return false+ }+ return false+}++// extractAllDecorators extracts decorators/annotations from a node across languages.+func extractAllDecorators(node *tree_sitter.Node, source []byte, language lang.Language, _ *lang.LanguageSpec) []string {+ switch language {+ case lang.Python:+ return extractDecorators(node, source)+ case lang.Java:+ return extractJavaAnnotations(node, source)+ case lang.TypeScript, lang.TSX:+ return extractTSDecorators(node, source)+ case lang.CSharp:+ return extractCSharpAttributes(node, source)+ }+ return nil+}++func extractJavaAnnotations(node *tree_sitter.Node, source []byte) []string {+ mods := node.ChildByFieldName("modifiers")+ if mods == nil {+ return nil+ }+ var decorators []string+ for i := uint(0); i < mods.ChildCount(); i++ {+ child := mods.Child(i)+ if child == nil {+ continue+ }+ if child.Kind() == "marker_annotation" || child.Kind() == "annotation" {+ decorators = append(decorators, parser.NodeText(child, source))+ }+ }+ return decorators+}++func extractTSDecorators(node *tree_sitter.Node, source []byte) []string {+ var decorators []string+ for i := uint(0); i < node.ChildCount(); i++ {+ child := node.Child(i)+ if child != nil && child.Kind() == "decorator" {+ decorators = append(decorators, parser.NodeText(child, source))+ }+ }+ return decorators+}++func extractCSharpAttributes(node *tree_sitter.Node, source []byte) []string {+ var decorators []string+ for i := uint(0); i < node.ChildCount(); i++ {+ child := node.Child(i)+ if child == nil || child.Kind() != "attribute_list" {+ continue+ }+ for j := uint(0); j < child.NamedChildCount(); j++ {+ attr := child.NamedChild(j)+ if attr != nil && attr.Kind() == "attribute" {+ decorators = append(decorators, parser.NodeText(attr, source))+ }+ }+ }+ return decorators+}++// Helper functions++func extractTypeFromAnnotation(typeAnn *tree_sitter.Node, source []byte) string {+ // type_annotation → first named child is the type+ for i := uint(0); i < typeAnn.NamedChildCount(); i++ {+ child := typeAnn.NamedChild(i)+ if child != nil {+ return cleanTypeName(parser.NodeText(child, source))+ }+ }+ return ""+}++// cleanTypeName strips pointers, references, generics to get the base type name.+func cleanTypeName(s string) string {+ s = strings.TrimSpace(s)+ s = strings.TrimPrefix(s, "*")+ s = strings.TrimPrefix(s, "&")+ s = strings.TrimPrefix(s, "[]")+ s = strings.TrimPrefix(s, "...")+ // Strip generic params: Map<String, Int> → Map+ if idx := strings.Index(s, "<"); idx > 0 {+ s = s[:idx]+ }+ // Strip array brackets: int[] → int+ if idx := strings.Index(s, "["); idx > 0 {+ s = s[:idx]+ }+ return strings.TrimSpace(s)+}++// isBuiltinType returns true for primitive/builtin type names that aren't+// useful to track as USES_TYPE targets.+func isBuiltinType(name string) bool {+ switch name {+ case "int", "int8", "int16", "int32", "int64",+ "uint", "uint8", "uint16", "uint32", "uint64",+ "float", "float32", "float64", "double",+ "string", "str", "bool", "boolean", "byte", "rune",+ "void", "None", "any", "interface", "object", "Object",+ "error", "uintptr", "complex64", "complex128",+ "number", "bigint", "symbol", "undefined", "null",+ "char", "short", "long", "i8", "i16", "i32", "i64",+ "u8", "u16", "u32", "u64", "f32", "f64", "usize", "isize",+ "self", "Self", "cls", "type":+ return true+ }+ return false+}++// buildSymbolSummary creates a compact symbol list for File node enrichment.+// Format: "kind:name" where kind is func/method/class/interface/type/var/const/macro/field.+func buildSymbolSummary(nodes []*store.Node, moduleQN string) []string {+ symbols := make([]string, 0, len(nodes))+ for _, n := range nodes {+ if n.QualifiedName == moduleQN {+ continue+ }+ prefix := labelToSymbolPrefix(n.Label)+ if prefix == "" {+ continue+ }+ symbols = append(symbols, prefix+":"+n.Name)+ }+ return symbols+}++func labelToSymbolPrefix(label string) string {+ switch label {+ case "Function":+ return "func"+ case "Method":+ return "method"+ case "Class":+ return "class"+ case "Interface":+ return "interface"+ case "Type":+ return "type"+ case "Enum":+ return "enum"+ case "Variable":+ return "var"+ case "Macro":+ return "macro"+ case "Field":+ return "field"+ default:+ return ""+ }+}diff --git a/internal/pipeline/inherits.go b/internal/pipeline/inherits.gonew file mode 100644index 000000000..396eb782d--- /dev/null+++ b/internal/pipeline/inherits.go@@ -0,0 +1,73 @@+package pipeline++import (+ "log/slog"++ "github.com/DeusData/codebase-memory-mcp/internal/store"+)++// passInherits creates INHERITS edges from Class nodes to their base classes.+// Reads base_classes property (set during extractClassDef) and resolves via registry.+func (p *Pipeline) passInherits() {+ slog.Info("pass.inherits")++ count := 0+ for _, label := range []string{"Class", "Type", "Interface", "Enum"} {+ nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)+ if err != nil {+ continue+ }+ for _, n := range nodes {+ bases, ok := n.Properties["base_classes"]+ if !ok {+ continue+ }+ baseList, ok := bases.([]any)+ if !ok {+ continue+ }++ moduleQN := qualifiedNamePrefix(n.QualifiedName)+ importMap := p.importMaps[moduleQN]++ for _, b := range baseList {+ baseName, ok := b.(string)+ if !ok || baseName == "" {+ continue+ }++ // Resolve base class to a registered Class/Type/Interface+ targetQN := resolveAsClass(baseName, p.registry, moduleQN, importMap)+ if targetQN == "" {+ continue+ }++ targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, targetQN)+ if targetNode == nil {+ continue+ }++ _, _ = p.Store.InsertEdge(&store.Edge{+ Project: p.ProjectName,+ SourceID: n.ID,+ TargetID: targetNode.ID,+ Type: "INHERITS",+ })+ count+++ }+ }+ }++ slog.Info("pass.inherits.done", "edges", count)+}++// qualifiedNamePrefix returns the module QN portion of a fully qualified name.+// e.g., "project.path.module.ClassName" → "project.path.module"+func qualifiedNamePrefix(qn string) string {+ for i := len(qn) - 1; i >= 0; i-- {+ if qn[i] == '.' {+ return qn[:i]+ }+ }+ return qn+}diff --git a/internal/pipeline/pipeline.go b/internal/pipeline/pipeline.goindex 38d19342e..9d6b6bc93 100644--- a/internal/pipeline/pipeline.go+++ b/internal/pipeline/pipeline.go@@ -135,13 +135,21 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {slog.Info("pass.timing", "pass", "structure", "elapsed", time.Since(t))t = time.Now()- p.passDefinitions(files)+ p.passDefinitions(files) // includes Variable extraction + enrichmentslog.Info("pass.timing", "pass", "definitions", "elapsed", time.Since(t))t = time.Now()- p.buildRegistry()+ p.buildRegistry() // includes Variable labelslog.Info("pass.timing", "pass", "registry", "elapsed", time.Since(t))+ t = time.Now()+ p.passInherits() // INHERITS edges from base_classes+ slog.Info("pass.timing", "pass", "inherits", "elapsed", time.Since(t))++ t = time.Now()+ p.passDecorates() // DECORATES edges from decorators+ slog.Info("pass.timing", "pass", "decorates", "elapsed", time.Since(t))+t = time.Now()p.passImports()slog.Info("pass.timing", "pass", "imports", "elapsed", time.Since(t))@@ -154,11 +162,35 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {p.passUsages()slog.Info("pass.timing", "pass", "usages", "elapsed", time.Since(t))+ 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.cleanupASTCache()+ t = time.Now()+ p.passTests() // TESTS/TESTS_FILE edges (DB-only)+ slog.Info("pass.timing", "pass", "tests", "elapsed", time.Since(t))++ t = time.Now()+ p.passCommunities() // Community nodes + MEMBER_OF edges (DB-only)+ slog.Info("pass.timing", "pass", "communities", "elapsed", time.Since(t))+t = time.Now()if err := p.passHTTPLinks(); err != nil {- slog.Warn("pass4.httplink.err", "err", err)+ slog.Warn("pass.httplink.err", "err", err)}slog.Info("pass.timing", "pass", "httplinks", "elapsed", time.Since(t))@@ -174,9 +206,29 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {p.updateFileHashes(files)slog.Info("pass.timing", "pass", "filehashes", "elapsed", time.Since(t))+ // Observability: per-edge-type counts+ p.logEdgeCounts()+return nil}+// logEdgeCounts logs the count of each edge type for observability.+func (p *Pipeline) logEdgeCounts() {+ edgeTypes := []string{+ "CALLS", "USAGE", "IMPORTS", "DEFINES", "DEFINES_METHOD",+ "TESTS", "TESTS_FILE", "INHERITS", "DECORATES", "USES_TYPE",+ "THROWS", "RAISES", "READS", "WRITES", "CONFIGURES", "MEMBER_OF",+ "HTTP_CALLS", "HANDLES", "ASYNC_CALLS", "IMPLEMENTS", "OVERRIDE",+ "FILE_CHANGES_WITH", "CONTAINS_FILE", "CONTAINS_FOLDER", "CONTAINS_PACKAGE",+ }+ for _, edgeType := range edgeTypes {+ count, err := p.Store.CountEdgesByType(p.ProjectName, edgeType)+ if err == nil && count > 0 {+ slog.Info("pipeline.edges", "type", edgeType, "count", count)+ }+ }+}+// runIncrementalPasses re-indexes only changed files + their dependents.func (p *Pipeline) runIncrementalPasses(allFiles []discover.FileInfo,@@ -215,26 +267,58 @@ func (p *Pipeline) runIncrementalPasses(filesToResolve := mergeFiles(changed, dependents)slog.Info("incremental.resolve", "changed", len(changed), "dependents", len(dependents))- // Delete CALLS and USAGE edges for files being re-resolved+ // Delete edges for files being re-resolved (all AST-derived edge types)for _, f := range filesToResolve {_ = p.Store.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "CALLS")_ = p.Store.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "USAGE")+ _ = p.Store.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "USES_TYPE")+ _ = p.Store.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "THROWS")+ _ = p.Store.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "RAISES")+ _ = p.Store.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "READS")+ _ = p.Store.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "WRITES")+ _ = p.Store.DeleteEdgesBySourceFile(p.ProjectName, f.RelPath, "CONFIGURES")}- // Pass 3: Re-resolve calls + usages for changed + dependent files+ // Re-resolve calls + usages for changed + dependent filesp.passCallsForFiles(filesToResolve)p.passUsagesForFiles(filesToResolve)+ // AST-dependent passes (run on cached files before cleanup)+ p.passUsesType()+ p.passThrows()+ p.passReadsWrites()+ p.passConfigures()+p.cleanupASTCache()+ // DB-derived edge types: delete all and re-run (cheap)+ _ = p.Store.DeleteEdgesByType(p.ProjectName, "TESTS")+ _ = p.Store.DeleteEdgesByType(p.ProjectName, "TESTS_FILE")+ p.passTests()++ _ = p.Store.DeleteEdgesByType(p.ProjectName, "INHERITS")+ p.passInherits()++ _ = p.Store.DeleteEdgesByType(p.ProjectName, "DECORATES")+ p.passDecorates()++ // Community detection: delete old communities and MEMBER_OF, re-run+ _ = p.Store.DeleteEdgesByType(p.ProjectName, "MEMBER_OF")+ _ = p.Store.DeleteNodesByLabel(p.ProjectName, "Community")+ p.passCommunities()+// HTTP linking and implements always run fully (they clean up first)if err := p.passHTTPLinks(); err != nil {- slog.Warn("pass4.httplink.err", "err", err)+ slog.Warn("pass.httplink.err", "err", err)}p.passImplements()p.passGitHistory()p.updateFileHashes(allFiles)++ // Observability+ p.logEdgeCounts()+return nil}@@ -452,7 +536,32 @@ func mergeFiles(a, b []discover.FileInfo) []discover.FileInfo {func (p *Pipeline) passStructure(files []discover.FileInfo) error {slog.Info("pass1.structure")- // Collect all package indicators+ dirSet, dirIsPackage := p.classifyDirectories(files)++ nodes := make([]*store.Node, 0, len(files)*2)+ edges := make([]pendingEdge, 0, len(files)*2)++ projectQN := p.ProjectName+ nodes = append(nodes, &store.Node{+ Project: p.ProjectName,+ Label: "Project",+ Name: p.ProjectName,+ QualifiedName: projectQN,+ })++ dirNodes, dirEdges := p.buildDirNodesEdges(dirSet, dirIsPackage, projectQN)+ nodes = append(nodes, dirNodes...)+ edges = append(edges, dirEdges...)++ fileNodes, fileEdges := p.buildFileNodesEdges(files)+ nodes = append(nodes, fileNodes...)+ edges = append(edges, fileEdges...)++ return p.batchWriteStructure(nodes, edges)+}++// classifyDirectories collects all directories and determines which are packages.+func (p *Pipeline) classifyDirectories(files []discover.FileInfo) (allDirs, packageDirs map[string]bool) {packageIndicators := make(map[string]bool)for _, l := range lang.AllLanguages() {spec := lang.ForLanguage(l)@@ -463,105 +572,92 @@ func (p *Pipeline) passStructure(files []discover.FileInfo) error {}}- // Phase A: Collect all unique directories from file paths- dirSet := make(map[string]bool)+ allDirs = make(map[string]bool)for _, f := range files {dir := filepath.Dir(f.RelPath)- for dir != "." && dir != "" && !dirSet[dir] {- dirSet[dir] = true+ for dir != "." && dir != "" && !allDirs[dir] {+ allDirs[dir] = truedir = filepath.Dir(dir)}}- // Phase B: Check package indicators via os.Stat (batched, not interleaved with SQL)- dirIsPackage := make(map[string]bool, len(dirSet))- for dir := range dirSet {+ packageDirs = make(map[string]bool, len(allDirs))+ for dir := range allDirs {absDir := filepath.Join(p.RepoPath, dir)for indicator := range packageIndicators {if _, err := os.Stat(filepath.Join(absDir, indicator)); err == nil {- dirIsPackage[dir] = true+ packageDirs[dir] = truebreak}}}+ return+}- // Phase C: Build all nodes and pending edges in memory- var nodes []*store.Node- var edges []pendingEdge-- // Project node- projectQN := p.ProjectName- nodes = append(nodes, &store.Node{- Project: p.ProjectName,- Label: "Project",- Name: p.ProjectName,- QualifiedName: projectQN,- })+func (p *Pipeline) buildDirNodesEdges(dirSet, dirIsPackage map[string]bool, projectQN string) ([]*store.Node, []pendingEdge) {+ nodes := make([]*store.Node, 0, len(dirSet))+ edges := make([]pendingEdge, 0, len(dirSet))- // Directory/Package nodes + containment edgesfor dir := range dirSet {- dirName := filepath.Base(dir)label := "Folder"+ edgeType := "CONTAINS_FOLDER"if dirIsPackage[dir] {label = "Package"+ edgeType = "CONTAINS_PACKAGE"}qn := fqn.FolderQN(p.ProjectName, dir)nodes = append(nodes, &store.Node{Project: p.ProjectName,Label: label,- Name: dirName,+ Name: filepath.Base(dir),QualifiedName: qn,FilePath: dir,})- // Containment edge from parentparent := filepath.Dir(dir)- var parentQN string- if parent == "." || parent == "" {- parentQN = projectQN- } else {+ parentQN := projectQN+ if parent != "." && parent != "" {parentQN = fqn.FolderQN(p.ProjectName, parent)}-- edgeType := "CONTAINS_FOLDER"- if dirIsPackage[dir] {- edgeType = "CONTAINS_PACKAGE"- }- edges = append(edges, pendingEdge{- SourceQN: parentQN,- TargetQN: qn,- Type: edgeType,- })+ edges = append(edges, pendingEdge{SourceQN: parentQN, TargetQN: qn, Type: edgeType})}+ return nodes, edges+}++func (p *Pipeline) buildFileNodesEdges(files []discover.FileInfo) ([]*store.Node, []pendingEdge) {+ nodes := make([]*store.Node, 0, len(files))+ edges := make([]pendingEdge, 0, len(files))- // File nodes + containment edgesfor _, f := range files {fileQN := fqn.Compute(p.ProjectName, f.RelPath, "") + ".__file__"+ fileProps := map[string]any{+ "extension": filepath.Ext(f.RelPath),+ "is_test": isTestFile(f.RelPath, f.Language),+ }+ if f.Language != "" {+ fileProps["language"] = string(f.Language)+ }nodes = append(nodes, &store.Node{Project: p.ProjectName,Label: "File",Name: filepath.Base(f.RelPath),QualifiedName: fileQN,FilePath: f.RelPath,- Properties: map[string]any{"extension": filepath.Ext(f.RelPath)},+ Properties: fileProps,})- dir := filepath.Dir(f.RelPath)- parentQN := p.dirQN(dir)- edges = append(edges, pendingEdge{- SourceQN: parentQN,- TargetQN: fileQN,- Type: "CONTAINS_FILE",- })+ parentQN := p.dirQN(filepath.Dir(f.RelPath))+ edges = append(edges, pendingEdge{SourceQN: parentQN, TargetQN: fileQN, Type: "CONTAINS_FILE"})}+ return nodes, edges+}- // Phase D: Batch write all nodes+func (p *Pipeline) batchWriteStructure(nodes []*store.Node, edges []pendingEdge) error {idMap, err := p.Store.UpsertNodeBatch(nodes)if err != nil {return fmt.Errorf("pass1 batch upsert: %w", err)}- // Resolve pending edges to real edges using ID maprealEdges := make([]*store.Edge, 0, len(edges))for _, pe := range edges {srcID, srcOK := idMap[pe.SourceQN]@@ -580,7 +676,6 @@ func (p *Pipeline) passStructure(files []discover.FileInfo) error {if err := p.Store.InsertEdgeBatch(realEdges); err != nil {return fmt.Errorf("pass1 batch edges: %w", err)}-return nil}@@ -754,7 +849,7 @@ func parseFileAST(projectName string, f discover.FileInfo) *parseResult {kind := node.Kind()if funcTypes[kind] {- extractFunctionDef(node, source, f, projectName, moduleQN, result)+ extractFunctionDef(node, source, f, projectName, moduleQN, spec, result)return false}@@ -764,7 +859,7 @@ func parseFileAST(projectName string, f discover.FileInfo) *parseResult {}// Macro definitions (C/C++ only)- if isCPP && (kind == "preproc_def" || kind == "preproc_function_def") {+ if isCPP && kind == "preproc_function_def" {extractMacroDef(node, source, f, projectName, moduleQN, macroNames, result)return false}@@ -779,11 +874,23 @@ func parseFileAST(projectName string, f discover.FileInfo) *parseResult {return true})- // Store macro names in result for later call resolution (pass 3)+ enrichModuleNode(moduleNode, macroNames, constants, root, source, f, projectName, moduleQN, spec, result)++ return result+}++// enrichModuleNode populates module node properties: macros, constants, exports, variables, symbols.+func enrichModuleNode(+ moduleNode *store.Node, macroNames map[string]bool, constants []string,+ root *tree_sitter.Node, source []byte, f discover.FileInfo,+ projectName, moduleQN string, spec *lang.LanguageSpec, result *parseResult,+) {+ if moduleNode.Properties == nil {+ moduleNode.Properties = make(map[string]any)+ }++ // Store macro names for call resolutionif len(macroNames) > 0 {- if moduleNode.Properties == nil {- moduleNode.Properties = make(map[string]any)- }macroList := make([]string, 0, len(macroNames))for name := range macroNames {macroList = append(macroList, name)@@ -791,9 +898,46 @@ func parseFileAST(projectName string, f discover.FileInfo) *parseResult {moduleNode.Properties["macros"] = macroList}- // Resolve interpolated/concatenated strings- resolved := resolveModuleStrings(root, source, f.Language)+ // Merge interpolated/concatenated string constants+ constants = mergeResolvedConstants(constants, root, source, f.Language)+ if len(constants) > 0 {+ moduleNode.Properties["constants"] = constants+ }++ moduleNode.Properties["is_test"] = isTestFile(f.RelPath, f.Language)++ // exports: collect exported symbol names+ var exports []string+ for _, n := range result.Nodes {+ if n.QualifiedName == moduleQN {+ continue+ }+ if exp, ok := n.Properties["is_exported"].(bool); ok && exp {+ exports = append(exports, n.Name)+ }+ }+ if len(exports) > 0 {+ moduleNode.Properties["exports"] = exports+ }+ // Extract module-level variables+ extractVariables(root, source, f, projectName, moduleQN, spec, result)++ if globalVars := extractGlobalVarNames(root, source, f, spec); len(globalVars) > 0 {+ moduleNode.Properties["global_vars"] = globalVars+ }++ if symbols := buildSymbolSummary(result.Nodes, moduleQN); len(symbols) > 0 {+ moduleNode.Properties["symbols"] = symbols+ }++ result.ImportMap = parseImports(root, source, f.Language, projectName, f.RelPath)+ moduleNode.Properties["imports_count"] = len(result.ImportMap)+}++// mergeResolvedConstants adds interpolated string constants to the existing list.+func mergeResolvedConstants(constants []string, root *tree_sitter.Node, source []byte, language lang.Language) []string {+ resolved := resolveModuleStrings(root, source, language)seen := make(map[string]bool, len(constants))for _, c := range constants {seen[c] = true@@ -808,22 +952,13 @@ func parseFileAST(projectName string, f discover.FileInfo) *parseResult {constants = append(constants, entry)}}-- // Update module node with constants (replace the initial module node)- if len(constants) > 0 {- moduleNode.Properties = map[string]any{"constants": constants}- }-- // Parse imports- result.ImportMap = parseImports(root, source, f.Language, projectName, f.RelPath)-- return result+ return constants}// extractFunctionDef extracts a function/method node and DEFINES edge as data (no DB).func extractFunctionDef(node *tree_sitter.Node, source []byte, f discover.FileInfo,- projectName, moduleQN string, result *parseResult,+ projectName, moduleQN string, spec *lang.LanguageSpec, result *parseResult,) {nameNode := node.ChildByFieldName("name")if nameNode == nil {@@ -842,12 +977,19 @@ func extractFunctionDef(paramsNode := node.ChildByFieldName("parameters")if paramsNode != nil {props["signature"] = parser.NodeText(paramsNode, source)+ if paramTypes := extractParamTypes(paramsNode, source, f.Language); len(paramTypes) > 0 {+ props["param_types"] = paramTypes+ }}for _, field := range []string{"result", "return_type", "type"} {rtNode := node.ChildByFieldName(field)if rtNode != nil {- props["return_type"] = parser.NodeText(rtNode, source)+ rtText := parser.NodeText(rtNode, source)+ props["return_type"] = rtText+ if returnTypes := extractReturnTypes(rtNode, source, f.Language); len(returnTypes) > 0 {+ props["return_types"] = returnTypes+ }break}}@@ -860,13 +1002,12 @@ func extractFunctionDef(props["is_exported"] = isExported(name, f.Language)- if f.Language == lang.Python {- decorators := extractDecorators(node, source)- if len(decorators) > 0 {- props["decorators"] = decorators- if hasFrameworkDecorator(decorators) {- props["is_entry_point"] = true- }+ // Decorator extraction (Python, Java, TS/JS)+ decorators := extractAllDecorators(node, source, f.Language, spec)+ if len(decorators) > 0 {+ props["decorators"] = decorators+ if hasFrameworkDecorator(decorators) {+ props["is_entry_point"] = true}}@@ -877,6 +1018,20 @@ func extractFunctionDef(startLine := safeRowToLine(node.StartPosition().Row)endLine := safeRowToLine(node.EndPosition().Row)+ // Enrichment: function body line count+ lines := endLine - startLine + 1+ if lines > 0 {+ props["lines"] = lines+ }++ // Enrichment: complexity (branching node count)+ if spec != nil && len(spec.BranchingNodeTypes) > 0 {+ complexity := countBranchingNodes(node, spec.BranchingNodeTypes)+ if complexity > 0 {+ props["complexity"] = complexity+ }+ }+result.Nodes = append(result.Nodes, &store.Node{Project: projectName,Label: label,@@ -930,6 +1085,26 @@ func extractClassDef(startLine := safeRowToLine(node.StartPosition().Row)endLine := safeRowToLine(node.EndPosition().Row)+ classProps := map[string]any{"is_exported": isExported(name, f.Language)}++ // Enrichment: base classes (for INHERITS edges in Phase 2)+ if baseClasses := extractBaseClasses(node, source, f.Language); len(baseClasses) > 0 {+ classProps["base_classes"] = baseClasses+ }++ // Enrichment: is_abstract+ if isAbstractClass(node, f.Language) {+ classProps["is_abstract"] = true+ }++ // Enrichment: decorators for class-level (Java annotations, TS decorators)+ if spec != nil {+ decorators := extractAllDecorators(node, source, f.Language, spec)+ if len(decorators) > 0 {+ classProps["decorators"] = decorators+ }+ }+result.Nodes = append(result.Nodes, &store.Node{Project: projectName,Label: label,@@ -938,7 +1113,7 @@ func extractClassDef(FilePath: f.RelPath,StartLine: startLine,EndLine: endLine,- Properties: map[string]any{"is_exported": isExported(name, f.Language)},+ Properties: classProps,})result.PendingEdges = append(result.PendingEdges, pendingEdge{@@ -952,6 +1127,25 @@ func extractClassDef(// Extract fields inside the class/structextractClassFieldDefs(node, source, f, projectName, classQN, spec, result)++ // Enrichment: method_count and field_count (count from extracted nodes)+ var methodCount, fieldCount int+ for _, pe := range result.PendingEdges {+ if pe.SourceQN == classQN {+ switch pe.Type {+ case "DEFINES_METHOD":+ methodCount+++ case "DEFINES":+ fieldCount+++ }+ }+ }+ if methodCount > 0 {+ classProps["method_count"] = methodCount+ }+ if fieldCount > 0 {+ classProps["field_count"] = fieldCount+ }}// extractClassMethodDefs walks a class AST node and extracts Method nodes (no DB).@@ -1133,7 +1327,7 @@ func extractIdentifierFromDeclarator(node *tree_sitter.Node, source []byte) stri}// extractFieldType extracts the type annotation from a field declaration.-func extractFieldType(node *tree_sitter.Node, source []byte, l lang.Language) string {+func extractFieldType(node *tree_sitter.Node, source []byte, _ lang.Language) string {// Try "type" field (Go, Rust, Java)if typeNode := node.ChildByFieldName("type"); typeNode != nil {return parser.NodeText(typeNode, source)@@ -1194,7 +1388,7 @@ func extractMacroDef(// buildRegistry populates the FunctionRegistry from all Function, Method,// and Class nodes in the store.func (p *Pipeline) buildRegistry() {- labels := []string{"Function", "Method", "Class", "Type", "Interface", "Enum", "Macro"}+ labels := []string{"Function", "Method", "Class", "Type", "Interface", "Enum", "Macro", "Variable"}for _, label := range labels {nodes, err := p.Store.FindNodesByLabel(p.ProjectName, label)if err != nil {@@ -1495,13 +1689,15 @@ func findEnclosingFunction(node *tree_sitter.Node, source []byte, project, relPa}func isConstantNode(node *tree_sitter.Node, language lang.Language) bool {- // Only look at top-level nodesparent := node.Parent()if parent == nil {return false}+ return isConstantForLanguage(node.Kind(), parent, language)+}++func isConstantForLanguage(kind string, parent *tree_sitter.Node, language lang.Language) bool {parentKind := parent.Kind()- kind := node.Kind()switch language {case lang.Go:@@ -1509,12 +1705,9 @@ func isConstantNode(node *tree_sitter.Node, language lang.Language) bool {case lang.Python:return parentKind == "module" && kind == "expression_statement"case lang.JavaScript, lang.TypeScript, lang.TSX:- return parentKind == "program" && kind == "lexical_declaration"+ return isJSConstantNode(kind, parentKind, parent)case lang.Rust:return parentKind == "source_file" && (kind == "const_item" || kind == "let_declaration")- case lang.Java:- // Java constants are in class bodies — handled differently (resolve.go walks class body)- return falsecase lang.PHP:return parentKind == "program" && kind == "expression_statement"case lang.Scala:@@ -1528,6 +1721,21 @@ func isConstantNode(node *tree_sitter.Node, language lang.Language) bool {}}+func isJSConstantNode(kind, parentKind string, parent *tree_sitter.Node) bool {+ if kind != "lexical_declaration" {+ return false+ }+ if parentKind == "program" {+ return true+ }+ // export const X = ... → program → export_statement → lexical_declaration+ if parentKind == "export_statement" {+ gp := parent.Parent()+ return gp != nil && gp.Kind() == "program"+ }+ return false+}+func extractConstant(node *tree_sitter.Node, source []byte) string {text := parser.NodeText(node, source)// Take just the first line (name = value)diff --git a/internal/pipeline/readwrite.go b/internal/pipeline/readwrite.gonew file mode 100644index 000000000..809b59009--- /dev/null+++ b/internal/pipeline/readwrite.go@@ -0,0 +1,383 @@+package pipeline++import (+ "log/slog"+ "runtime"+ "strings"++ tree_sitter "github.com/tree-sitter/go-tree-sitter"+ "golang.org/x/sync/errgroup"++ "github.com/DeusData/codebase-memory-mcp/internal/discover"+ "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"+)++// passVariables extracts module-level variable declarations and creates Variable+// nodes + DEFINES edges during passDefinitions.+func extractVariables(+ root *tree_sitter.Node, source []byte, f discover.FileInfo,+ projectName, moduleQN string, spec *lang.LanguageSpec, result *parseResult,+) {+ if spec == nil || len(spec.VariableNodeTypes) == 0 {+ return+ }+ varTypes := toSet(spec.VariableNodeTypes)++ parser.Walk(root, func(node *tree_sitter.Node) bool {+ if !isModuleLevelNode(node, f.Language) || !varTypes[node.Kind()] {+ return true+ }++ names := extractVarNames(node, source, f.Language)+ for _, name := range names {+ if name == "" || name == "_" {+ continue+ }+ varQN := fqn.Compute(projectName, f.RelPath, name)+ startLine := safeRowToLine(node.StartPosition().Row)+ endLine := safeRowToLine(node.EndPosition().Row)++ result.Nodes = append(result.Nodes, &store.Node{+ Project: projectName,+ Label: "Variable",+ Name: name,+ QualifiedName: varQN,+ FilePath: f.RelPath,+ StartLine: startLine,+ EndLine: endLine,+ Properties: map[string]any{"is_exported": isExported(name, f.Language)},+ })+ result.PendingEdges = append(result.PendingEdges, pendingEdge{+ SourceQN: moduleQN,+ TargetQN: varQN,+ Type: "DEFINES",+ })+ }+ return false+ })+}++// isModuleLevelNode checks if a node is at the module/file top level.+func isModuleLevelNode(node *tree_sitter.Node, language lang.Language) bool {+ parent := node.Parent()+ if parent == nil {+ return false+ }+ parentKind := parent.Kind()++ switch language {+ case lang.Go, lang.Rust:+ return parentKind == "source_file"+ case lang.Python:+ if parentKind == "module" {+ return true+ }+ // Python wraps assignments: module → expression_statement → assignment+ if parentKind == "expression_statement" {+ if gp := parent.Parent(); gp != nil {+ return gp.Kind() == "module"+ }+ }+ case lang.JavaScript, lang.TypeScript, lang.TSX:+ if parentKind == "program" {+ return true+ }+ // JS/TS wraps exports: program → export_statement → declaration+ if parentKind == "export_statement" {+ if gp := parent.Parent(); gp != nil {+ return gp.Kind() == "program"+ }+ }+ }+ return false+}++// extractVarNames extracts variable names from a declaration node.+func extractVarNames(node *tree_sitter.Node, source []byte, language lang.Language) []string {+ switch language {+ case lang.Go:+ return extractGoVarNames(node, source)+ case lang.Python:+ return extractPythonVarNames(node, source)+ case lang.JavaScript, lang.TypeScript, lang.TSX:+ return extractJSVarNames(node, source)+ case lang.Rust:+ return extractRustVarNames(node, source)+ }+ return nil+}++func extractGoVarNames(node *tree_sitter.Node, source []byte) []string {+ var names []string+ parser.Walk(node, func(child *tree_sitter.Node) bool {+ if child.Kind() == "var_spec" || child.Kind() == "const_spec" {+ if nameNode := child.ChildByFieldName("name"); nameNode != nil {+ names = append(names, parser.NodeText(nameNode, source))+ }+ return false+ }+ return true+ })+ return names+}++func extractPythonVarNames(node *tree_sitter.Node, source []byte) []string {+ leftNode := node.ChildByFieldName("left")+ if leftNode == nil || leftNode.Kind() != "identifier" {+ return nil+ }+ name := parser.NodeText(leftNode, source)+ if strings.HasPrefix(name, "__") {+ return nil+ }+ return []string{name}+}++func extractJSVarNames(node *tree_sitter.Node, source []byte) []string {+ var names []string+ parser.Walk(node, func(child *tree_sitter.Node) bool {+ if child.Kind() == "variable_declarator" {+ if nameNode := child.ChildByFieldName("name"); nameNode != nil {+ if nameNode.Kind() == "identifier" {+ names = append(names, parser.NodeText(nameNode, source))+ }+ }+ return false+ }+ return true+ })+ return names+}++func extractRustVarNames(node *tree_sitter.Node, source []byte) []string {+ if nameNode := node.ChildByFieldName("name"); nameNode != nil {+ return []string{parser.NodeText(nameNode, source)}+ }+ return nil+}++// passReadsWrites creates READS and WRITES edges from functions to Variable nodes.+func (p *Pipeline) passReadsWrites() {+ slog.Info("pass.readwrite")++ type fileEntry struct {+ relPath string+ cached *cachedAST+ }+ var files []fileEntry+ for relPath, cached := range p.astCache {+ spec := lang.ForLanguage(cached.Language)+ if spec != nil && len(spec.AssignmentNodeTypes) > 0 {+ files = append(files, fileEntry{relPath, cached})+ }+ }++ if len(files) == 0 {+ return+ }++ results := make([][]resolvedEdge, len(files))+ numWorkers := runtime.NumCPU()+ if numWorkers > len(files) {+ numWorkers = len(files)+ }++ g := new(errgroup.Group)+ g.SetLimit(numWorkers)+ for i, fe := range files {+ g.Go(func() error {+ results[i] = p.resolveFileReadsWrites(fe.relPath, fe.cached)+ return nil+ })+ }+ _ = g.Wait()++ p.flushResolvedEdges(results)++ total := 0+ for _, r := range results {+ total += len(r)+ }+ slog.Info("pass.readwrite.done", "edges", total)+}++func (p *Pipeline) resolveFileReadsWrites(relPath string, cached *cachedAST) []resolvedEdge {+ spec := lang.ForLanguage(cached.Language)+ if spec == nil {+ return nil+ }++ moduleQN := fqn.ModuleQN(p.ProjectName, relPath)+ importMap := p.importMaps[moduleQN]+ assignTypes := toSet(spec.AssignmentNodeTypes)+ root := cached.Tree.RootNode()++ var edges []resolvedEdge+ seen := make(map[[3]string]bool)++ parser.Walk(root, func(node *tree_sitter.Node) bool {+ if node.Kind() != "identifier" {+ return true+ }++ refName := parser.NodeText(node, cached.Source)+ if refName == "" || isKeywordOrBuiltin(refName, cached.Language) {+ return false+ }++ targetQN := p.resolveVariableStrict(refName, moduleQN, importMap)+ if targetQN == "" {+ return false+ }++ callerQN := findEnclosingFunction(node, cached.Source, p.ProjectName, relPath, spec)+ if callerQN == "" {+ callerQN = moduleQN+ }+ if callerQN == targetQN {+ return false+ }++ edgeType := "READS"+ if isWriteContext(node, assignTypes, cached.Language) {+ edgeType = "WRITES"++ if isAugmentedAssignmentContext(node) {+ readKey := [3]string{callerQN, targetQN, "READS"}+ if !seen[readKey] {+ seen[readKey] = true+ edges = append(edges, resolvedEdge{+ CallerQN: callerQN,+ TargetQN: targetQN,+ Type: "READS",+ })+ }+ }+ }++ key := [3]string{callerQN, targetQN, edgeType}+ if seen[key] {+ return false+ }+ seen[key] = true++ edges = append(edges, resolvedEdge{+ CallerQN: callerQN,+ TargetQN: targetQN,+ Type: edgeType,+ })+ return false+ })++ return edges+}++// resolveVariableStrict resolves an identifier to a Variable node using only+// Strategy 1 (import map) and Strategy 2 (same module). Never project-wide fallback.+func (p *Pipeline) resolveVariableStrict(name, moduleQN string, importMap map[string]string) string {+ p.registry.mu.RLock()+ defer p.registry.mu.RUnlock()++ if importMap != nil {+ if resolved, ok := importMap[name]; ok {+ if label, exists := p.registry.exact[resolved]; exists && label == "Variable" {+ return resolved+ }+ }+ }++ candidate := moduleQN + "." + name+ if label, exists := p.registry.exact[candidate]; exists && label == "Variable" {+ return candidate+ }++ return ""+}++// isWriteContext returns true if the identifier is on the left side of an assignment.+func isWriteContext(node *tree_sitter.Node, assignTypes map[string]bool, language lang.Language) bool {+ parent := node.Parent()+ if parent == nil {+ return false+ }++ // For Go short_var_declaration, left is always expression_list+ if language == lang.Go && parent.Kind() == "expression_list" {+ if gp := parent.Parent(); gp != nil && gp.Kind() == "short_var_declaration" {+ leftNode := gp.ChildByFieldName("left")+ if leftNode != nil && leftNode.Id() == parent.Id() {+ return true+ }+ }+ }++ if !assignTypes[parent.Kind()] {+ return false+ }++ leftNode := parent.ChildByFieldName("left")+ if leftNode == nil {+ return false+ }++ if leftNode.Id() == node.Id() {+ return true+ }++ // For Go: left is expression_list, check if node is inside it+ if leftNode.Kind() == "expression_list" {+ for i := uint(0); i < leftNode.NamedChildCount(); i++ {+ child := leftNode.NamedChild(i)+ if child != nil && child.Id() == node.Id() {+ return true+ }+ }+ }++ return false+}++// isAugmentedAssignmentContext returns true if the node is in an augmented assignment (+=, -=).+func isAugmentedAssignmentContext(node *tree_sitter.Node) bool {+ parent := node.Parent()+ if parent == nil {+ return false+ }+ switch parent.Kind() {+ case "augmented_assignment", "augmented_assignment_expression", "compound_assignment_expr":+ return true+ }+ return false+}++// extractGlobalVarNames extracts module-level variable names for the global_vars+// Module property.+func extractGlobalVarNames(root *tree_sitter.Node, source []byte, f discover.FileInfo, spec *lang.LanguageSpec) []string {+ if spec == nil || len(spec.VariableNodeTypes) == 0 {+ return nil+ }+ varTypes := toSet(spec.VariableNodeTypes)+ var names []string++ parser.Walk(root, func(node *tree_sitter.Node) bool {+ if !isModuleLevelNode(node, f.Language) || !varTypes[node.Kind()] {+ return true+ }+ names = append(names, extractVarNames(node, source, f.Language)...)+ return false+ })++ // Deduplicate+ seen := make(map[string]bool, len(names))+ deduped := names[:0]+ for _, n := range names {+ if n != "" && n != "_" && !seen[n] {+ seen[n] = true+ deduped = append(deduped, n)+ }+ }+ return deduped+}diff --git a/internal/pipeline/resolver.go b/internal/pipeline/resolver.goindex 338ea6f16..d304bcea8 100644--- a/internal/pipeline/resolver.go+++ b/internal/pipeline/resolver.go@@ -183,6 +183,13 @@ func (r *FunctionRegistry) FuzzyResolve(calleeName, moduleQN string) (string, boreturn "", false}+// LabelOf returns the node label for a qualified name, or "" if not registered.+func (r *FunctionRegistry) LabelOf(qualifiedName string) string {+ r.mu.RLock()+ defer r.mu.RUnlock()+ return r.exact[qualifiedName]+}+// Exists returns true if a qualified name is registered.// Uses RLock for concurrent read safety.func (r *FunctionRegistry) Exists(qualifiedName string) bool {diff --git a/internal/pipeline/testdetect.go b/internal/pipeline/testdetect.gonew file mode 100644index 000000000..831360935--- /dev/null+++ b/internal/pipeline/testdetect.go@@ -0,0 +1,131 @@+package pipeline++import (+ "path/filepath"+ "strings"++ "github.com/DeusData/codebase-memory-mcp/internal/lang"+)++// isTestFile returns true if the file path indicates a test file for the given language.+func isTestFile(relPath string, language lang.Language) bool {+ base := filepath.Base(relPath)+ dir := filepath.Dir(relPath)++ switch language {+ case lang.Go:+ return strings.HasSuffix(base, "_test.go")++ case lang.Python:+ if strings.HasPrefix(base, "test_") || strings.HasSuffix(base, "_test.py") {+ return true+ }+ return containsTestDir(dir, "__tests__", "tests")++ case lang.JavaScript, lang.TypeScript, lang.TSX:+ noExt := strings.TrimSuffix(base, filepath.Ext(base))+ // Handle double-extensions like .test.ts, .spec.tsx+ if strings.HasSuffix(noExt, ".test") || strings.HasSuffix(noExt, ".spec") {+ return true+ }+ return containsTestDir(dir, "__tests__")++ case lang.Java:+ if strings.HasSuffix(base, "Test.java") || strings.HasSuffix(base, "Tests.java") {+ return true+ }+ return containsTestDir(dir, "src/test")++ case lang.Rust:+ if strings.HasSuffix(base, "_test.rs") {+ return true+ }+ return containsTestDir(dir, "tests")++ case lang.CPP:+ noExt := strings.TrimSuffix(base, filepath.Ext(base))+ if strings.HasSuffix(noExt, "_test") {+ return true+ }+ return containsTestDir(dir, "test", "tests")++ case lang.PHP:+ if strings.HasSuffix(base, "Test.php") {+ return true+ }+ return containsTestDir(dir, "tests")++ case lang.Scala:+ noExt := strings.TrimSuffix(base, filepath.Ext(base))+ if strings.HasSuffix(noExt, "Spec") || strings.HasSuffix(noExt, "Test") {+ return true+ }+ return containsTestDir(dir, "src/test")++ case lang.CSharp:+ noExt := strings.TrimSuffix(base, filepath.Ext(base))+ if strings.HasSuffix(noExt, "Test") || strings.HasSuffix(noExt, "Tests") {+ return true+ }+ return containsTestDir(dir, "Tests", "tests")+ }++ return false+}++// containsTestDir returns true if any segment of dir matches one of the patterns.+func containsTestDir(dir string, patterns ...string) bool {+ normalised := filepath.ToSlash(dir)+ for _, p := range patterns {+ if strings.Contains(normalised, p+"/") || strings.HasSuffix(normalised, p) {+ return true+ }+ }+ return false+}++// isTestFunction returns true if the function name indicates a test entry point+// (as opposed to a test helper). Used by passTests to gate TESTS edge creation.+func isTestFunction(funcName string, language lang.Language) bool {+ switch language {+ case lang.Go:+ return strings.HasPrefix(funcName, "Test") ||+ strings.HasPrefix(funcName, "Benchmark") ||+ strings.HasPrefix(funcName, "Example")++ case lang.Python:+ return strings.HasPrefix(funcName, "test_") ||+ strings.HasPrefix(funcName, "Test")++ case lang.JavaScript, lang.TypeScript, lang.TSX:+ // Jest/Vitest test entry functions+ switch funcName {+ case "describe", "it", "test", "beforeAll", "afterAll", "beforeEach", "afterEach":+ return true+ }+ return false++ case lang.Java:+ // JUnit test methods often annotated; name heuristic as fallback+ return strings.HasPrefix(funcName, "test") ||+ strings.HasSuffix(funcName, "Test")++ case lang.Rust:+ return strings.HasPrefix(funcName, "test_") ||+ strings.HasPrefix(funcName, "Test")++ case lang.PHP:+ return strings.HasPrefix(funcName, "test") ||+ strings.HasPrefix(funcName, "Test")++ case lang.Scala:+ return strings.HasPrefix(funcName, "test") ||+ strings.HasSuffix(funcName, "Spec")++ case lang.CSharp:+ return strings.HasPrefix(funcName, "Test") ||+ strings.HasSuffix(funcName, "Test")+ }++ return false+}diff --git a/internal/pipeline/tests.go b/internal/pipeline/tests.gonew file mode 100644index 000000000..39b2f53dd--- /dev/null+++ b/internal/pipeline/tests.go@@ -0,0 +1,200 @@+package pipeline++import (+ "log/slog"+ "path/filepath"+ "strings"++ "github.com/DeusData/codebase-memory-mcp/internal/lang"+ "github.com/DeusData/codebase-memory-mcp/internal/store"+)++// passTests derives TESTS and TESTS_FILE edges from existing CALLS/IMPORTS data.+// No AST needed — purely DB-driven post-processing.+func (p *Pipeline) passTests() {+ slog.Info("pass.tests")+ testsCount := p.createTestsEdges()+ testsFileCount := p.createTestsFileEdges()+ slog.Info("pass.tests.done", "tests", testsCount, "tests_file", testsFileCount)+}++// createTestsEdges finds CALLS edges from test functions to production functions+// and creates TESTS edges.+func (p *Pipeline) createTestsEdges() int {+ callEdges, err := p.Store.FindEdgesByType(p.ProjectName, "CALLS")+ if err != nil {+ slog.Warn("pass.tests.calls.err", "err", err)+ return 0+ }++ if len(callEdges) == 0 {+ return 0+ }++ // Collect all unique source/target node IDs+ nodeIDs := make(map[int64]bool)+ for _, e := range callEdges {+ nodeIDs[e.SourceID] = true+ nodeIDs[e.TargetID] = true+ }++ // Batch-load all nodes+ idList := make([]int64, 0, len(nodeIDs))+ for id := range nodeIDs {+ idList = append(idList, id)+ }+ nodeMap := p.batchLoadNodes(idList)++ edges := make([]*store.Edge, 0, len(callEdges)/4)+ for _, e := range callEdges {+ srcNode := nodeMap[e.SourceID]+ tgtNode := nodeMap[e.TargetID]+ if srcNode == nil || tgtNode == nil {+ continue+ }++ srcLang := langFromFilePath(srcNode.FilePath)+ tgtLang := langFromFilePath(tgtNode.FilePath)++ // Source must be in a test file, target must NOT be+ if !isTestFile(srcNode.FilePath, srcLang) {+ continue+ }+ if isTestFile(tgtNode.FilePath, tgtLang) {+ continue+ }++ // Test helper gate: only Test*/test_* named functions produce TESTS edges+ if !isTestFunction(srcNode.Name, srcLang) {+ continue+ }++ edges = append(edges, &store.Edge{+ Project: p.ProjectName,+ SourceID: srcNode.ID,+ TargetID: tgtNode.ID,+ Type: "TESTS",+ })+ }++ if len(edges) > 0 {+ if err := p.Store.InsertEdgeBatch(edges); err != nil {+ slog.Warn("pass.tests.insert.err", "err", err)+ }+ }+ return len(edges)+}++// createTestsFileEdges creates TESTS_FILE edges from test modules to production modules.+func (p *Pipeline) createTestsFileEdges() int {+ modules, err := p.Store.FindNodesByLabel(p.ProjectName, "Module")+ if err != nil {+ return 0+ }++ testModules := make(map[int64]*store.Node)+ prodModules := make(map[string]*store.Node) // keyed by file path+ for _, m := range modules {+ modLang := langFromFilePath(m.FilePath)+ if isTestFile(m.FilePath, modLang) {+ testModules[m.ID] = m+ } else {+ prodModules[m.FilePath] = m+ }+ }++ var edges []*store.Edge+ for _, testMod := range testModules {+ // Strategy 1: naming convention+ prodPath := testFileToProductionFile(testMod.FilePath)+ if prodPath != "" {+ if prodMod, ok := prodModules[prodPath]; ok {+ edges = append(edges, &store.Edge{+ Project: p.ProjectName,+ SourceID: testMod.ID,+ TargetID: prodMod.ID,+ Type: "TESTS_FILE",+ })+ continue+ }+ }++ // Strategy 2: IMPORTS from test module to production modules+ importEdges, _ := p.Store.FindEdgesBySourceAndType(testMod.ID, "IMPORTS")+ for _, ie := range importEdges {+ targetNode, _ := p.Store.FindNodeByID(ie.TargetID)+ if targetNode == nil || targetNode.Label != "Module" {+ continue+ }+ tgtLang := langFromFilePath(targetNode.FilePath)+ if !isTestFile(targetNode.FilePath, tgtLang) {+ edges = append(edges, &store.Edge{+ Project: p.ProjectName,+ SourceID: testMod.ID,+ TargetID: targetNode.ID,+ Type: "TESTS_FILE",+ })+ }+ }+ }++ if len(edges) > 0 {+ if err := p.Store.InsertEdgeBatch(edges); err != nil {+ slog.Warn("pass.tests_file.insert.err", "err", err)+ }+ }+ return len(edges)+}++// testFileToProductionFile returns the expected production file path for a test file.+func testFileToProductionFile(testPath string) string {+ base := filepath.Base(testPath)+ dir := filepath.Dir(testPath)+ ext := filepath.Ext(base)+ noExt := strings.TrimSuffix(base, ext)++ // Go: foo_test.go → foo.go+ if strings.HasSuffix(noExt, "_test") && ext == ".go" {+ return filepath.Join(dir, strings.TrimSuffix(noExt, "_test")+ext)+ }++ // Python: test_foo.py → foo.py+ if strings.HasPrefix(noExt, "test_") && ext == ".py" {+ return filepath.Join(dir, strings.TrimPrefix(noExt, "test_")+ext)+ }++ // JS/TS: foo.test.ts → foo.ts, foo.spec.ts → foo.ts+ for _, suffix := range []string{".test", ".spec"} {+ if strings.HasSuffix(noExt, suffix) {+ return filepath.Join(dir, strings.TrimSuffix(noExt, suffix)+ext)+ }+ }++ return ""+}++// batchLoadNodes loads nodes by ID using batch queries.+func (p *Pipeline) batchLoadNodes(ids []int64) map[int64]*store.Node {+ result := make(map[int64]*store.Node, len(ids))+ nodes, err := p.Store.FindNodesByIDs(ids)+ if err != nil {+ // Fallback to individual lookups+ for _, id := range ids {+ if n, err := p.Store.FindNodeByID(id); err == nil && n != nil {+ result[n.ID] = n+ }+ }+ return result+ }+ for _, n := range nodes {+ result[n.ID] = n+ }+ return result+}++// langFromFilePath determines the language from a file extension.+func langFromFilePath(filePath string) lang.Language {+ ext := filepath.Ext(filePath)+ l, _ := lang.LanguageForExtension(ext)+ return l+}diff --git a/internal/pipeline/throws.go b/internal/pipeline/throws.gonew file mode 100644index 000000000..bde0b9627--- /dev/null+++ b/internal/pipeline/throws.go@@ -0,0 +1,217 @@+package pipeline++import (+ "log/slog"+ "runtime"+ "strings"++ tree_sitter "github.com/tree-sitter/go-tree-sitter"+ "golang.org/x/sync/errgroup"++ "github.com/DeusData/codebase-memory-mcp/internal/fqn"+ "github.com/DeusData/codebase-memory-mcp/internal/lang"+ "github.com/DeusData/codebase-memory-mcp/internal/parser"+)++// passThrows creates THROWS/RAISES edges from functions to exception classes.+// Covers Java throws clauses + throw/raise statements in Java, Python, TS/JS.+func (p *Pipeline) passThrows() {+ slog.Info("pass.throws")++ type fileEntry struct {+ relPath string+ cached *cachedAST+ }+ files := make([]fileEntry, 0, len(p.astCache))+ for relPath, cached := range p.astCache {+ spec := lang.ForLanguage(cached.Language)+ if spec == nil {+ continue+ }+ if len(spec.ThrowNodeTypes) == 0 && spec.ThrowsClauseField == "" {+ continue+ }+ files = append(files, fileEntry{relPath, cached})+ }++ if len(files) == 0 {+ return+ }++ results := make([][]resolvedEdge, len(files))+ numWorkers := runtime.NumCPU()+ if numWorkers > len(files) {+ numWorkers = len(files)+ }++ g := new(errgroup.Group)+ g.SetLimit(numWorkers)+ for i, fe := range files {+ g.Go(func() error {+ results[i] = p.resolveFileThrows(fe.relPath, fe.cached)+ return nil+ })+ }+ _ = g.Wait()++ p.flushResolvedEdges(results)++ total := 0+ for _, r := range results {+ total += len(r)+ }+ slog.Info("pass.throws.done", "edges", total)+}++func (p *Pipeline) resolveFileThrows(relPath string, cached *cachedAST) []resolvedEdge {+ spec := lang.ForLanguage(cached.Language)+ if spec == nil {+ return nil+ }++ funcTypes := toSet(spec.FunctionNodeTypes)+ throwTypes := toSet(spec.ThrowNodeTypes)+ moduleQN := fqn.ModuleQN(p.ProjectName, relPath)+ importMap := p.importMaps[moduleQN]+ root := cached.Tree.RootNode()++ var edges []resolvedEdge++ parser.Walk(root, func(node *tree_sitter.Node) bool {+ if !funcTypes[node.Kind()] {+ return true+ }++ nameNode := node.ChildByFieldName("name")+ if nameNode == nil {+ return false+ }+ funcName := parser.NodeText(nameNode, cached.Source)+ if funcName == "" {+ return false+ }+ funcQN := fqn.Compute(p.ProjectName, relPath, funcName)++ // Java: declared throws clause+ edges = append(edges, p.extractDeclaredThrows(node, cached.Source, spec, funcQN, moduleQN, importMap)...)++ // Body: throw/raise statements+ edges = append(edges, p.extractBodyThrows(node, cached, throwTypes, funcQN, moduleQN, importMap)...)++ return false+ })++ return edges+}++// extractDeclaredThrows handles Java's "throws ExceptionA, ExceptionB" clause.+func (p *Pipeline) extractDeclaredThrows(node *tree_sitter.Node, source []byte, spec *lang.LanguageSpec, funcQN, moduleQN string, importMap map[string]string) []resolvedEdge {+ if spec.ThrowsClauseField == "" {+ return nil+ }+ throwsNode := node.ChildByFieldName(spec.ThrowsClauseField)+ if throwsNode == nil {+ return nil+ }++ var edges []resolvedEdge+ for i := uint(0); i < throwsNode.NamedChildCount(); i++ {+ child := throwsNode.NamedChild(i)+ if child == nil {+ continue+ }+ exName := cleanTypeName(parser.NodeText(child, source))+ if exName == "" || isBuiltinType(exName) {+ continue+ }+ targetQN := resolveAsClass(exName, p.registry, moduleQN, importMap)+ if targetQN != "" {+ edges = append(edges, resolvedEdge{+ CallerQN: funcQN,+ TargetQN: targetQN,+ Type: "THROWS",+ Properties: map[string]any{"declared": true},+ })+ }+ }+ return edges+}++// extractBodyThrows walks function body for throw/raise statements.+func (p *Pipeline) extractBodyThrows(node *tree_sitter.Node, cached *cachedAST, throwTypes map[string]bool, funcQN, moduleQN string, importMap map[string]string) []resolvedEdge {+ bodyNode := node.ChildByFieldName("body")+ if bodyNode == nil {+ bodyNode = node.ChildByFieldName("block")+ }+ if bodyNode == nil {+ return nil+ }++ var edges []resolvedEdge+ parser.Walk(bodyNode, func(child *tree_sitter.Node) bool {+ if !throwTypes[child.Kind()] {+ return true+ }++ exName := extractThrownExceptionName(child, cached.Source)+ if exName == "" || isBuiltinType(exName) {+ return false+ }+ targetQN := resolveAsClass(exName, p.registry, moduleQN, importMap)+ if targetQN != "" {+ edges = append(edges, resolvedEdge{+ CallerQN: funcQN,+ TargetQN: targetQN,+ Type: "RAISES",+ Properties: map[string]any{"declared": false},+ })+ }+ return false+ })+ return edges+}++// extractThrownExceptionName extracts the class name from a throw/raise statement.+func extractThrownExceptionName(throwNode *tree_sitter.Node, source []byte) string {+ for i := uint(0); i < throwNode.NamedChildCount(); i++ {+ child := throwNode.NamedChild(i)+ if child == nil {+ continue+ }+ if name := extractExceptionClassName(child, source); name != "" {+ return name+ }+ }+ return ""+}++// extractExceptionClassName extracts the class name from an exception expression.+func extractExceptionClassName(child *tree_sitter.Node, source []byte) string {+ switch child.Kind() {+ case "new_expression", "object_creation_expression":+ if typeNode := child.ChildByFieldName("type"); typeNode != nil {+ return cleanTypeName(parser.NodeText(typeNode, source))+ }+ if child.NamedChildCount() > 0 {+ first := child.NamedChild(0)+ if first != nil && (first.Kind() == "identifier" || first.Kind() == "type_identifier") {+ return parser.NodeText(first, source)+ }+ }++ case "call", "call_expression":+ funcNode := child.ChildByFieldName("function")+ if funcNode == nil {+ return ""+ }+ name := parser.NodeText(funcNode, source)+ if idx := strings.LastIndex(name, "."); idx >= 0 {+ name = name[idx+1:]+ }+ return name++ case "identifier", "type_identifier":+ return parser.NodeText(child, source)+ }+ return ""+}diff --git a/internal/pipeline/usages.go b/internal/pipeline/usages.goindex 49e1fef04..c736e4a35 100644--- a/internal/pipeline/usages.go+++ b/internal/pipeline/usages.go@@ -179,6 +179,11 @@ func (p *Pipeline) resolveFileUsages(relPath string, cached *cachedAST) []resolvreturn false}+ // Skip Variable targets — handled by passReadsWrites (READS/WRITES edges)+ if p.registry.LabelOf(targetQN) == "Variable" {+ return false+ }+if targetQN == callerQN {return false}diff --git a/internal/pipeline/usestype.go b/internal/pipeline/usestype.gonew file mode 100644index 000000000..dcd596d93--- /dev/null+++ b/internal/pipeline/usestype.go@@ -0,0 +1,249 @@+package pipeline++import (+ "log/slog"+ "runtime"++ tree_sitter "github.com/tree-sitter/go-tree-sitter"+ "golang.org/x/sync/errgroup"++ "github.com/DeusData/codebase-memory-mcp/internal/fqn"+ "github.com/DeusData/codebase-memory-mcp/internal/lang"+ "github.com/DeusData/codebase-memory-mcp/internal/parser"+)++// passUsesType creates USES_TYPE edges from functions to type/class nodes+// referenced in their signatures and bodies.+// Parallel per-file (same two-stage pattern as passCalls/passUsages).+func (p *Pipeline) passUsesType() {+ slog.Info("pass.usestype")++ type fileEntry struct {+ relPath string+ cached *cachedAST+ }+ var files []fileEntry+ for relPath, cached := range p.astCache {+ if lang.ForLanguage(cached.Language) != nil {+ files = append(files, fileEntry{relPath, cached})+ }+ }++ if len(files) == 0 {+ return+ }++ // Stage 1: Parallel per-file type reference extraction+ results := make([][]resolvedEdge, len(files))+ numWorkers := runtime.NumCPU()+ if numWorkers > len(files) {+ numWorkers = len(files)+ }++ g := new(errgroup.Group)+ g.SetLimit(numWorkers)+ for i, fe := range files {+ g.Go(func() error {+ results[i] = p.resolveFileTypeRefs(fe.relPath, fe.cached)+ return nil+ })+ }+ _ = g.Wait()++ // Stage 2: Batch write+ p.flushResolvedEdges(results)++ total := 0+ for _, r := range results {+ total += len(r)+ }+ slog.Info("pass.usestype.done", "edges", total)+}++// resolveFileTypeRefs extracts type references from function signatures and bodies.+func (p *Pipeline) resolveFileTypeRefs(relPath string, cached *cachedAST) []resolvedEdge {+ spec := lang.ForLanguage(cached.Language)+ if spec == nil {+ return nil+ }++ funcTypes := toSet(spec.FunctionNodeTypes)+ moduleQN := fqn.ModuleQN(p.ProjectName, relPath)+ importMap := p.importMaps[moduleQN]+ root := cached.Tree.RootNode()++ var edges []resolvedEdge+ seen := make(map[[2]string]bool)++ parser.Walk(root, func(node *tree_sitter.Node) bool {+ if !funcTypes[node.Kind()] {+ return true+ }++ nameNode := node.ChildByFieldName("name")+ if nameNode == nil {+ return false+ }+ funcName := parser.NodeText(nameNode, cached.Source)+ if funcName == "" {+ return false+ }+ funcQN := fqn.Compute(p.ProjectName, relPath, funcName)++ // Extract type references from signature + body+ allTypes := make(map[string]bool)+ for _, t := range p.extractSignatureTypeRefs(node, cached.Source, cached.Language) {+ allTypes[t] = true+ }+ for _, t := range p.extractBodyTypeRefs(node, cached.Source, cached.Language) {+ allTypes[t] = true+ }++ for typeName := range allTypes {+ if isBuiltinType(typeName) {+ continue+ }+ targetQN := resolveAsClass(typeName, p.registry, moduleQN, importMap)+ if targetQN == "" {+ continue+ }+ key := [2]string{funcQN, targetQN}+ if seen[key] {+ continue+ }+ seen[key] = true+ edges = append(edges, resolvedEdge{+ CallerQN: funcQN,+ TargetQN: targetQN,+ Type: "USES_TYPE",+ })+ }++ return false+ })++ return edges+}++// extractSignatureTypeRefs extracts type names from function parameter + return type.+func (p *Pipeline) extractSignatureTypeRefs(funcNode *tree_sitter.Node, source []byte, language lang.Language) []string {+ var types []string++ if paramsNode := funcNode.ChildByFieldName("parameters"); paramsNode != nil {+ types = append(types, extractParamTypes(paramsNode, source, language)...)+ }++ for _, field := range []string{"result", "return_type", "type"} {+ if retNode := funcNode.ChildByFieldName(field); retNode != nil {+ types = append(types, extractReturnTypes(retNode, source, language)...)+ break+ }+ }++ return types+}++// extractBodyTypeRefs walks a function body for type references in+// local var declarations, type assertions, casts, and generic instantiations.+func (p *Pipeline) extractBodyTypeRefs(funcNode *tree_sitter.Node, source []byte, language lang.Language) []string {+ bodyNode := funcNode.ChildByFieldName("body")+ if bodyNode == nil {+ bodyNode = funcNode.ChildByFieldName("block")+ }+ if bodyNode == nil {+ return nil+ }++ var types []string+ seen := make(map[string]bool)++ addType := func(name string) {+ name = cleanTypeName(name)+ if name != "" && !isBuiltinType(name) && !seen[name] {+ seen[name] = true+ types = append(types, name)+ }+ }++ parser.Walk(bodyNode, func(node *tree_sitter.Node) bool {+ extractBodyTypeRef(node, source, language, addType)+ return true+ })++ return types+}++// extractBodyTypeRef extracts a type reference from a single body AST node.+func extractBodyTypeRef(node *tree_sitter.Node, source []byte, language lang.Language, addType func(string)) {+ kind := node.Kind()+ switch language {+ case lang.Go:+ extractGoBodyType(node, source, kind, addType)+ case lang.TypeScript, lang.TSX:+ extractTSBodyType(node, source, kind, addType)+ case lang.Java:+ extractJavaBodyType(node, source, kind, addType)+ case lang.Python:+ if kind == "assignment" {+ if typeNode := node.ChildByFieldName("type"); typeNode != nil {+ addType(parser.NodeText(typeNode, source))+ }+ }+ case lang.Rust:+ extractRustBodyType(node, source, kind, addType)+ }+}++func extractGoBodyType(node *tree_sitter.Node, source []byte, kind string, addType func(string)) {+ switch kind {+ case "var_spec", "type_assertion", "type_conversion_expression", "composite_literal":+ if typeNode := node.ChildByFieldName("type"); typeNode != nil {+ addType(parser.NodeText(typeNode, source))+ }+ }+}++func extractTSBodyType(node *tree_sitter.Node, source []byte, kind string, addType func(string)) {+ switch kind {+ case "variable_declarator":+ if typeAnn := findChildByKind(node, "type_annotation"); typeAnn != nil {+ addType(extractTypeFromAnnotation(typeAnn, source))+ }+ case "as_expression", "satisfies_expression":+ if typeNode := node.ChildByFieldName("type"); typeNode != nil {+ addType(parser.NodeText(typeNode, source))+ }+ case "type_arguments":+ for i := uint(0); i < node.NamedChildCount(); i++ {+ if child := node.NamedChild(i); child != nil {+ addType(parser.NodeText(child, source))+ }+ }+ }+}++func extractJavaBodyType(node *tree_sitter.Node, source []byte, kind string, addType func(string)) {+ switch kind {+ case "local_variable_declaration", "cast_expression":+ if typeNode := node.ChildByFieldName("type"); typeNode != nil {+ addType(parser.NodeText(typeNode, source))+ }+ case "generic_type":+ if typeArgs := findChildByKind(node, "type_arguments"); typeArgs != nil {+ for i := uint(0); i < typeArgs.NamedChildCount(); i++ {+ if child := typeArgs.NamedChild(i); child != nil {+ addType(parser.NodeText(child, source))+ }+ }+ }+ }+}++func extractRustBodyType(node *tree_sitter.Node, source []byte, kind string, addType func(string)) {+ switch kind {+ case "let_declaration", "type_cast_expression":+ if typeNode := node.ChildByFieldName("type"); typeNode != nil {+ addType(parser.NodeText(typeNode, source))+ }+ }+}diff --git a/internal/store/edges.go b/internal/store/edges.goindex cb0110a34..41b8d86af 100644--- a/internal/store/edges.go+++ b/internal/store/edges.go@@ -3,6 +3,7 @@ package storeimport ("database/sql""fmt"+ "log/slog""strings")@@ -87,6 +88,13 @@ func (s *Store) DeleteEdgesByProject(project string) error {return err}+// CountEdgesByType returns the number of edges of a given type for a project.+func (s *Store) CountEdgesByType(project, edgeType string) (int, error) {+ var count int+ err := s.q.QueryRow("SELECT COUNT(*) FROM edges WHERE project=? AND type=?", project, edgeType).Scan(&count)+ return count, err+}+// DeleteEdgesByType deletes all edges of a given type for a project.func (s *Store) DeleteEdgesByType(project, edgeType string) error {_, err := s.q.Exec("DELETE FROM edges WHERE project=? AND type=?", project, edgeType)@@ -156,8 +164,25 @@ func (s *Store) insertEdgeChunk(batch []*Edge) error {}sb.WriteString(` ON CONFLICT(source_id, target_id, type) DO UPDATE SET properties=excluded.properties`)- if _, err := s.q.Exec(sb.String(), args...); err != nil {- return fmt.Errorf("insert edge batch: %w", err)+ _, err := s.q.Exec(sb.String(), args...)+ if err == nil {+ return nil+ }++ // Batch failed (likely FK constraint from stale LastInsertId) — fall back+ // to one-at-a-time inserts so one bad edge doesn't break the entire batch.+ skipped := 0+ for _, e := range batch {+ 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`,+ e.Project, e.SourceID, e.TargetID, e.Type, marshalProps(e.Properties)); err2 != nil {+ skipped+++ }+ }+ if skipped > 0 {+ slog.Info("edges.batch.fk_skip", "skipped", skipped, "total", len(batch))}return nil}@@ -199,18 +224,23 @@ func (s *Store) FindEdgesBySourceIDs(sourceIDs []int64, edgeTypes []string) (mapquery += " AND type IN (" + strings.Join(typePH, ",") + ")"}- rows, err := s.q.Query(query, args...)- if err != nil {- return nil, fmt.Errorf("find edges by source ids: %w", err)- }- edges, err := scanEdges(rows)- rows.Close()- if err != nil {+ if err := func() error {+ rows, err := s.q.Query(query, args...)+ if err != nil {+ return fmt.Errorf("find edges by source ids: %w", err)+ }+ defer rows.Close()+ edges, err := scanEdges(rows)+ if err != nil {+ return err+ }+ for _, e := range edges {+ result[e.SourceID] = append(result[e.SourceID], e)+ }+ return nil+ }(); err != nil {return nil, err}- for _, e := range edges {- result[e.SourceID] = append(result[e.SourceID], e)- }}return result, nil}@@ -252,18 +282,23 @@ func (s *Store) FindEdgesByTargetIDs(targetIDs []int64, edgeTypes []string) (mapquery += " AND type IN (" + strings.Join(typePH, ",") + ")"}- rows, err := s.q.Query(query, args...)- if err != nil {- return nil, fmt.Errorf("find edges by target ids: %w", err)- }- edges, err := scanEdges(rows)- rows.Close()- if err != nil {+ if err := func() error {+ rows, err := s.q.Query(query, args...)+ if err != nil {+ return fmt.Errorf("find edges by target ids: %w", err)+ }+ defer rows.Close()+ edges, err := scanEdges(rows)+ if err != nil {+ return err+ }+ for _, e := range edges {+ result[e.TargetID] = append(result[e.TargetID], e)+ }+ return nil+ }(); err != nil {return nil, err}- for _, e := range edges {- result[e.TargetID] = append(result[e.TargetID], e)- }}return result, nil}diff --git a/internal/store/migrate.go b/internal/store/migrate.gonew file mode 100644index 000000000..a950a6b3e--- /dev/null+++ b/internal/store/migrate.go@@ -0,0 +1,185 @@+package store++import (+ "database/sql"+ "fmt"+ "io"+ "log/slog"+ "os"+ "path/filepath"++ _ "github.com/mattn/go-sqlite3"+)++// migrate performs a one-time migration from the legacy single-DB layout+// (codebase-memory.db) to per-project .db files.+// Safe to call multiple times — it's a no-op if the legacy DB doesn't exist+// or has already been migrated.+func (r *StoreRouter) migrate() error {+ legacyPath := filepath.Join(r.dir, "codebase-memory.db")+ if _, err := os.Stat(legacyPath); os.IsNotExist(err) {+ return nil // nothing to migrate+ }++ slog.Info("migrate.start", "legacy_db", legacyPath)++ // Backup the legacy DB before any modification+ backupPath := legacyPath + ".backup"+ if _, err := os.Stat(backupPath); os.IsNotExist(err) {+ if err := copyFile(legacyPath, backupPath); err != nil {+ return fmt.Errorf("backup: %w", err)+ }+ slog.Info("migrate.backup", "path", backupPath)+ }++ // Open legacy DB+ legacyDB, err := sql.Open("sqlite3", legacyPath+"?_journal_mode=WAL&_busy_timeout=5000")+ if err != nil {+ return fmt.Errorf("open legacy: %w", err)+ }+ defer legacyDB.Close()++ // Get list of projects+ rows, err := legacyDB.Query("SELECT name FROM projects")+ if err != nil {+ return fmt.Errorf("list projects: %w", err)+ }+ defer rows.Close()++ var projectNames []string+ for rows.Next() {+ var name string+ if err := rows.Scan(&name); err != nil {+ return fmt.Errorf("scan project: %w", err)+ }+ projectNames = append(projectNames, name)+ }+ if err := rows.Err(); err != nil {+ return fmt.Errorf("rows iteration: %w", err)+ }++ if len(projectNames) == 0 {+ slog.Info("migrate.skip", "reason", "no_projects")+ return r.renameLegacy(legacyPath)+ }++ // Migrate each project+ migrated := 0+ for _, name := range projectNames {+ targetPath := filepath.Join(r.dir, name+".db")+ if _, err := os.Stat(targetPath); err == nil {+ slog.Info("migrate.project.exists", "project", name)+ migrated+++ continue+ }++ if err := r.migrateProject(legacyDB, name, targetPath); err != nil {+ slog.Warn("migrate.project.err", "project", name, "err", err)+ continue // skip failed projects, user can re-index+ }+ migrated+++ }++ slog.Info("migrate.done", "total", len(projectNames), "migrated", migrated)+ return r.renameLegacy(legacyPath)+}++// migrateProject copies one project's data from the legacy DB into a new per-project DB.+func (r *StoreRouter) migrateProject(legacyDB *sql.DB, projectName, targetPath string) error {+ // Create the target DB with schema+ targetStore, err := OpenPath(targetPath)+ if err != nil {+ return fmt.Errorf("open target: %w", err)+ }+ targetStore.Close()++ // Use ATTACH DATABASE for efficient bulk copy+ _, err = legacyDB.Exec("ATTACH DATABASE ? AS target", targetPath)+ if err != nil {+ return fmt.Errorf("attach: %w", err)+ }+ defer func() {+ _, _ = legacyDB.Exec("DETACH DATABASE target")+ }()++ // Copy projects+ _, err = legacyDB.Exec(`INSERT OR REPLACE INTO target.projects (name, indexed_at, root_path)+ SELECT name, indexed_at, root_path FROM projects WHERE name=?`, projectName)+ if err != nil {+ return fmt.Errorf("copy projects: %w", err)+ }++ // Copy nodes (preserving IDs)+ _, err = legacyDB.Exec(`INSERT OR REPLACE INTO target.nodes (id, project, label, name, qualified_name, file_path, start_line, end_line, properties)+ SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties FROM nodes WHERE project=?`, projectName)+ if err != nil {+ return fmt.Errorf("copy nodes: %w", err)+ }++ // Copy edges (preserving IDs)+ _, err = legacyDB.Exec(`INSERT OR REPLACE INTO target.edges (id, project, source_id, target_id, type, properties)+ SELECT id, project, source_id, target_id, type, properties FROM edges WHERE project=?`, projectName)+ if err != nil {+ return fmt.Errorf("copy edges: %w", err)+ }++ // Copy file_hashes+ _, err = legacyDB.Exec(`INSERT OR REPLACE INTO target.file_hashes (project, rel_path, sha256)+ SELECT project, rel_path, sha256 FROM file_hashes WHERE project=?`, projectName)+ if err != nil {+ return fmt.Errorf("copy file_hashes: %w", err)+ }++ // Verify row counts+ var srcNodes, tgtNodes int+ _ = legacyDB.QueryRow("SELECT COUNT(*) FROM nodes WHERE project=?", projectName).Scan(&srcNodes)+ _ = legacyDB.QueryRow("SELECT COUNT(*) FROM target.nodes WHERE project=?", projectName).Scan(&tgtNodes)+ if srcNodes != tgtNodes {+ return fmt.Errorf("node count mismatch: src=%d tgt=%d", srcNodes, tgtNodes)+ }++ var srcEdges, tgtEdges int+ _ = legacyDB.QueryRow("SELECT COUNT(*) FROM edges WHERE project=?", projectName).Scan(&srcEdges)+ _ = legacyDB.QueryRow("SELECT COUNT(*) FROM target.edges WHERE project=?", projectName).Scan(&tgtEdges)+ if srcEdges != tgtEdges {+ return fmt.Errorf("edge count mismatch: src=%d tgt=%d", srcEdges, tgtEdges)+ }++ slog.Info("migrate.project.ok", "project", projectName, "nodes", srcNodes, "edges", srcEdges)+ return nil+}++// renameLegacy renames the legacy DB to mark migration as complete.+func (r *StoreRouter) renameLegacy(legacyPath string) error {+ migratedPath := legacyPath + ".migrated"+ if err := os.Rename(legacyPath, migratedPath); err != nil {+ return fmt.Errorf("rename legacy: %w", err)+ }+ // Also clean up WAL/SHM files+ for _, suffix := range []string{"-wal", "-shm"} {+ _ = os.Remove(legacyPath + suffix)+ }+ slog.Info("migrate.renamed", "from", legacyPath, "to", migratedPath)+ return nil+}++// copyFile copies a file from src to dst.+func copyFile(src, dst string) error {+ in, err := os.Open(src)+ if err != nil {+ return err+ }+ defer in.Close()++ out, err := os.Create(dst)+ if err != nil {+ return err+ }+ defer out.Close()++ _, err = io.Copy(out, in)+ if err != nil {+ return err+ }+ return out.Sync()+}diff --git a/internal/store/nodes.go b/internal/store/nodes.goindex bde2f6823..d9c5ffde1 100644--- a/internal/store/nodes.go+++ b/internal/store/nodes.go@@ -7,6 +7,9 @@ import ()// UpsertNode inserts or replaces a node (dedup by qualified_name).+// Note: LastInsertId() can return stale IDs for ON CONFLICT DO UPDATE,+// causing occasional FK failures in downstream edge inserts. This is+// accepted for performance — the fallback SELECT only runs when id==0.func (s *Store) UpsertNode(n *Node) (int64, error) {res, err := s.q.Exec(`INSERT INTO nodes (project, label, name, qualified_name, file_path, start_line, end_line, properties)@@ -130,18 +133,23 @@ func (s *Store) FindNodesByIDs(ids []int64) (map[int64]*Node, error) {"SELECT id, project, label, name, qualified_name, file_path, start_line, end_line, properties FROM nodes WHERE id IN (%s)",strings.Join(placeholders, ","))- rows, err := s.q.Query(query, args...)- if err != nil {- return nil, fmt.Errorf("find nodes by ids: %w", err)- }- nodes, err := scanNodes(rows)- rows.Close()- if err != nil {+ if err := func() error {+ rows, err := s.q.Query(query, args...)+ if err != nil {+ return fmt.Errorf("find nodes by ids: %w", err)+ }+ defer rows.Close()+ nodes, err := scanNodes(rows)+ if err != nil {+ return err+ }+ for _, n := range nodes {+ result[n.ID] = n+ }+ return nil+ }(); err != nil {return nil, err}- for _, n := range nodes {- result[n.ID] = n- }}return result, nil}diff --git a/internal/store/router.go b/internal/store/router.gonew file mode 100644index 000000000..afb140f53--- /dev/null+++ b/internal/store/router.go@@ -0,0 +1,197 @@+package store++import (+ "fmt"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "sync"+)++// ProjectInfo holds metadata about a discovered project database.+type ProjectInfo struct {+ Name string+ DBPath string+ RootPath string+}++// StoreRouter manages per-project SQLite databases.+// Each project gets its own .db file in the cache directory.+type StoreRouter struct {+ dir string // ~/.cache/codebase-memory-mcp/+ stores map[string]*Store // project name → open Store (lazy)+ mu sync.Mutex+}++// NewRouter creates a StoreRouter, ensuring the cache directory exists.+// Runs migration from single-DB layout if needed.+func NewRouter() (*StoreRouter, error) {+ dir, err := cacheDir()+ if err != nil {+ return nil, err+ }++ r := &StoreRouter{+ dir: dir,+ stores: make(map[string]*Store),+ }++ // Run one-time migration from single DB to per-project DBs+ if err := r.migrate(); err != nil {+ slog.Warn("router.migrate.err", "err", err)+ }++ return r, nil+}++// NewRouterWithDir creates a StoreRouter using a custom directory (for testing).+// No migration is run.+func NewRouterWithDir(dir string) (*StoreRouter, error) {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ return nil, fmt.Errorf("mkdir: %w", err)+ }+ return &StoreRouter{+ dir: dir,+ stores: make(map[string]*Store),+ }, nil+}++// ForProject returns the Store for the given project, opening it lazily.+func (r *StoreRouter) ForProject(name string) (*Store, error) {+ if name == "*" || name == "all" {+ return nil, fmt.Errorf("invalid project name: %q", name)+ }+ r.mu.Lock()+ defer r.mu.Unlock()++ if s, ok := r.stores[name]; ok {+ return s, nil+ }++ s, err := OpenInDir(r.dir, name)+ if err != nil {+ return nil, fmt.Errorf("open store %q: %w", name, err)+ }+ r.stores[name] = s+ return s, nil+}++// AllStores opens all .db files in the cache dir and returns a name→Store map.+func (r *StoreRouter) AllStores() map[string]*Store {+ r.mu.Lock()+ defer r.mu.Unlock()++ entries, err := os.ReadDir(r.dir)+ if err != nil {+ slog.Warn("router.all_stores.readdir", "err", err)+ return r.stores+ }++ for _, e := range entries {+ if e.IsDir() || !strings.HasSuffix(e.Name(), ".db") {+ continue+ }+ name := strings.TrimSuffix(e.Name(), ".db")+ if name == "codebase-memory" {+ continue // skip legacy single DB+ }+ if _, ok := r.stores[name]; ok {+ continue+ }+ s, err := OpenInDir(r.dir, name)+ if err != nil {+ slog.Warn("router.all_stores.open", "project", name, "err", err)+ continue+ }+ r.stores[name] = s+ }++ // Return a copy to avoid external mutation+ result := make(map[string]*Store, len(r.stores))+ for k, v := range r.stores {+ result[k] = v+ }+ return result+}++// ListProjects scans .db files and queries each for metadata.+func (r *StoreRouter) ListProjects() ([]*ProjectInfo, error) {+ entries, err := os.ReadDir(r.dir)+ if err != nil {+ return nil, fmt.Errorf("readdir: %w", err)+ }++ result := make([]*ProjectInfo, 0, len(entries))+ for _, e := range entries {+ if e.IsDir() || !strings.HasSuffix(e.Name(), ".db") {+ continue+ }+ name := strings.TrimSuffix(e.Name(), ".db")+ if name == "codebase-memory" {+ continue // skip legacy single DB+ }+ info := &ProjectInfo{+ Name: name,+ DBPath: filepath.Join(r.dir, e.Name()),+ }++ // Try to get root_path from the projects table+ s, err := r.ForProject(name)+ if err == nil {+ projects, listErr := s.ListProjects()+ if listErr == nil && len(projects) > 0 {+ info.RootPath = projects[0].RootPath+ }+ }++ result = append(result, info)+ }+ return result, nil+}++// DeleteProject closes the Store connection and removes the .db + WAL/SHM files.+func (r *StoreRouter) DeleteProject(name string) error {+ r.mu.Lock()+ defer r.mu.Unlock()++ if s, ok := r.stores[name]; ok {+ s.Close()+ delete(r.stores, name)+ }++ dbPath := filepath.Join(r.dir, name+".db")+ for _, suffix := range []string{"", "-wal", "-shm"} {+ p := dbPath + suffix+ if err := os.Remove(p); err != nil && !os.IsNotExist(err) {+ return fmt.Errorf("remove %s: %w", p, err)+ }+ }+ slog.Info("router.delete", "project", name)+ return nil+}++// HasProject checks if a .db file exists for the given project (without opening it).+func (r *StoreRouter) HasProject(name string) bool {+ dbPath := filepath.Join(r.dir, name+".db")+ _, err := os.Stat(dbPath)+ return err == nil+}++// Dir returns the cache directory path.+func (r *StoreRouter) Dir() string {+ return r.dir+}++// CloseAll closes all open Store connections.+func (r *StoreRouter) CloseAll() {+ r.mu.Lock()+ defer r.mu.Unlock()++ for name, s := range r.stores {+ if err := s.Close(); err != nil {+ slog.Warn("router.close", "project", name, "err", err)+ }+ }+ r.stores = make(map[string]*Store)+}diff --git a/internal/store/search.go b/internal/store/search.goindex c1c2cc4a4..b50ab3ad1 100644--- a/internal/store/search.go+++ b/internal/store/search.go@@ -3,6 +3,7 @@ package storeimport ("fmt""regexp"+ "slices""strings")@@ -21,6 +22,7 @@ type SearchParams struct {ExcludeEntryPoints bool // when true, exclude nodes with is_entry_point=trueIncludeConnected bool // when true, load connected node names (expensive, off by default)ExcludeLabels []string // labels to exclude from results+ SortBy string // "relevance" (default), "name", "degree"}// SearchResult is a node with edge degree info.@@ -123,8 +125,11 @@ func (s *Store) Search(params *SearchParams) (*SearchOutput, error) {if needsNameScan || hasDegreeFilter {sqlLimit = 200000 // must cover full dataset for accurate Go-side filtering} else {- // Fetch enough for offset + limit- sqlLimit = params.Offset + params.Limit+ // Scan beyond offset+limit so total/has_more are accurate.+ // The +1000 buffer ensures has_more is correct for result sets+ // up to ~1000 beyond the requested page, at negligible cost+ // (~2 extra batch degree queries ≈ 20ms worst case).+ sqlLimit = params.Offset + params.Limit + 1000if sqlLimit > 200000 {sqlLimit = 200000}@@ -171,6 +176,13 @@ func (s *Store) Search(params *SearchParams) (*SearchOutput, error) {return nil, err}+ // Sort results before pagination+ sortBy := params.SortBy+ if sortBy == "" {+ sortBy = "relevance"+ }+ sortSearchResults(allResults, sortBy, params.NamePattern)+total := len(allResults)// Apply offset and limit@@ -390,6 +402,73 @@ func extractLikeHints(pattern string) []string {return hints}+// sortSearchResults sorts results based on the requested sort mode.+func sortSearchResults(results []*SearchResult, sortBy, namePattern string) {+ switch sortBy {+ case "name":+ slices.SortStableFunc(results, func(a, b *SearchResult) int {+ return strings.Compare(a.Node.Name, b.Node.Name)+ })+ case "degree":+ slices.SortStableFunc(results, func(a, b *SearchResult) int {+ return (b.InDegree + b.OutDegree) - (a.InDegree + a.OutDegree) // descending+ })+ default: // "relevance"+ literalQuery := extractLiteralQuery(namePattern)+ lowerQuery := strings.ToLower(literalQuery)+ slices.SortStableFunc(results, func(a, b *SearchResult) int {+ return compareRelevance(a, b, literalQuery, lowerQuery)+ })+ }+}++// compareRelevance implements tiered relevance: exact match > prefix match > degree.+func compareRelevance(a, b *SearchResult, literalQuery, lowerQuery string) int {+ if literalQuery == "" {+ return compareDegree(a, b)+ }+ // Tier 1: Exact name match (case-insensitive)+ if cmp := compareBool(strings.EqualFold(a.Node.Name, literalQuery), strings.EqualFold(b.Node.Name, literalQuery)); cmp != 0 {+ return cmp+ }+ // Tier 2: Prefix match+ if cmp := compareBool(strings.HasPrefix(strings.ToLower(a.Node.Name), lowerQuery), strings.HasPrefix(strings.ToLower(b.Node.Name), lowerQuery)); cmp != 0 {+ return cmp+ }+ return compareDegree(a, b)+}++// compareBool returns -1 if a is true and b is false, 1 if opposite, 0 if equal.+func compareBool(a, b bool) int {+ if a == b {+ return 0+ }+ if a {+ return -1+ }+ return 1+}++// compareDegree compares total degree descending (higher degree first).+func compareDegree(a, b *SearchResult) int {+ return (b.InDegree + b.OutDegree) - (a.InDegree + a.OutDegree)+}++// extractLiteralQuery returns the literal string from a regex pattern if it contains+// no special regex syntax beyond leading/trailing .* anchors and (?i) flag.+func extractLiteralQuery(pattern string) string {+ if pattern == "" {+ return ""+ }+ p := strings.TrimPrefix(pattern, "(?i)")+ p = strings.TrimPrefix(p, ".*")+ p = strings.TrimSuffix(p, ".*")+ if strings.ContainsAny(p, ".*+?^${}()|[]\\") {+ return ""+ }+ return p+}+// filterByNamePattern filters nodes by a regex name pattern.func filterByNamePattern(nodes []*Node, pattern string) ([]*Node, error) {re, err := regexp.Compile(pattern)diff --git a/internal/store/store.go b/internal/store/store.goindex 57d77b7f8..3ebc88266 100644--- a/internal/store/store.go+++ b/internal/store/store.go@@ -62,7 +62,7 @@ func cacheDir() (string, error) {return dir, nil}-// Open opens or creates a SQLite database for the given project.+// Open opens or creates a SQLite database for the given project in the default cache dir.func Open(project string) (*Store, error) {dir, err := cacheDir()if err != nil {@@ -72,6 +72,12 @@ func Open(project string) (*Store, error) {return OpenPath(dbPath)}+// OpenInDir opens or creates a SQLite database for the given project in a specific directory.+func OpenInDir(dir, project string) (*Store, error) {+ dbPath := filepath.Join(dir, project+".db")+ return OpenPath(dbPath)+}+// OpenPath opens a SQLite database at the given path.func OpenPath(dbPath string) (*Store, error) {dsn := dbPath + "?_journal_mode=WAL" +diff --git a/internal/tools/code_search.go b/internal/tools/code_search.goindex 1553ab773..052b0006b 100644--- a/internal/tools/code_search.go+++ b/internal/tools/code_search.go@@ -9,6 +9,7 @@ import ("regexp""strings"+ "github.com/DeusData/codebase-memory-mcp/internal/store""github.com/modelcontextprotocol/go-sdk/mcp")@@ -26,6 +27,7 @@ type searchCodeParams struct {offset intisRegex boolre *regexp.Regexp+ project string}// parseSearchCodeParams extracts and validates search_code parameters from the request.@@ -41,6 +43,7 @@ func parseSearchCodeParams(req *mcp.CallToolRequest) (*searchCodeParams, *mcp.CamaxResults: getIntArg(args, "max_results", 10),offset: getIntArg(args, "offset", 0),isRegex: getBoolArg(args, "regex"),+ project: getStringArg(args, "project"),}if p.pattern == "" {@@ -64,12 +67,12 @@ func (s *Server) handleSearchCode(_ context.Context, req *mcp.CallToolRequest) (}// Resolve project root- root, err := s.resolveProjectRoot()+ root, err := s.resolveProjectRoot(params.project)if err != nil {return errResult(fmt.Sprintf("resolve root: %v", err)), nil}- filePaths := s.collectSearchFilePaths(params.fileGlob)+ filePaths := s.collectSearchFilePaths(params.fileGlob, params.project)// Collect all matches up to offset+maxResults for accurate total countfetchLimit := params.offset + params.maxResults@@ -98,7 +101,7 @@ func (s *Server) handleSearchCode(_ context.Context, req *mcp.CallToolRequest) (}pageMatches := allMatches[start:end]- return jsonResult(map[string]any{+ responseData := map[string]any{"pattern": params.pattern,"total": total,"limit": params.maxResults,@@ -106,15 +109,19 @@ func (s *Server) handleSearchCode(_ context.Context, req *mcp.CallToolRequest) ("has_more": hasMore,"matches": pageMatches,"files_count": len(filePaths),- }), nil+ }+ s.addIndexStatus(responseData)+ s.addUpdateNotice(responseData)++ return jsonResult(responseData), nil}// collectSearchFilePaths gathers indexed file paths, optionally filtered by a glob pattern.-func (s *Server) collectSearchFilePaths(fileGlob string) []string {- projects, _ := s.store.ListProjects()+func (s *Server) collectSearchFilePaths(fileGlob, project string) []string {var filePaths []string- for _, p := range projects {- files, _ := s.store.FindNodesByLabel(p.Name, "File")++ collectFromStore := func(st *store.Store, projName string) {+ files, _ := st.FindNodesByLabel(projName, "File")for _, f := range files {if f.FilePath == "" {continue@@ -131,6 +138,19 @@ func (s *Server) collectSearchFilePaths(fileGlob string) []string {filePaths = append(filePaths, f.FilePath)}}++ st, err := s.resolveStore(project)+ if err != nil {+ return filePaths+ }++ projName := s.resolveProjectName(project)+ projects, _ := st.ListProjects()+ if len(projects) > 0 {+ projName = projects[0].Name+ }+ collectFromStore(st, projName)+return filePaths}diff --git a/internal/tools/file.go b/internal/tools/file.goindex 49eaebf1b..2b57f8c96 100644--- a/internal/tools/file.go+++ b/internal/tools/file.go@@ -28,7 +28,7 @@ func (s *Server) handleReadFile(_ context.Context, req *mcp.CallToolRequest) (*m// Resolve relative path against project rootabsPath := filePathif !filepath.IsAbs(filePath) {- root, rootErr := s.resolveProjectRoot()+ root, rootErr := s.resolveProjectRoot("")if rootErr != nil {return errResult(fmt.Sprintf("resolve root: %v", rootErr)), nil}@@ -102,7 +102,8 @@ func (s *Server) handleListDirectory(_ context.Context, req *mcp.CallToolRequest// Resolve relative path against project rootabsPath := dirPathif dirPath == "" || !filepath.IsAbs(dirPath) {- root, rootErr := s.resolveProjectRoot()+ project := getStringArg(args, "project")+ root, rootErr := s.resolveProjectRoot(project)if rootErr != nil {return errResult(fmt.Sprintf("resolve root: %v", rootErr)), nil}@@ -191,9 +192,31 @@ func listDirChildren(absPath string) ([]dirEntry, error) {return entries, nil}-// resolveProjectRoot finds the first indexed project root path.-func (s *Server) resolveProjectRoot() (string, error) {- projects, err := s.store.ListProjects()+// resolveProjectRoot finds a project root path by name or from session.+func (s *Server) resolveProjectRoot(project string) (string, error) {+ if project == "*" || project == "all" {+ return "", 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")+ }++ // Use session root if available and no specific project requested+ if project == "" && s.sessionRoot != "" {+ return s.sessionRoot, nil+ }++ projName := s.resolveProjectName(project)+ if projName == "" {+ return "", fmt.Errorf("no projects indexed")+ }+ if !s.router.HasProject(projName) {+ return "", fmt.Errorf("project %q not found; use list_projects to see available projects", projName)+ }++ st, err := s.router.ForProject(projName)+ if err != nil {+ return "", err+ }++ projects, err := st.ListProjects()if err != nil {return "", err}diff --git a/internal/tools/index.go b/internal/tools/index.goindex f5848d4f7..2f58d7a04 100644--- a/internal/tools/index.go+++ b/internal/tools/index.go@@ -18,7 +18,10 @@ func (s *Server) handleIndexRepository(_ context.Context, req *mcp.CallToolRequerepoPath := getStringArg(args, "repo_path")if repoPath == "" {- return errResult("repo_path is required"), nil+ repoPath = s.sessionRoot // auto-detected from session+ }+ if repoPath == "" {+ return errResult("repo_path is required (no session root detected)"), nil}// Resolve to absolute path@@ -33,17 +36,28 @@ func (s *Server) handleIndexRepository(_ context.Context, req *mcp.CallToolReques.indexMu.Lock()defer s.indexMu.Unlock()+ // Get per-project store+ st, err := s.router.ForProject(projectName)+ if err != nil {+ return errResult(fmt.Sprintf("store: %v", err)), nil+ }+// Run the indexing pipeline- p := pipeline.New(s.store, absPath)+ p := pipeline.New(st, absPath)if err := p.Run(); err != nil {return errResult(fmt.Sprintf("indexing failed: %v", err)), nil}+ // Update session state if this is the session project+ if projectName == s.sessionProject {+ s.indexStatus.Store("ready")+ }+// Gather stats- nodeCount, _ := s.store.CountNodes(projectName)- edgeCount, _ := s.store.CountEdges(projectName)+ nodeCount, _ := st.CountNodes(projectName)+ edgeCount, _ := st.CountEdges(projectName)- proj, _ := s.store.GetProject(projectName)+ proj, _ := st.GetProject(projectName)indexedAt := store.Now()if proj != nil {indexedAt = proj.IndexedAtdiff --git a/internal/tools/projects.go b/internal/tools/projects.goindex 90a0714dd..fe61a2c35 100644--- a/internal/tools/projects.go+++ b/internal/tools/projects.go@@ -3,35 +3,58 @@ package toolsimport ("context""fmt"+ "path/filepath"+ "time""github.com/modelcontextprotocol/go-sdk/mcp")func (s *Server) handleListProjects(_ context.Context, _ *mcp.CallToolRequest) (*mcp.CallToolResult, error) {- projects, err := s.store.ListProjects()+ projectInfos, err := s.router.ListProjects()if err != nil {return errResult(fmt.Sprintf("list projects: %v", err)), nil}- type projectInfo struct {- Name string `json:"name"`- RootPath string `json:"root_path"`- IndexedAt string `json:"indexed_at"`- Nodes int `json:"nodes"`- Edges int `json:"edges"`+ type projectEntry struct {+ Name string `json:"name"`+ RootPath string `json:"root_path"`+ IndexedAt string `json:"indexed_at"`+ Nodes int `json:"nodes"`+ Edges int `json:"edges"`+ DBPath string `json:"db_path"`+ IsSessionProject bool `json:"is_session_project,omitempty"`}- result := make([]projectInfo, 0, len(projects))- for _, p := range projects {- nc, _ := s.store.CountNodes(p.Name)- ec, _ := s.store.CountEdges(p.Name)- result = append(result, projectInfo{- Name: p.Name,- RootPath: p.RootPath,- IndexedAt: p.IndexedAt,+ result := make([]projectEntry, 0, len(projectInfos))+ for _, info := range projectInfos {+ st, err := s.router.ForProject(info.Name)+ if err != nil {+ continue+ }++ nc, _ := st.CountNodes(info.Name)+ ec, _ := st.CountEdges(info.Name)++ indexedAt := ""+ rootPath := info.RootPath+ proj, _ := st.GetProject(info.Name)+ if proj != nil {+ indexedAt = proj.IndexedAt+ rootPath = proj.RootPath+ }++ entry := projectEntry{+ Name: info.Name,+ RootPath: rootPath,+ IndexedAt: indexedAt,Nodes: nc,Edges: ec,- })+ DBPath: info.DBPath,+ }+ if info.Name == s.sessionProject {+ entry.IsSessionProject = true+ }+ result = append(result, entry)}return jsonResult(result), nil@@ -49,22 +72,100 @@ func (s *Server) handleDeleteProject(_ context.Context, req *mcp.CallToolRequest}// Verify project exists- proj, _ := s.store.GetProject(name)- if proj == nil {+ if !s.router.HasProject(name) {return errResult(fmt.Sprintf("project not found: %s", name)), nil}- if err := s.store.DeleteProject(name); err != nil {+ if err := s.router.DeleteProject(name); err != nil {return errResult(fmt.Sprintf("delete failed: %v", err)), nil}- // file_hashes table is not cascaded from projects — delete separately- if err := s.store.DeleteFileHashes(name); err != nil {- return errResult(fmt.Sprintf("delete file hashes failed: %v", err)), nil- }-return jsonResult(map[string]any{"deleted": name,"status": "ok",}), nil}++func (s *Server) handleIndexStatus(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {+ args, err := parseArgs(req)+ if err != nil {+ return errResult(err.Error()), nil+ }++ projectName := getStringArg(args, "project")+ if projectName == "" {+ projectName = s.sessionProject+ }+ if projectName == "" {+ return jsonResult(map[string]any{+ "status": "no_session",+ "message": "No session project detected. Pass 'project' parameter or ensure the MCP client provides roots.",+ }), nil+ }++ // Check if DB file exists+ if !s.router.HasProject(projectName) {+ return jsonResult(map[string]any{+ "project": projectName,+ "status": "not_indexed",+ "message": fmt.Sprintf("No index found for project %q. Call index_repository to create one.", projectName),+ "db_path": filepath.Join(s.router.Dir(), projectName+".db"),+ }), nil+ }++ // Get store and project metadata+ st, err := s.router.ForProject(projectName)+ if err != nil {+ return errResult(fmt.Sprintf("open store: %v", err)), nil+ }++ proj, _ := st.GetProject(projectName)+ if proj == nil {+ // DB file exists but no project row — partially indexed or corrupted+ return jsonResult(map[string]any{+ "project": projectName,+ "status": "partial",+ "message": "Database file exists but project metadata is missing. Re-run index_repository.",+ "db_path": filepath.Join(s.router.Dir(), projectName+".db"),+ }), nil+ }++ nodeCount, _ := st.CountNodes(projectName)+ edgeCount, _ := st.CountEdges(projectName)++ // Determine current indexing state+ currentStatus, _ := s.indexStatus.Load().(string)+ isSessionProject := projectName == s.sessionProject++ result := map[string]any{+ "project": projectName,+ "status": "ready",+ "indexed_at": proj.IndexedAt,+ "root_path": proj.RootPath,+ "nodes": nodeCount,+ "edges": edgeCount,+ "is_session_project": isSessionProject,+ "db_path": filepath.Join(s.router.Dir(), projectName+".db"),+ }++ // Determine index type (initial vs incremental)+ if nodeCount == 0 && edgeCount == 0 {+ result["index_type"] = "none"+ } else {+ result["index_type"] = "incremental"+ }++ // If this is the session project and indexing is in progress+ if isSessionProject && currentStatus == "indexing" {+ result["status"] = "indexing"+ if startedAt, ok := s.indexStartedAt.Load().(time.Time); ok {+ result["index_started_at"] = startedAt.UTC().Format(time.RFC3339)+ result["index_elapsed_seconds"] = int(time.Since(startedAt).Seconds())+ }+ if nodeCount == 0 {+ result["index_type"] = "initial"+ }+ }++ return jsonResult(result), nil+}diff --git a/internal/tools/query.go b/internal/tools/query.goindex 99b3d6471..55641b046 100644--- a/internal/tools/query.go+++ b/internal/tools/query.go@@ -19,15 +19,24 @@ func (s *Server) handleQueryGraph(_ context.Context, req *mcp.CallToolRequest) (return errResult("missing required 'query' parameter"), nil}- exec := &cypher.Executor{Store: s.store}+ st, err := s.resolveStore(getStringArg(args, "project"))+ if err != nil {+ return errResult(fmt.Sprintf("resolve store: %v", err)), nil+ }++ exec := &cypher.Executor{Store: st}result, err := exec.Execute(query)if err != nil {return errResult(fmt.Sprintf("query error: %v", err)), nil}- return jsonResult(map[string]any{+ responseData := map[string]any{"columns": result.Columns,"rows": result.Rows,"total": len(result.Rows),- }), nil+ }+ s.addIndexStatus(responseData)+ s.addUpdateNotice(responseData)++ return jsonResult(responseData), nil}diff --git a/internal/tools/schema.go b/internal/tools/schema.goindex 8e780ac8a..172706a50 100644--- a/internal/tools/schema.go+++ b/internal/tools/schema.go@@ -8,17 +8,27 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp")-func (s *Server) handleGetGraphSchema(_ context.Context, _ *mcp.CallToolRequest) (*mcp.CallToolResult, error) {- projects, err := s.store.ListProjects()+func (s *Server) handleGetGraphSchema(_ context.Context, req *mcp.CallToolRequest) (*mcp.CallToolResult, error) {+ args, err := parseArgs(req)if err != nil {- return errResult(fmt.Sprintf("list projects: %v", err)), nil+ return errResult(err.Error()), nil}- if len(projects) == 0 {- return jsonResult(map[string]any{- "message": "no projects indexed",- "projects": []any{},- }), nil+ project := getStringArg(args, "project")+ st, err := s.resolveStore(project)+ if err != nil {+ return errResult(fmt.Sprintf("resolve store: %v", err)), nil+ }++ projName := s.resolveProjectName(project)+ projects, _ := st.ListProjects()+ if len(projects) > 0 {+ projName = projects[0].Name+ }++ schema, schemaErr := st.GetSchema(projName)+ if schemaErr != nil {+ return errResult(fmt.Sprintf("schema: %v", schemaErr)), nil}type projectSchema struct {@@ -26,19 +36,7 @@ func (s *Server) handleGetGraphSchema(_ context.Context, _ *mcp.CallToolRequest)Schema *store.SchemaInfo `json:"schema"`}- schemas := make([]projectSchema, 0, len(projects))- for _, p := range projects {- schema, schemaErr := s.store.GetSchema(p.Name)- if schemaErr != nil {- continue- }- schemas = append(schemas, projectSchema{- Project: p.Name,- Schema: schema,- })- }-return jsonResult(map[string]any{- "projects": schemas,+ "projects": []projectSchema{{Project: projName, Schema: schema}},}), nil}diff --git a/internal/tools/search.go b/internal/tools/search.goindex b82fe8767..52e62d09a 100644--- a/internal/tools/search.go+++ b/internal/tools/search.go@@ -28,32 +28,38 @@ func (s *Server) handleSearchGraph(_ context.Context, req *mcp.CallToolRequest)IncludeConnected: getBoolArg(args, "include_connected"),}- // Parse exclude_labels array+ // Parse exclude_labels array; default to excluding Community nodesif rawLabels, ok := args["exclude_labels"]; ok {if labelArr, ok := rawLabels.([]any); ok {for _, l := range labelArr {- if s, ok := l.(string); ok {- params.ExcludeLabels = append(params.ExcludeLabels, s)+ if str, ok := l.(string); ok {+ params.ExcludeLabels = append(params.ExcludeLabels, str)}}}+ } else {+ params.ExcludeLabels = []string{"Community"}}- projectFilter := getStringArg(args, "project")+ params.SortBy = getStringArg(args, "sort_by")- projects, err := s.store.ListProjects()+ st, err := s.resolveStore(getStringArg(args, "project"))if err != nil {- return errResult(fmt.Sprintf("list projects: %v", err)), nil+ return errResult(fmt.Sprintf("resolve store: %v", err)), nil}- if len(projects) == 0 {- return jsonResult(map[string]any{- "message": "no projects indexed",- "results": []any{},- }), nil+ projName := s.resolveProjectName(getStringArg(args, "project"))+ projects, _ := st.ListProjects()+ if len(projects) > 0 {+ projName = projects[0].Name+ }++ params.Project = projName+ output, searchErr := st.Search(params)+ if searchErr != nil {+ return errResult(fmt.Sprintf("search: %v", searchErr)), nil}- // Search across matching projects, collect resultstype resultEntry struct {Project string `json:"project"`Name string `json:"name"`@@ -67,40 +73,31 @@ func (s *Server) handleSearchGraph(_ context.Context, req *mcp.CallToolRequest)ConnectedNames []string `json:"connected_names,omitempty"`}- var allResults []resultEntry- totalAcrossProjects := 0- for _, p := range projects {- if projectFilter != "" && p.Name != projectFilter {- continue- }- params.Project = p.Name- output, searchErr := s.store.Search(params)- if searchErr != nil {- continue- }- totalAcrossProjects += output.Total- for _, r := range output.Results {- entry := resultEntry{- Project: p.Name,- Name: r.Node.Name,- QualifiedName: r.Node.QualifiedName,- Label: r.Node.Label,- FilePath: r.Node.FilePath,- StartLine: r.Node.StartLine,- EndLine: r.Node.EndLine,- InDegree: r.InDegree,- OutDegree: r.OutDegree,- ConnectedNames: r.ConnectedNames,- }- allResults = append(allResults, entry)- }+ results := make([]resultEntry, 0, len(output.Results))+ for _, r := range output.Results {+ results = append(results, resultEntry{+ Project: projName,+ Name: r.Node.Name,+ QualifiedName: r.Node.QualifiedName,+ Label: r.Node.Label,+ FilePath: r.Node.FilePath,+ StartLine: r.Node.StartLine,+ EndLine: r.Node.EndLine,+ InDegree: r.InDegree,+ OutDegree: r.OutDegree,+ ConnectedNames: r.ConnectedNames,+ })}- return jsonResult(map[string]any{- "total": totalAcrossProjects,+ responseData := map[string]any{+ "total": output.Total,"limit": params.Limit,"offset": params.Offset,- "has_more": params.Offset+params.Limit < totalAcrossProjects,- "results": allResults,- }), nil+ "has_more": params.Offset+params.Limit < output.Total,+ "results": results,+ }+ s.addIndexStatus(responseData)+ s.addUpdateNotice(responseData)++ return jsonResult(responseData), nil}diff --git a/internal/tools/snippet.go b/internal/tools/snippet.goindex 57aeecea0..232f5cd2b 100644--- a/internal/tools/snippet.go+++ b/internal/tools/snippet.go@@ -22,8 +22,14 @@ func (s *Server) handleGetCodeSnippet(_ context.Context, req *mcp.CallToolRequesreturn errResult("qualified_name is required"), nil}- // Find the node across all projects- node, project, _ := s.findNodeByQNAcrossProjects(qn)+ project := getStringArg(args, "project")+ effectiveProject := s.resolveProjectName(project)++ // 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+ }if node == nil {return errResult(fmt.Sprintf("node not found: %s", qn)), nil}@@ -36,10 +42,15 @@ func (s *Server) handleGetCodeSnippet(_ context.Context, req *mcp.CallToolRequesreturn errResult("node has no line range"), nil}- // Resolve file path against the project's root path- proj, _ := s.store.GetProject(project)+ // 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+ }++ proj, _ := st.GetProject(foundProject)if proj == nil {- return errResult(fmt.Sprintf("project not found: %s", project)), nil+ return errResult(fmt.Sprintf("project not found: %s", foundProject)), nil}absPath := filepath.Join(proj.RootPath, node.FilePath)diff --git a/internal/tools/tools.go b/internal/tools/tools.goindex df246d286..c1fc5dcbc 100644--- a/internal/tools/tools.go+++ b/internal/tools/tools.go@@ -4,9 +4,18 @@ import ("context""encoding/json""fmt"+ "io""log/slog"+ "net/http"+ "net/url"+ "os"+ "path/filepath""sort"+ "strconv"+ "strings""sync"+ "sync/atomic"+ "time""github.com/DeusData/codebase-memory-mcp/internal/pipeline""github.com/DeusData/codebase-memory-mcp/internal/store"@@ -14,30 +23,49 @@ import ("github.com/modelcontextprotocol/go-sdk/mcp")+// Version is the current release version, referenced by MCP handshake and update checker.+const Version = "0.2.0"++// 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"+// Server wraps the MCP server with tool handlers.type Server struct {mcp *mcp.Server- store *store.Store+ router *store.StoreRouterwatcher *watcher.WatcherindexMu sync.Mutexhandlers map[string]mcp.ToolHandler++ // Session-aware fields (set once via sync.Once, then immutable)+ sessionOnce sync.Once+ sessionRoot string // absolute path from client+ sessionProject string // filepath.Base(sessionRoot)+ indexStatus atomic.Value+ indexStartedAt atomic.Value // time.Time — when current/last index started+ updateNotice atomic.Value // string — set once by checkForUpdate, cleared after first injection}// NewServer creates a new MCP server with all tools registered.-func NewServer(s *store.Store) *Server {+func NewServer(r *store.StoreRouter) *Server {srv := &Server{- store: s,- mcp: mcp.NewServer(- &mcp.Implementation{- Name: "codebase-memory-mcp",- Version: "0.1.3",- },- nil,- ),+ router: r,handlers: make(map[string]mcp.ToolHandler),}++ srv.mcp = mcp.NewServer(+ &mcp.Implementation{+ Name: "codebase-memory-mcp",+ Version: Version,+ },+ &mcp.ServerOptions{+ InitializedHandler: srv.onInitialized,+ RootsListChangedHandler: srv.onRootsChanged,+ },+ )+srv.registerTools()- srv.watcher = watcher.New(s, srv.syncProject)+ srv.watcher = watcher.New(r, srv.syncProject)return srv}@@ -49,13 +77,17 @@ func (s *Server) StartWatcher(ctx context.Context) {// syncProject is called by the watcher when file changes are detected.// Uses TryLock to skip if an index operation is already in progress.-func (s *Server) syncProject(_, rootPath string) error {+func (s *Server) syncProject(projectName, rootPath string) error {if !s.indexMu.TryLock() {slog.Debug("watcher.skip", "path", rootPath, "reason", "index_in_progress")return nil}defer s.indexMu.Unlock()- p := pipeline.New(s.store, rootPath)+ st, err := s.router.ForProject(projectName)+ if err != nil {+ return fmt.Errorf("store for %s: %w", projectName, err)+ }+ p := pipeline.New(st, rootPath)return p.Run()}@@ -64,7 +96,234 @@ func (s *Server) MCPServer() *mcp.Server {return s.mcp}-// addTool registers a tool in both the MCP server and the local dispatch map.+// Router returns the underlying StoreRouter for direct access (e.g. CLI mode).+func (s *Server) Router() *store.StoreRouter {+ return s.router+}++// SessionProject returns the auto-detected session project name (may be empty).+func (s *Server) SessionProject() string {+ return s.sessionProject+}++// SetSessionRoot sets the session root path directly (for CLI mode).+func (s *Server) SetSessionRoot(rootPath string) {+ s.sessionOnce.Do(func() {+ s.sessionRoot = rootPath+ if rootPath != "" {+ s.sessionProject = filepath.Base(rootPath)+ }+ })+ go s.checkForUpdate()+}++// --- Session detection ---++// onInitialized is called when the client sends notifications/initialized.+func (s *Server) onInitialized(ctx context.Context, req *mcp.InitializedRequest) {+ s.sessionOnce.Do(func() {+ s.sessionRoot = s.detectSessionRoot(ctx, req.Session)+ if s.sessionRoot != "" {+ s.sessionProject = filepath.Base(s.sessionRoot)+ s.startAutoIndex()+ }+ })+ go s.checkForUpdate()+}++// onRootsChanged re-detects session root if not yet set.+func (s *Server) onRootsChanged(ctx context.Context, req *mcp.RootsListChangedRequest) {+ s.sessionOnce.Do(func() {+ s.sessionRoot = s.detectSessionRoot(ctx, req.Session)+ if s.sessionRoot != "" {+ s.sessionProject = filepath.Base(s.sessionRoot)+ s.startAutoIndex()+ }+ })+ go s.checkForUpdate()+}++// detectSessionRoot tries multiple fallback strategies to find the project root.+func (s *Server) detectSessionRoot(ctx context.Context, session *mcp.ServerSession) string {+ // 1. Try MCP roots protocol+ if session != nil {+ result, err := session.ListRoots(ctx, nil)+ if err == nil && len(result.Roots) > 0 {+ uri := result.Roots[0].URI+ if path, ok := parseFileURI(uri); ok {+ slog.Info("session.root.from_roots", "path", path)+ return path+ }+ }+ }++ // 2. Fall back to process working directory+ if cwd, err := os.Getwd(); err == nil && cwd != "/" && cwd != os.Getenv("HOME") {+ slog.Info("session.root.from_cwd", "path", cwd)+ return cwd+ }++ // 3. Fall back to single indexed project from DB+ projects, err := s.router.ListProjects()+ if err == nil && len(projects) == 1 && projects[0].RootPath != "" {+ slog.Info("session.root.from_db", "path", projects[0].RootPath)+ return projects[0].RootPath+ }++ slog.Info("session.root.none", "reason", "no_roots_no_cwd_no_single_project")+ return ""+}++// parseFileURI extracts a filesystem path from a file:// URI.+func parseFileURI(uri string) (string, bool) {+ u, err := url.Parse(uri)+ if err != nil || u.Scheme != "file" {+ return "", false+ }+ return u.Path, true+}++// startAutoIndex triggers background indexing for the session project.+func (s *Server) startAutoIndex() {+ hasDB := s.router.HasProject(s.sessionProject)++ if !hasDB {+ s.indexStatus.Store("indexing")+ } else {+ s.indexStatus.Store("ready")+ }++ go func() {+ if !s.indexMu.TryLock() {+ slog.Debug("autoindex.skip", "reason", "index_in_progress")+ return+ }+ defer s.indexMu.Unlock()++ s.indexStartedAt.Store(time.Now())+ if !hasDB {+ s.indexStatus.Store("indexing")+ }++ st, err := s.router.ForProject(s.sessionProject)+ if err != nil {+ slog.Warn("autoindex.store.err", "err", err)+ return+ }+ p := pipeline.New(st, s.sessionRoot)+ if err := p.Run(); err != nil {+ slog.Warn("autoindex.err", "err", err)+ return+ }+ s.indexStatus.Store("ready")+ slog.Info("autoindex.done", "project", s.sessionProject)+ }()+}++// --- Store routing ---++// resolveStore returns the Store for the given project, or the session project if empty.+func (s *Server) resolveStore(project string) (*store.Store, error) {+ if project == "*" || project == "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")+ }+ if project == "" {+ project = s.sessionProject+ }+ if project == "" {+ return nil, fmt.Errorf("no project specified and no session project detected; pass project parameter")+ }+ if !s.router.HasProject(project) {+ return nil, fmt.Errorf("project %q not found; use list_projects to see available projects", project)+ }+ return s.router.ForProject(project)+}++// resolveProjectName returns the effective project name for routing.+func (s *Server) resolveProjectName(project string) string {+ if project == "" {+ return s.sessionProject+ }+ return project+}++// addIndexStatus adds the index_status field to response data if indexing is in progress.+func (s *Server) addIndexStatus(data map[string]any) {+ status, _ := s.indexStatus.Load().(string)+ if status == "indexing" {+ data["index_status"] = "indexing"+ }+}++// addUpdateNotice injects update_available into the first tool response, then clears itself.+func (s *Server) addUpdateNotice(data map[string]any) {+ if notice, ok := s.updateNotice.Load().(string); ok && notice != "" {+ data["update_available"] = notice+ s.updateNotice.Store("")+ }+}++// checkForUpdate fetches the latest GitHub release and stores a notice if newer.+func (s *Server) checkForUpdate() {+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()++ req, err := http.NewRequestWithContext(ctx, "GET", releaseURL, nil)+ if err != nil {+ return+ }+ req.Header.Set("Accept", "application/vnd.github+json")++ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ return+ }+ defer resp.Body.Close()++ if resp.StatusCode != 200 {+ return+ }++ body, err := io.ReadAll(io.LimitReader(resp.Body, 4096))+ if err != nil {+ return+ }++ var release struct {+ TagName string `json:"tag_name"`+ }+ if err := json.Unmarshal(body, &release); err != nil {+ return+ }++ latest := strings.TrimPrefix(release.TagName, "v")+ if latest == "" || latest == Version {+ return+ }+ if compareVersions(latest, Version) > 0 {+ s.updateNotice.Store(fmt.Sprintf(+ "v%s → v%s available. Update: go install github.com/DeusData/codebase-memory-mcp/cmd/codebase-memory-mcp@v%s",+ Version, latest, latest))+ }+}++// compareVersions compares two semver strings (e.g. "0.2.1" vs "0.2.0").+// Returns >0 if a > b, <0 if a < b, 0 if equal.+func compareVersions(a, b string) int {+ aParts := strings.Split(a, ".")+ bParts := strings.Split(b, ".")+ for i := 0; i < len(aParts) && i < len(bParts); i++ {+ ai, _ := strconv.Atoi(aParts[i])+ bi, _ := strconv.Atoi(bParts[i])+ if ai != bi {+ return ai - bi+ }+ }+ return len(aParts) - len(bParts)+}++// --- Tool registration ---+func (s *Server) addTool(tool *mcp.Tool, handler mcp.ToolHandler) {s.mcp.AddTool(tool, handler)s.handlers[tool.Name] = handler@@ -116,13 +375,13 @@ func (s *Server) registerGraphTools() {func (s *Server) registerIndexAndTraceTool() {s.addTool(&mcp.Tool{Name: "index_repository",- Description: "Index a repository into the code graph. Parses source files, extracts functions/classes/modules, resolves call relationships (CALLS), read references (USAGE), interface implementations (IMPLEMENTS + OVERRIDE), HTTP/async cross-service links, and git history change coupling (FILE_CHANGES_WITH). Supports incremental reindex via content hashing. Auto-sync keeps the graph fresh after initial indexing.",+ Description: "Index a repository into the code graph. Parses source files, extracts functions/classes/modules, resolves call relationships (CALLS), read references (USAGE), interface implementations (IMPLEMENTS + OVERRIDE), HTTP/async cross-service links, and git history change coupling (FILE_CHANGES_WITH). Supports incremental reindex via content hashing. Auto-sync keeps the graph fresh after initial indexing. If repo_path is omitted, uses the auto-detected session project root.",InputSchema: json.RawMessage(`{"type": "object","properties": {"repo_path": {"type": "string",- "description": "Absolute path to the repository to index. If omitted, uses the configured project root."+ "description": "Absolute path to the repository to index. If omitted, uses the auto-detected session project root."}}}`),@@ -130,7 +389,7 @@ func (s *Server) registerIndexAndTraceTool() {s.addTool(&mcp.Tool{Name: "trace_call_path",- Description: "Trace call paths from/to a function. Requires EXACT function name — if unsure, call search_graph(name_pattern=...) first to discover the correct name. Returns hop-by-hop callees/callers with edge types (CALLS, HTTP_CALLS, ASYNC_CALLS, USAGE, OVERRIDE). USAGE edges indicate read references (callbacks, variable assignments) rather than invocations. OVERRIDE edges link struct methods to the interface methods they implement. Use depth=1 first, increase only if needed. IMPORTANT: Use direction='both' for full cross-service context — HTTP_CALLS edges from other services appear as inbound edges on backend functions, so direction='outbound' alone misses cross-service callers. For async dispatch (Cloud Tasks, Pub/Sub), find dispatch functions via search_graph(name_pattern='.*CreateTask.*') then trace via CALLS edges. If the function is not found, use search_graph with a name_pattern regex to find similar names before retrying.",+ Description: "Trace the call path of a function (who calls it, what it calls). Requires exact function name — use search_graph first to find the exact name. Follow up with get_code_snippet to read the actual source code. Returns hop-by-hop callees/callers with edge types (CALLS, HTTP_CALLS, ASYNC_CALLS, USAGE, OVERRIDE). If the function is not found, returns suggestions of similar names — use the qualified_name from suggestions in a retry. Use depth=1 first, increase only if needed. Use direction='both' for full cross-service context — HTTP_CALLS edges from other services appear as inbound edges, so direction='outbound' alone misses cross-service callers. Best practice: search_graph(name_pattern='.*Order.*') → trace_call_path(function_name='processOrder') → get_code_snippet(qualified_name='...')",InputSchema: json.RawMessage(`{"type": "object","properties": {@@ -146,6 +405,10 @@ func (s *Server) registerIndexAndTraceTool() {"type": "string","description": "Traversal direction: 'outbound' (what it calls), 'inbound' (what calls it), or 'both'","enum": ["outbound", "inbound", "both"]+ },+ "project": {+ "type": "string",+ "description": "Project to trace in. Defaults to session project."}},"required": ["function_name"]@@ -157,7 +420,15 @@ func (s *Server) registerSchemaAndSnippetTools() {s.addTool(&mcp.Tool{Name: "get_graph_schema",Description: "Return the schema of the indexed code graph: node label counts, edge type counts, relationship patterns (e.g. Function-CALLS->Function), and sample function/class names. Use to understand what's in the graph before querying.",- InputSchema: json.RawMessage(`{"type": "object"}`),+ InputSchema: json.RawMessage(`{+ "type": "object",+ "properties": {+ "project": {+ "type": "string",+ "description": "Project to get schema for. Defaults to session project."+ }+ }+ }`),}, s.handleGetGraphSchema)s.addTool(&mcp.Tool{@@ -169,6 +440,10 @@ func (s *Server) registerSchemaAndSnippetTools() {"qualified_name": {"type": "string","description": "Fully qualified name of the node (e.g. 'myproject.cmd.server.main.HandleRequest')"+ },+ "project": {+ "type": "string",+ "description": "Project to search in. Defaults to session project."}},"required": ["qualified_name"]@@ -179,13 +454,13 @@ func (s *Server) registerSchemaAndSnippetTools() {func (s *Server) registerSearchTools() {s.addTool(&mcp.Tool{Name: "search_graph",- Description: "Search the code graph for nodes. Returns 10 results per page (use offset to paginate, has_more indicates more pages). For dead code: use relationship='CALLS', direction='inbound', max_degree=0, exclude_entry_points=true. For fan-out: use relationship='CALLS', direction='outbound', min_degree=N. Route nodes: properties.handler contains the actual handler function name. Prefer this over query_graph for counting — no row cap. IMPORTANT: The 'relationship' filter counts how many edges of that type each node has (degree filtering) — it does NOT return the actual edges. To list cross-service HTTP_CALLS or ASYNC_CALLS edges with their properties (url_path, confidence), use query_graph with Cypher instead: MATCH (a)-[r:HTTP_CALLS]->(b) RETURN a.name, b.name, r.url_path, r.confidence. Relationship types: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, DEFINES, DEFINES_METHOD, HANDLES, CONTAINS_FILE, CONTAINS_FOLDER, CONTAINS_PACKAGE, IMPLEMENTS, OVERRIDE, USAGE, FILE_CHANGES_WITH.",+ Description: "Search the code knowledge graph for functions, classes, modules, routes, and other code elements. Returns nodes matching the criteria with their connectivity (in/out degree). Results are sorted by relevance by default (exact match first, prefix match second, then by connectivity). Community nodes are excluded by default. Pass exclude_labels: [] to include them. Best practice: Chain with trace_call_path and get_code_snippet for complete answers. Example workflow: search_graph(name_pattern='.*Order.*') → trace_call_path(function_name='processOrder') → get_code_snippet(qualified_name='...'). Returns 10 results per page (use offset to paginate, has_more indicates more pages). For dead code: use relationship='CALLS', direction='inbound', max_degree=0, exclude_entry_points=true. For fan-out: use relationship='CALLS', direction='outbound', min_degree=N. Route nodes: properties.handler contains the actual handler function name. Prefer this over query_graph for counting — no row cap. IMPORTANT: The 'relationship' filter counts how many edges of that type each node has (degree filtering) — it does NOT return the actual edges. To list cross-service HTTP_CALLS or ASYNC_CALLS edges with their properties, use query_graph with Cypher instead. Relationship types: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, DEFINES, DEFINES_METHOD, HANDLES, CONTAINS_FILE, CONTAINS_FOLDER, CONTAINS_PACKAGE, IMPLEMENTS, OVERRIDE, USAGE, FILE_CHANGES_WITH.",InputSchema: json.RawMessage(`{"type": "object","properties": {"project": {"type": "string",- "description": "Filter by project name. If omitted, searches all indexed projects."+ "description": "Project to search in. Defaults to session project."},"label": {"type": "string",@@ -235,7 +510,12 @@ func (s *Server) registerSearchTools() {"exclude_labels": {"type": "array","items": {"type": "string"},- "description": "Labels to exclude from results (e.g. ['Route'] to filter out route noise when searching by name_pattern)"+ "description": "Labels to exclude from results. Community nodes are excluded by default — pass [] to include them."+ },+ "sort_by": {+ "type": "string",+ "enum": ["relevance", "name", "degree"],+ "description": "Sort order. Default: relevance (exact match first, prefix match second, then by connectivity)"}}}`),@@ -266,6 +546,10 @@ func (s *Server) registerSearchTools() {"offset": {"type": "integer","description": "Skip N matches for pagination (default: 0). Check has_more in response."+ },+ "project": {+ "type": "string",+ "description": "Project to search in. Defaults to session project."}},"required": ["pattern"]@@ -283,6 +567,10 @@ func (s *Server) registerQueryTool() {"query": {"type": "string","description": "Cypher query, e.g. MATCH (f:Function)-[:CALLS]->(g:Function) WHERE f.name = 'main' RETURN g.name, g.qualified_name LIMIT 20"+ },+ "project": {+ "type": "string",+ "description": "Project to query. Defaults to session project."}},"required": ["query"]@@ -292,7 +580,6 @@ func (s *Server) registerQueryTool() {// registerFileTools registers tools for file and directory operations.func (s *Server) registerFileTools() {- // 8. read_files.addTool(&mcp.Tool{Name: "read_file",Description: "Read any file from the indexed project. Supports line range selection for large files. Use for reading config files (Dockerfile, go.mod, requirements.txt), source code, or any text file.",@@ -316,7 +603,6 @@ func (s *Server) registerFileTools() {}`),}, s.handleReadFile)- // 9. list_directorys.addTool(&mcp.Tool{Name: "list_directory",Description: "List files and subdirectories in a directory. Supports glob patterns for filtering. Use for exploring project structure.",@@ -330,6 +616,10 @@ func (s *Server) registerFileTools() {"pattern": {"type": "string","description": "Glob pattern to filter entries (e.g. '*.go', '*.py')"+ },+ "project": {+ "type": "string",+ "description": "Project name to resolve root from. Defaults to session project."}}}`),@@ -338,17 +628,15 @@ func (s *Server) registerFileTools() {// registerProjectTools registers tools for project management.func (s *Server) registerProjectTools() {- // 6. list_projectss.addTool(&mcp.Tool{Name: "list_projects",Description: "List all indexed projects with their indexed_at timestamp, root path, and node/edge counts.",InputSchema: json.RawMessage(`{"type": "object"}`),}, s.handleListProjects)- // 7. delete_projects.addTool(&mcp.Tool{Name: "delete_project",- Description: "Delete an indexed project and all its graph data (nodes, edges, file hashes). This action is irreversible.",+ Description: "Delete an indexed project and all its graph data (nodes, edges, file hashes). Removes the project's .db file. This action is irreversible.",InputSchema: json.RawMessage(`{"type": "object","properties": {@@ -360,8 +648,24 @@ func (s *Server) registerProjectTools() {"required": ["project_name"]}`),}, s.handleDeleteProject)++ s.addTool(&mcp.Tool{+ Name: "index_status",+ Description: "Check the indexing status of a project. Returns whether the project is indexed, currently indexing, or not found. Shows last indexed timestamp, node/edge counts, and whether the index is initial or incremental. Use this to check if the graph is ready for queries.",+ InputSchema: json.RawMessage(`{+ "type": "object",+ "properties": {+ "project": {+ "type": "string",+ "description": "Project name to check. Defaults to the auto-detected session project."+ }+ }+ }`),+ }, s.handleIndexStatus)}+// --- Helpers ---+// jsonResult marshals data to JSON and returns as tool result.func jsonResult(data any) *mcp.CallToolResult {b, err := json.MarshalIndent(data, "", " ")@@ -403,11 +707,11 @@ func getStringArg(args map[string]any, key string) string {if !ok {return ""}- s, ok := v.(string)+ str, ok := v.(string)if !ok {return ""}- return s+ return str}// getIntArg extracts an integer argument with a default value.@@ -436,14 +740,30 @@ func getBoolArg(args map[string]any, key string) bool {return b}-// findNodeAcrossProjects searches all projects for a node by simple name.-func (s *Server) findNodeAcrossProjects(name string) (*store.Node, string, error) {- projects, err := s.store.ListProjects()+// findNodeAcrossProjects searches for a node by simple name in the specified project.+// Falls back to the session project if no filter is given.+func (s *Server) findNodeAcrossProjects(name 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, "", fmt.Errorf("list projects: %w", err)+ return nil, "", err}+ projects, _ := st.ListProjects()for _, p := range projects {- nodes, findErr := s.store.FindNodesByName(p.Name, name)+ nodes, findErr := st.FindNodesByName(p.Name, name)if findErr != nil {continue}@@ -454,14 +774,30 @@ func (s *Server) findNodeAcrossProjects(name string) (*store.Node, string, errorreturn nil, "", fmt.Errorf("node not found: %s", name)}-// findNodeByQNAcrossProjects searches all projects for a node by qualified name.-func (s *Server) findNodeByQNAcrossProjects(qn string) (*store.Node, string, error) {- projects, err := s.store.ListProjects()+// 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, "", fmt.Errorf("list projects: %w", err)+ return nil, "", err}+ projects, _ := st.ListProjects()for _, p := range projects {- node, findErr := s.store.FindNodeByQN(p.Name, qn)+ node, findErr := st.FindNodeByQN(p.Name, qn)if findErr != nil {continue}diff --git a/internal/tools/trace.go b/internal/tools/trace.goindex c2684b3d1..b7cc7bbf3 100644--- a/internal/tools/trace.go+++ b/internal/tools/trace.go@@ -3,6 +3,8 @@ package toolsimport ("context""fmt"+ "regexp"+ "strings""github.com/DeusData/codebase-memory-mcp/internal/store""github.com/modelcontextprotocol/go-sdk/mcp"@@ -32,38 +34,65 @@ func (s *Server) handleTraceCallPath(_ context.Context, req *mcp.CallToolRequestdirection = "outbound"}- // Find the function node across all projects- rootNode, project, _ := s.findNodeAcrossProjects(funcName)+ project := getStringArg(args, "project")+ effectiveProject := s.resolveProjectName(project)++ // Find the function node+ rootNode, foundProject, findErr := s.findNodeAcrossProjects(funcName, effectiveProject)+ if findErr != nil && !strings.HasPrefix(findErr.Error(), "node not found") {+ return errResult(findErr.Error()), nil+ }if rootNode == nil {+ // Fuzzy fallback: search for similar names and return structured suggestions+ suggestions := s.findSimilarNodes(funcName, effectiveProject, 5)+ if len(suggestions) > 0 {+ suggList := make([]map[string]string, len(suggestions))+ for i, n := range suggestions {+ suggList[i] = map[string]string{+ "name": n.Name,+ "qualified_name": n.QualifiedName,+ "label": n.Label,+ }+ }+ return jsonResult(map[string]any{+ "error": fmt.Sprintf("function not found: %s", funcName),+ "suggestions": suggList,+ }), nil+ }return errResult(fmt.Sprintf("function not found: %s", funcName)), nil}+ // Get the store for the found project+ st, err := s.router.ForProject(foundProject)+ if err != nil {+ return errResult(fmt.Sprintf("store: %v", err)), nil+ }+edgeTypes := []string{"CALLS", "HTTP_CALLS", "ASYNC_CALLS"}// Build root inforoot := buildNodeInfo(rootNode)- // Get module info (constants) by finding the module that defines this function- moduleInfo := s.getModuleInfo(rootNode, project)+ // Get module info+ moduleInfo := s.getModuleInfo(st, rootNode, foundProject)// Run BFSvar allVisited []*store.NodeHopvar allEdges []store.EdgeInfoif direction == "both" {- // Run outbound + inbound separately, merge- outResult, outErr := s.store.BFS(rootNode.ID, "outbound", edgeTypes, depth, 200)+ outResult, outErr := st.BFS(rootNode.ID, "outbound", edgeTypes, depth, 200)if outErr == nil {allVisited = append(allVisited, outResult.Visited...)allEdges = append(allEdges, outResult.Edges...)}- inResult, inErr := s.store.BFS(rootNode.ID, "inbound", edgeTypes, depth, 200)+ inResult, inErr := st.BFS(rootNode.ID, "inbound", edgeTypes, depth, 200)if inErr == nil {allVisited = append(allVisited, inResult.Visited...)allEdges = append(allEdges, inResult.Edges...)}} else {- result, bfsErr := s.store.BFS(rootNode.ID, direction, edgeTypes, depth, 200)+ result, bfsErr := st.BFS(rootNode.ID, direction, edgeTypes, depth, 200)if bfsErr != nil {return errResult(fmt.Sprintf("bfs err: %v", bfsErr)), nil}@@ -78,20 +107,24 @@ func (s *Server) handleTraceCallPath(_ context.Context, req *mcp.CallToolRequestedges := buildEdgeList(allEdges)// Get indexed_at from project- proj, _ := s.store.GetProject(project)+ proj, _ := st.GetProject(foundProject)indexedAt := ""if proj != nil {indexedAt = proj.IndexedAt}- return jsonResult(map[string]any{+ responseData := map[string]any{"root": root,"module": moduleInfo,"hops": hops,"edges": edges,"indexed_at": indexedAt,"total_results": len(allVisited),- }), nil+ }+ s.addIndexStatus(responseData)+ s.addUpdateNotice(responseData)++ return jsonResult(responseData), nil}func buildNodeInfo(n *store.Node) map[string]any {@@ -112,13 +145,12 @@ func buildNodeInfo(n *store.Node) map[string]any {return info}-func (s *Server) getModuleInfo(funcNode *store.Node, project string) map[string]any {+func (s *Server) getModuleInfo(st *store.Store, funcNode *store.Node, project string) map[string]any {if funcNode.FilePath == "" {return map[string]any{}}- // Find module nodes in the same file- modules, err := s.store.FindNodesByLabel(project, "Module")+ modules, err := st.FindNodesByLabel(project, "Module")if err != nil {return map[string]any{}}@@ -163,6 +195,44 @@ func buildHops(visited []*store.NodeHop) []hopEntry {return hops}+// findSimilarNodes searches for nodes whose name contains the input string (case-insensitive).+func (s *Server) findSimilarNodes(name, project string, limit int) []*store.Node {+ effectiveProject := s.resolveProjectName(project)+ if effectiveProject == "" {+ return nil+ }+ if !s.router.HasProject(effectiveProject) {+ return nil+ }+ st, err := s.router.ForProject(effectiveProject)+ if err != nil {+ return nil+ }+ // Get actual project name from DB+ projName := effectiveProject+ projects, _ := st.ListProjects()+ if len(projects) > 0 {+ projName = projects[0].Name+ }+ params := &store.SearchParams{+ Project: projName,+ NamePattern: "(?i)" + regexp.QuoteMeta(name),+ Limit: limit,+ MinDegree: -1,+ MaxDegree: -1,+ ExcludeLabels: []string{"Community"},+ }+ out, searchErr := st.Search(params)+ if searchErr != nil {+ return nil+ }+ nodes := make([]*store.Node, len(out.Results))+ for i, r := range out.Results {+ nodes[i] = r.Node+ }+ return nodes+}+func buildEdgeList(edges []store.EdgeInfo) []map[string]any {result := make([]map[string]any, 0, len(edges))for _, e := range edges {diff --git a/internal/tools/traces.go b/internal/tools/traces.goindex f427ba8ca..d48936ee1 100644--- a/internal/tools/traces.go+++ b/internal/tools/traces.go@@ -42,7 +42,12 @@ func (s *Server) handleIngestTraces(_ context.Context, req *mcp.CallToolRequest)return errResult("project and file_path are required"), nil}- result, err := traces.Ingest(s.store, project, filePath)+ st, err := s.resolveStore(project)+ if err != nil {+ return errResult("store: " + err.Error()), nil //nolint:nilerr // WHY: MCP handler contract returns tool errors in result, Go error is always nil+ }++ result, err := traces.Ingest(st, project, filePath)if err != nil {return errResult(err.Error()), nil}diff --git a/internal/tools/update_test.go b/internal/tools/update_test.gonew file mode 100644index 000000000..16115e8c1--- /dev/null+++ b/internal/tools/update_test.go@@ -0,0 +1,154 @@+package tools++import (+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestCompareVersions(t *testing.T) {+ tests := []struct {+ a, b string+ want int // >0, 0, or <0+ }{+ {"0.2.1", "0.2.0", 1},+ {"0.2.0", "0.2.0", 0},+ {"0.1.9", "0.2.0", -1},+ {"0.10.0", "0.2.0", 1}, // numeric, not string comparison+ {"1.0.0", "0.99.99", 1},+ {"0.0.1", "0.0.2", -1},+ }+ for _, tt := range tests {+ t.Run(fmt.Sprintf("%s_vs_%s", tt.a, tt.b), func(t *testing.T) {+ got := compareVersions(tt.a, tt.b)+ switch {+ case tt.want > 0 && got <= 0:+ t.Fatalf("compareVersions(%q, %q) = %d, want > 0", tt.a, tt.b, got)+ case tt.want < 0 && got >= 0:+ t.Fatalf("compareVersions(%q, %q) = %d, want < 0", tt.a, tt.b, got)+ case tt.want == 0 && got != 0:+ t.Fatalf("compareVersions(%q, %q) = %d, want 0", tt.a, tt.b, got)+ }+ })+ }+}++func TestCheckForUpdate_NewerAvailable(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ fmt.Fprint(w, `{"tag_name": "v99.0.0"}`)+ }))+ defer ts.Close()++ old := releaseURL+ releaseURL = ts.URL+ defer func() { releaseURL = old }()++ srv := &Server{}+ srv.checkForUpdate()++ notice, _ := srv.updateNotice.Load().(string)+ if notice == "" {+ t.Fatal("expected update notice to be set")+ }+ if !strings.Contains(notice, "v99.0.0") {+ t.Fatalf("notice should mention v99.0.0, got: %s", notice)+ }+ if !strings.Contains(notice, "go install") {+ t.Fatalf("notice should contain install command, got: %s", notice)+ }+}++func TestCheckForUpdate_AlreadyCurrent(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ fmt.Fprintf(w, `{"tag_name": "v%s"}`, Version)+ }))+ defer ts.Close()++ old := releaseURL+ releaseURL = ts.URL+ defer func() { releaseURL = old }()++ srv := &Server{}+ srv.checkForUpdate()++ notice, _ := srv.updateNotice.Load().(string)+ if notice != "" {+ t.Fatalf("expected empty notice for current version, got: %s", notice)+ }+}++func TestCheckForUpdate_OlderAvailable(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ fmt.Fprint(w, `{"tag_name": "v0.0.1"}`)+ }))+ defer ts.Close()++ old := releaseURL+ releaseURL = ts.URL+ defer func() { releaseURL = old }()++ srv := &Server{}+ srv.checkForUpdate()++ notice, _ := srv.updateNotice.Load().(string)+ if notice != "" {+ t.Fatalf("expected empty notice for older version, got: %s", notice)+ }+}++func TestCheckForUpdate_ServerError(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(500)+ }))+ defer ts.Close()++ old := releaseURL+ releaseURL = ts.URL+ defer func() { releaseURL = old }()++ srv := &Server{}+ srv.checkForUpdate() // should not panic++ notice, _ := srv.updateNotice.Load().(string)+ if notice != "" {+ t.Fatalf("expected empty notice on server error, got: %s", notice)+ }+}++func TestCheckForUpdate_MalformedJSON(t *testing.T) {+ ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ fmt.Fprint(w, `not json at all!!!`)+ }))+ defer ts.Close()++ old := releaseURL+ releaseURL = ts.URL+ defer func() { releaseURL = old }()++ srv := &Server{}+ srv.checkForUpdate() // should not panic++ notice, _ := srv.updateNotice.Load().(string)+ if notice != "" {+ t.Fatalf("expected empty notice on malformed JSON, got: %s", notice)+ }+}++func TestAddUpdateNotice_ShowsOnce(t *testing.T) {+ srv := &Server{}+ srv.updateNotice.Store("v0.2.0 → v0.3.0 available")++ first := map[string]any{}+ srv.addUpdateNotice(first)+ if _, ok := first["update_available"]; !ok {+ t.Fatal("expected update_available in first map")+ }++ second := map[string]any{}+ srv.addUpdateNotice(second)+ if _, ok := second["update_available"]; ok {+ t.Fatal("expected update_available to be absent in second map (show-once)")+ }+}diff --git a/internal/watcher/watcher.go b/internal/watcher/watcher.goindex 7fcec8fe7..c6dda5046 100644--- a/internal/watcher/watcher.go+++ b/internal/watcher/watcher.go@@ -31,15 +31,15 @@ type IndexFunc func(projectName, rootPath string) error// Watcher polls indexed projects for file changes and triggers re-indexing.type Watcher struct {- store *store.Store+ router *store.StoreRouterindexFn IndexFuncprojects map[string]*projectState}// New creates a Watcher. indexFn is called when file changes are detected.-func New(s *store.Store, indexFn IndexFunc) *Watcher {+func New(r *store.StoreRouter, indexFn IndexFunc) *Watcher {return &Watcher{- store: s,+ router: r,indexFn: indexFn,projects: make(map[string]*projectState),}@@ -63,19 +63,30 @@ func (w *Watcher) Run(ctx context.Context) {// pollAll lists all indexed projects and polls each that is due.func (w *Watcher) pollAll() {- projects, err := w.store.ListProjects()+ projectInfos, err := w.router.ListProjects()if err != nil {slog.Warn("watcher.list_projects", "err", err)return}now := time.Now()- for _, proj := range projects {- state, exists := w.projects[proj.Name]+ for _, info := range projectInfos {+ // Get the store for this project (never cache directly)+ st, stErr := w.router.ForProject(info.Name)+ if stErr != nil {+ continue+ }++ // Get the project metadata from the store+ proj, projErr := st.GetProject(info.Name)+ if projErr != nil || proj == nil {+ continue+ }++ state, exists := w.projects[info.Name]if !exists {- // First time seeing this project — capture baselinestate = &projectState{}- w.projects[proj.Name] = state+ w.projects[info.Name] = state}if exists && now.Before(state.nextPoll) {diff --git a/internal/watcher/watcher_test.go b/internal/watcher/watcher_test.goindex 0151443de..a74c7595b 100644--- a/internal/watcher/watcher_test.go+++ b/internal/watcher/watcher_test.go@@ -11,6 +11,26 @@ import ("github.com/DeusData/codebase-memory-mcp/internal/store")+// newTestRouter creates a StoreRouter backed by a temp directory with a project registered.+func newTestRouter(t *testing.T, projectName, rootPath string) *store.StoreRouter {+ t.Helper()+ dbDir := t.TempDir()+ r, err := store.NewRouterWithDir(dbDir)+ if err != nil {+ t.Fatal(err)+ }+ if projectName != "" {+ st, err := r.ForProject(projectName)+ if err != nil {+ t.Fatal(err)+ }+ if err := st.UpsertProject(projectName, rootPath); err != nil {+ t.Fatal(err)+ }+ }+ return r+}+func TestSnapshotsEqual(t *testing.T) {now := time.Now()@@ -149,22 +169,14 @@ func TestCaptureSnapshotDetectsChanges(t *testing.T) {}func TestWatcherTriggersOnChange(t *testing.T) {- s, err := store.OpenMemory()- if err != nil {- t.Fatal(err)- }- defer s.Close()-tmpDir := t.TempDir()goFile := filepath.Join(tmpDir, "main.go")if err := os.WriteFile(goFile, []byte("package main\n"), 0o600); err != nil {t.Fatal(err)}- // Register the project so ListProjects returns it- if err := s.UpsertProject(filepath.Base(tmpDir), tmpDir); err != nil {- t.Fatal(err)- }+ r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)+ defer r.CloseAll()var indexCount atomic.Int32indexFn := func(_, _ string) error {@@ -172,7 +184,7 @@ func TestWatcherTriggersOnChange(t *testing.T) {return nil}- w := New(s, indexFn)+ w := New(r, indexFn)// First poll — baseline capture, no indexw.pollAll()@@ -191,8 +203,8 @@ func TestWatcherTriggersOnChange(t *testing.T) {}// Modify the file- now := time.Now().Add(time.Second)- if err := os.Chtimes(goFile, now, now); err != nil {+ futureTime := time.Now().Add(time.Second)+ if err := os.Chtimes(goFile, futureTime, futureTime); err != nil {t.Fatal(err)}@@ -207,13 +219,14 @@ func TestWatcherTriggersOnChange(t *testing.T) {}func TestWatcherCancellation(t *testing.T) {- s, err := store.OpenMemory()+ dbDir := t.TempDir()+ r, err := store.NewRouterWithDir(dbDir)if err != nil {t.Fatal(err)}- defer s.Close()+ defer r.CloseAll()- w := New(s, func(_, _ string) error { return nil })+ w := New(r, func(_, _ string) error { return nil })ctx, cancel := context.WithCancel(context.Background())@@ -234,19 +247,11 @@ func TestWatcherCancellation(t *testing.T) {}func TestWatcherSkipsMissingRoot(t *testing.T) {- s, err := store.OpenMemory()- if err != nil {- t.Fatal(err)- }- defer s.Close()-- // Register a project with a non-existent path- if err := s.UpsertProject("ghost", "/nonexistent/path"); err != nil {- t.Fatal(err)- }+ r := newTestRouter(t, "ghost", "/nonexistent/path")+ defer r.CloseAll()var indexCount atomic.Int32- w := New(s, func(_, _ string) error {+ w := New(r, func(_, _ string) error {indexCount.Add(1)return nil})@@ -258,24 +263,17 @@ func TestWatcherSkipsMissingRoot(t *testing.T) {}func TestWatcherNewFileTriggersIndex(t *testing.T) {- s, err := store.OpenMemory()- if err != nil {- t.Fatal(err)- }- defer s.Close()-tmpDir := t.TempDir()goFile := filepath.Join(tmpDir, "main.go")if err := os.WriteFile(goFile, []byte("package main\n"), 0o600); err != nil {t.Fatal(err)}- if err := s.UpsertProject(filepath.Base(tmpDir), tmpDir); err != nil {- t.Fatal(err)- }+ r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)+ defer r.CloseAll()var indexCount atomic.Int32- w := New(s, func(_, _ string) error {+ w := New(r, func(_, _ string) error {indexCount.Add(1)return nil})