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
Fix all golangci-lint issues across the codebase
Martin Vogela208b34c8bf3
diff --git a/internal/cypher/executor.go b/internal/cypher/executor.goindex f859a932d..446f82bcb 100644--- a/internal/cypher/executor.go+++ b/internal/cypher/executor.go@@ -12,13 +12,40 @@ import ("github.com/DeusData/codebase-memory-mcp/internal/store")-const maxResultRows = 200+const defaultMaxRows = 200+const absoluteMaxRows = 10000// Executor runs Cypher execution plans against a store.type Executor struct {- Store *store.Store- regexCache map[string]*regexp.Regexp- ctx context.Context // set by Execute, used for DB queries+ Store *store.Store+ MaxRows int // 0 means defaultMaxRows+ regexCache map[string]*regexp.Regexp+ ctx context.Context // set by Execute, used for DB queries+ expandLimit int // binding cap for current query (set per-execution)+}++func (e *Executor) maxRows() int {+ if e.MaxRows <= 0 {+ return defaultMaxRows+ }+ if e.MaxRows > absoluteMaxRows {+ return absoluteMaxRows+ }+ return e.MaxRows+}++// bindingCap returns the maximum number of bindings to keep during expansion.+// For aggregation queries (COUNT), we need all bindings for correct counts,+// so the cap is much higher. For non-aggregation queries, cap at maxRows*2.+func (e *Executor) bindingCap(ret *ReturnClause) int {+ if ret != nil {+ for _, item := range ret.Items {+ if item.Func == "COUNT" {+ return absoluteMaxRows * 10 // 100k cap for aggregation+ }+ }+ }+ return e.maxRows() * 2}// Result holds the tabular output of a query.@@ -67,6 +94,8 @@ func (e *Executor) executePlan(plan *Plan) (*Result, error) {return nil, fmt.Errorf("list projects: %w", err)}+ bindingCap := e.bindingCap(plan.ReturnSpec)+ e.expandLimit = bindingCapvar allBindings []bindingfor _, proj := range projects {bindings, err := e.executeStepsForProject(proj.Name, plan.Steps)@@ -74,8 +103,8 @@ func (e *Executor) executePlan(plan *Plan) (*Result, error) {continue // skip projects that error}allBindings = append(allBindings, bindings...)- if len(allBindings) > maxResultRows*2 {- allBindings = allBindings[:maxResultRows*2]+ if len(allBindings) > bindingCap {+ allBindings = allBindings[:bindingCap]break}}@@ -128,7 +157,7 @@ func (e *Executor) tryAggregateSQL(plan *Plan) (*Result, bool) {}// LIMIT- allRows = applyLimit(allRows, plan.ReturnSpec.Limit)+ allRows = applyLimit(allRows, plan.ReturnSpec.Limit, e.maxRows())return &Result{Columns: cols, Rows: allRows}, true}@@ -421,8 +450,12 @@ func (e *Executor) executeStepsForProject(project string, steps []PlanStep) ([]bisLastStep := i == len(steps)-1_, isExpand := step.(*ExpandRelationship)if isLastStep || isExpand {- if len(bindings) > maxResultRows*2 {- bindings = bindings[:maxResultRows*2]+ stepCap := e.expandLimit+ if stepCap <= 0 {+ stepCap = e.maxRows() * 2+ }+ if len(bindings) > stepCap {+ bindings = bindings[:stepCap]}}}@@ -503,7 +536,11 @@ func (e *Executor) execJoinScanExpand(project string, scan *ScanNodes, expand *ELIMIT ?`,srcCol, tgtCol, typeFilter, srcLabelClause, tgtLabelClause)- args = append(args, maxResultRows*2)+ sqlLimit := e.expandLimit+ if sqlLimit <= 0 {+ sqlLimit = e.maxRows() * 2+ }+ args = append(args, sqlLimit)rows, err := e.Store.DB().QueryContext(e.ctx, query, args...)if err != nil {@@ -674,8 +711,8 @@ func (e *Executor) execExpand(s *ExpandRelationship, bindings []binding) ([]bindreturn nil, err}result = append(result, expanded...)- if len(result) > maxResultRows*2 {- result = result[:maxResultRows*2]+ if len(result) > e.maxRows()*2 {+ result = result[:e.maxRows()*2]break}}@@ -709,7 +746,11 @@ func (e *Executor) expandFixedLengthBatch(s *ExpandRelationship, bindings []bindreturn nil, err}- return buildExpandedBindings(bindings, s, edgesByNode, nodeMap, direction), nil+ expandCap := e.expandLimit+ if expandCap <= 0 {+ expandCap = e.maxRows() * 2+ }+ return buildExpandedBindings(bindings, s, edgesByNode, nodeMap, direction, expandCap), nil}// collectSourceIDs extracts unique node IDs from bindings for the given variable.@@ -773,7 +814,7 @@ func collectTargetIDs(edgesByNode map[int64][]*store.Edge, direction string) []i}// 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 {+func buildExpandedBindings(bindings []binding, s *ExpandRelationship, edgesByNode map[int64][]*store.Edge, nodeMap map[int64]*store.Node, direction string, maxRows int) []binding {result := make([]binding, 0, len(bindings))for _, b := range bindings {fromNode, ok := b.nodes[s.FromVar]@@ -807,8 +848,8 @@ func buildExpandedBindings(bindings []binding, s *ExpandRelationship, edgesByNodresult = append(result, newB)}- if len(result) > maxResultRows*2 {- result = result[:maxResultRows*2]+ if len(result) > maxRows*2 {+ result = result[:maxRows*2]break}}@@ -831,7 +872,7 @@ func (e *Executor) expandVariableLength(b binding, fromNode *store.Node, s *ExpaedgeTypes = []string{"CALLS"} // default}- bfsResult, err := e.Store.BFS(fromNode.ID, direction, edgeTypes, maxDepth, maxResultRows)+ bfsResult, err := e.Store.BFS(fromNode.ID, direction, edgeTypes, maxDepth, e.maxRows())if err != nil {return nil, fmt.Errorf("bfs: %w", err)}@@ -1121,8 +1162,8 @@ func (e *Executor) defaultProjection(bindings []binding) (*Result, error) {rows = append(rows, row)}- if len(rows) > maxResultRows {- rows = rows[:maxResultRows]+ if len(rows) > e.maxRows() {+ rows = rows[:e.maxRows()]}return &Result{Columns: cols, Rows: rows}, nil@@ -1155,7 +1196,7 @@ func (e *Executor) simpleProjection(bindings []binding, ret *ReturnClause) (*Res}// LIMIT- rows = applyLimit(rows, ret.Limit)+ rows = applyLimit(rows, ret.Limit, e.maxRows())return &Result{Columns: cols, Rows: rows}, nil}@@ -1254,9 +1295,9 @@ func resolveOrderColumn(orderBy string, items []ReturnItem, cols []string) strin}// applyLimit enforces the LIMIT clause on result rows.-func applyLimit(rows []map[string]any, limit int) []map[string]any {- if limit <= 0 || limit > maxResultRows {- limit = maxResultRows+func applyLimit(rows []map[string]any, limit, maxRows int) []map[string]any {+ if limit <= 0 || limit > maxRows {+ limit = maxRows}if len(rows) > limit {return rows[:limit]@@ -1292,7 +1333,7 @@ func (e *Executor) aggregateResults(bindings []binding, ret *ReturnClause) (*Res}// LIMIT- rows = applyLimit(rows, ret.Limit)+ rows = applyLimit(rows, ret.Limit, e.maxRows())return &Result{Columns: cols, Rows: rows}, nil}diff --git a/internal/pipeline/go_dep_registry.go b/internal/pipeline/go_dep_registry.gonew file mode 100644index 000000000..ec06fa044--- /dev/null+++ b/internal/pipeline/go_dep_registry.go@@ -0,0 +1,356 @@+package pipeline++import (+ "go/ast"+ "go/parser"+ "go/token"+ "log/slog"+ "os"+ "path/filepath"+ "strings"+ "sync"++ "github.com/DeusData/codebase-memory-mcp/internal/cbm"+)++// goDepCache caches parsed third-party module definitions.+// Keyed by module@version (immutable in Go module cache).+var (+ goDepCacheMu sync.RWMutex+ goDepCache = make(map[string]map[string][]cbm.CrossFileDef) // module@version -> importPath -> defs+)++// goDepVersions maps Go import path prefix → module@version directory path.+// Built from go.mod + go.sum.+type goDepVersions struct {+ // modDirByPath maps module import path → absolute directory in module cache+ modDirByPath map[string]string+}++// buildGoDepVersions reads go.mod and locates each dependency in the module cache.+func buildGoDepVersions(repoPath string) *goDepVersions {+ data, err := os.ReadFile(filepath.Join(repoPath, "go.mod"))+ if err != nil {+ return nil+ }++ goPath := os.Getenv("GOPATH")+ if goPath == "" {+ home, _ := os.UserHomeDir()+ goPath = filepath.Join(home, "go")+ }+ modCacheBase := filepath.Join(goPath, "pkg", "mod")++ dv := &goDepVersions{+ modDirByPath: make(map[string]string),+ }++ // Parse go.mod for require directives+ inRequire := false+ for _, line := range strings.Split(string(data), "\n") {+ line = strings.TrimSpace(line)+ if line == "require (" {+ inRequire = true+ continue+ }+ if line == ")" {+ inRequire = false+ continue+ }+ if strings.HasPrefix(line, "require ") {+ // Single-line require+ line = strings.TrimPrefix(line, "require ")+ } else if !inRequire {+ continue+ }++ // Parse "module/path v1.2.3 // indirect"+ parts := strings.Fields(line)+ if len(parts) < 2 {+ continue+ }+ modPath := parts[0]+ version := parts[1]++ // Module cache uses escaped paths (uppercase letters → !lowercase)+ escaped := escapeModPath(modPath)+ modDir := filepath.Join(modCacheBase, escaped+"@"+version)++ if info, err := os.Stat(modDir); err == nil && info.IsDir() { //nolint:gosec // path from trusted go.mod + GOPATH+ dv.modDirByPath[modPath] = modDir+ }+ }++ return dv+}++// escapeModPath applies Go module cache path escaping.+// Uppercase letters are replaced with !lowercase.+func escapeModPath(path string) string {+ var b strings.Builder+ for _, c := range path {+ if c >= 'A' && c <= 'Z' {+ b.WriteByte('!')+ b.WriteRune(c + 32)+ } else {+ b.WriteRune(c)+ }+ }+ return b.String()+}++// resolveModDir returns the module cache directory for a Go import path.+// Handles subpackage paths by finding the longest matching module prefix.+func (dv *goDepVersions) resolveModDir(importPath string) (modPath, modDir, subPkg string) {+ if dv == nil {+ return "", "", ""+ }+ // Try exact match first, then progressively shorter prefixes+ path := importPath+ for path != "" {+ if dir, ok := dv.modDirByPath[path]; ok {+ sub := strings.TrimPrefix(importPath, path)+ sub = strings.TrimPrefix(sub, "/")+ return path, dir, sub+ }+ idx := strings.LastIndex(path, "/")+ if idx < 0 {+ break+ }+ path = path[:idx]+ }+ return "", "", ""+}++// parseThirdPartyPackage parses a third-party Go package directory and extracts definitions.+func parseThirdPartyPackage(modPath, modDir, subPkg string) []cbm.CrossFileDef {+ pkgDir := modDir+ if subPkg != "" {+ pkgDir = filepath.Join(modDir, subPkg)+ }++ // The import path for this specific package+ importPath := modPath+ if subPkg != "" {+ importPath = modPath + "/" + subPkg+ }++ // Check cache+ cacheKey := modDir // module@version dir is unique and immutable+ goDepCacheMu.RLock()+ if cached, ok := goDepCache[cacheKey]; ok {+ if defs, ok := cached[importPath]; ok {+ goDepCacheMu.RUnlock()+ return defs+ }+ }+ goDepCacheMu.RUnlock()++ // Parse Go files in the package directory+ fset := token.NewFileSet()+ pkgs, err := parser.ParseDir(fset, pkgDir, func(fi os.FileInfo) bool { //nolint:staticcheck // SA1019: go/packages is heavyweight; ParseDir suffices for extracting exported names from module cache+ name := fi.Name()+ // Skip test files and non-Go files+ return strings.HasSuffix(name, ".go") && !strings.HasSuffix(name, "_test.go")+ }, 0) // no comments needed+ if err != nil {+ return nil+ }++ var defs []cbm.CrossFileDef+ for _, pkg := range pkgs {+ for _, file := range pkg.Files {+ defs = append(defs, extractDefsFromAST(file, importPath)...)+ }+ }++ // Cache the result+ goDepCacheMu.Lock()+ if goDepCache[cacheKey] == nil {+ goDepCache[cacheKey] = make(map[string][]cbm.CrossFileDef)+ }+ goDepCache[cacheKey][importPath] = defs+ goDepCacheMu.Unlock()++ return defs+}++// extractDefsFromAST extracts exported function/method/type definitions from an AST file.+func extractDefsFromAST(file *ast.File, importPath string) []cbm.CrossFileDef {+ var defs []cbm.CrossFileDef++ for _, decl := range file.Decls {+ switch d := decl.(type) {+ case *ast.FuncDecl:+ if cd, ok := extractFuncDef(d, importPath); ok {+ defs = append(defs, cd)+ }+ case *ast.GenDecl:+ defs = append(defs, extractTypeDefs(d, importPath)...)+ }+ }++ return defs+}++// extractFuncDef extracts a single exported function/method definition from a FuncDecl.+func extractFuncDef(d *ast.FuncDecl, importPath string) (cbm.CrossFileDef, bool) {+ if !d.Name.IsExported() {+ return cbm.CrossFileDef{}, false+ }++ cd := cbm.CrossFileDef{+ ShortName: d.Name.Name,+ DefModuleQN: importPath,+ }++ // Return types+ if d.Type.Results != nil && len(d.Type.Results.List) > 0 {+ retTypes := make([]string, 0, len(d.Type.Results.List))+ for _, field := range d.Type.Results.List {+ retTypes = append(retTypes, typeExprToString(field.Type))+ }+ cd.ReturnTypes = strings.Join(retTypes, "|")+ }++ if d.Recv != nil && len(d.Recv.List) > 0 {+ cd.Label = "Method"+ recvType := typeExprToString(d.Recv.List[0].Type)+ recvType = strings.TrimPrefix(recvType, "*")+ cd.ReceiverType = importPath + "." + recvType+ cd.QualifiedName = importPath + "." + recvType + "." + d.Name.Name+ } else {+ cd.Label = "Function"+ cd.QualifiedName = importPath + "." + d.Name.Name+ }++ return cd, true+}++// extractTypeDefs extracts exported type definitions from a GenDecl.+func extractTypeDefs(d *ast.GenDecl, importPath string) []cbm.CrossFileDef {+ if d.Tok != token.TYPE {+ return nil+ }+ var defs []cbm.CrossFileDef+ for _, spec := range d.Specs {+ ts, ok := spec.(*ast.TypeSpec)+ if !ok || !ts.Name.IsExported() {+ continue+ }++ cd := cbm.CrossFileDef{+ QualifiedName: importPath + "." + ts.Name.Name,+ ShortName: ts.Name.Name,+ DefModuleQN: importPath,+ }++ switch t := ts.Type.(type) {+ case *ast.InterfaceType:+ cd.Label = "Interface"+ cd.IsInterface = true+ case *ast.StructType:+ cd.Label = "Type"+ cd.EmbeddedTypes = extractStructEmbeds(t, importPath)+ default:+ cd.Label = "Type"+ }++ defs = append(defs, cd)+ }+ return defs+}++// extractStructEmbeds extracts embedded type names from a struct type.+func extractStructEmbeds(st *ast.StructType, importPath string) string {+ if st.Fields == nil {+ return ""+ }+ var embeds []string+ for _, field := range st.Fields.List {+ if len(field.Names) == 0 {+ embed := typeExprToString(field.Type)+ embed = strings.TrimPrefix(embed, "*")+ embeds = append(embeds, importPath+"."+embed)+ }+ }+ if len(embeds) > 0 {+ return strings.Join(embeds, "|")+ }+ return ""+}++// typeExprToString converts an ast.Expr representing a type to its string form.+func typeExprToString(expr ast.Expr) string {+ switch t := expr.(type) {+ case *ast.Ident:+ return t.Name+ case *ast.StarExpr:+ return "*" + typeExprToString(t.X)+ case *ast.ArrayType:+ if t.Len == nil {+ return "[]" + typeExprToString(t.Elt)+ }+ return "[...]" + typeExprToString(t.Elt)+ case *ast.SelectorExpr:+ return typeExprToString(t.X) + "." + t.Sel.Name+ case *ast.MapType:+ return "map[" + typeExprToString(t.Key) + "]" + typeExprToString(t.Value)+ case *ast.ChanType:+ return "chan " + typeExprToString(t.Value)+ case *ast.InterfaceType:+ return "interface{}"+ case *ast.FuncType:+ return "func()"+ case *ast.Ellipsis:+ return "..." + typeExprToString(t.Elt)+ default:+ return "any"+ }+}++// integrateThirdPartyDeps extends buildGoLSPDefIndex to also parse third-party deps.+// Called during pipeline setup, populates the index with dep definitions.+func (idx *goLSPDefIndex) integrateThirdPartyDeps(repoPath string, importMaps map[string]map[string]string) {+ if idx == nil {+ return+ }++ dv := buildGoDepVersions(repoPath)+ if dv == nil || len(dv.modDirByPath) == 0 {+ return+ }++ // Collect all unique third-party import paths from all files+ needed := make(map[string]bool)+ for _, importMap := range importMaps {+ for _, goImportPath := range importMap {+ if _, exists := idx.byImportPath[goImportPath]; !exists {+ needed[goImportPath] = true+ }+ }+ }++ parsedCount := 0+ defCount := 0+ for importPath := range needed {+ modPath, modDir, subPkg := dv.resolveModDir(importPath)+ if modDir == "" {+ continue+ }++ defs := parseThirdPartyPackage(modPath, modDir, subPkg)+ if len(defs) > 0 {+ idx.byImportPath[importPath] = defs+ defCount += len(defs)+ parsedCount+++ }+ }++ if parsedCount > 0 {+ slog.Info("go_lsp.third_party.index",+ "packages", parsedCount,+ "defs", defCount,+ )+ }+}diff --git a/internal/pipeline/go_lsp_cross.go b/internal/pipeline/go_lsp_cross.gonew file mode 100644index 000000000..c6794b5f4--- /dev/null+++ b/internal/pipeline/go_lsp_cross.go@@ -0,0 +1,344 @@+package pipeline++import (+ "fmt"+ "go/ast"+ "go/parser"+ "go/token"+ "log/slog"+ "os"+ "path/filepath"+ "strings"++ "github.com/DeusData/codebase-memory-mcp/internal/cbm"+ "github.com/DeusData/codebase-memory-mcp/internal/fqn"+ "github.com/DeusData/codebase-memory-mcp/internal/lang"+)++// goLSPDefIndex indexes cross-file definitions by Go import path for LSP resolution.+type goLSPDefIndex struct {+ // byImportPath maps Go import path → []CrossFileDef+ byImportPath map[string][]cbm.CrossFileDef+ // goModulePath is the Go module path from go.mod (e.g., "github.com/DeusData/...")+ goModulePath string+}++// buildGoLSPDefIndex builds the cross-file definition index for Go LSP resolution.+// Called once before pass3 (passCalls). Scans all Go files in extractionCache.+func (p *Pipeline) buildGoLSPDefIndex() *goLSPDefIndex {+ goModPath := readGoModulePath(p.RepoPath)+ if goModPath == "" {+ return nil+ }++ idx := &goLSPDefIndex{+ byImportPath: make(map[string][]cbm.CrossFileDef),+ goModulePath: goModPath,+ }++ for relPath, ext := range p.extractionCache {+ if ext.Language != lang.Go {+ continue+ }+ if ext.Result == nil || len(ext.Result.Definitions) == 0 {+ continue+ }++ // Compute Go import path for this file's package+ dir := filepath.Dir(relPath)+ var importPath string+ if dir == "." || dir == "" {+ importPath = goModPath+ } else {+ importPath = goModPath + "/" + filepath.ToSlash(dir)+ }++ moduleQN := fqn.ModuleQN(p.ProjectName, relPath)+ defs := cbm.DefsToLSPDefs(ext.Result.Definitions, moduleQN)++ // Enrich struct types with field definitions and interfaces with method names from Go source+ if len(defs) > 0 {+ enrichStructFieldDefs(p.RepoPath, relPath, defs)+ enrichInterfaceMethodNames(p.RepoPath, relPath, defs)+ idx.byImportPath[importPath] = append(idx.byImportPath[importPath], defs...)+ }+ }++ totalDefs := 0+ for _, defs := range idx.byImportPath {+ totalDefs += len(defs)+ }+ if totalDefs > 0 {+ slog.Info("go_lsp.cross_file.index",+ "packages", len(idx.byImportPath),+ "defs", totalDefs,+ )+ }++ return idx+}++// collectCrossFileDefs returns cross-file definitions for all imported packages.+func (idx *goLSPDefIndex) collectCrossFileDefs(importMap map[string]string) []cbm.CrossFileDef {+ if idx == nil || len(importMap) == 0 {+ return nil+ }++ var result []cbm.CrossFileDef+ seen := make(map[string]bool)++ for _, goImportPath := range importMap {+ if seen[goImportPath] {+ continue+ }+ seen[goImportPath] = true++ // Check if this import path matches a project package+ if defs, ok := idx.byImportPath[goImportPath]; ok {+ // Rewrite QNs: the C resolver will look up "importPath.TypeName",+ // so cross-file defs need their QN prefixed with the Go import path.+ for i := range defs {+ cd := defs[i]+ cd.QualifiedName = requalifyForImport(defs[i].QualifiedName, defs[i].DefModuleQN, goImportPath)+ cd.DefModuleQN = goImportPath+ if cd.ReceiverType != "" {+ cd.ReceiverType = requalifyForImport(defs[i].ReceiverType, defs[i].DefModuleQN, goImportPath)+ }+ // Requalify embedded types+ if cd.EmbeddedTypes != "" {+ parts := strings.Split(cd.EmbeddedTypes, "|")+ for j, part := range parts {+ parts[j] = requalifyForImport(part, defs[i].DefModuleQN, goImportPath)+ }+ cd.EmbeddedTypes = strings.Join(parts, "|")+ }+ result = append(result, cd)+ }+ }+ }++ return result+}++// requalifyForImport replaces the module QN prefix in a qualified name with+// the Go import path prefix so the C resolver can match it via import map lookup.+// E.g., "proj.internal-store-store.go.Store" → "github.com/.../internal/store.Store"+func requalifyForImport(qn, moduleQN, goImportPath string) string {+ if moduleQN == "" || !strings.HasPrefix(qn, moduleQN) {+ return qn+ }+ suffix := qn[len(moduleQN):]+ return goImportPath + suffix+}++// enrichStructFieldDefs parses Go source to extract struct field name:type pairs.+// Populates FieldDefs on Type/Class CrossFileDef entries.+func enrichStructFieldDefs(repoPath, relPath string, defs []cbm.CrossFileDef) {+ // Collect struct type names that need field info+ structNames := make(map[string]int) // shortName -> index in defs+ for i := range defs {+ d := &defs[i]+ if (d.Label == "Type" || d.Label == "Class") && !d.IsInterface {+ structNames[d.ShortName] = i+ }+ }+ if len(structNames) == 0 {+ return+ }++ src, err := os.ReadFile(filepath.Join(repoPath, relPath))+ if err != nil {+ return+ }++ fset := token.NewFileSet()+ f, err := parser.ParseFile(fset, relPath, src, 0)+ if err != nil {+ return+ }++ for _, decl := range f.Decls {+ gd, ok := decl.(*ast.GenDecl)+ if !ok || gd.Tok != token.TYPE {+ continue+ }+ enrichStructFieldsFromGenDecl(gd, structNames, defs)+ }+}++// enrichStructFieldsFromGenDecl processes a single GenDecl to extract struct field definitions.+func enrichStructFieldsFromGenDecl(gd *ast.GenDecl, structNames map[string]int, defs []cbm.CrossFileDef) {+ for _, spec := range gd.Specs {+ ts, ok := spec.(*ast.TypeSpec)+ if !ok {+ continue+ }+ idx, found := structNames[ts.Name.Name]+ if !found {+ continue+ }+ st, ok := ts.Type.(*ast.StructType)+ if !ok {+ continue+ }+ if fields := extractExportedStructFields(st); len(fields) > 0 {+ defs[idx].FieldDefs = strings.Join(fields, "|")+ }+ }+}++// extractExportedStructFields returns exported field name:type pairs from a struct.+func extractExportedStructFields(st *ast.StructType) []string {+ var fields []string+ for _, field := range st.Fields.List {+ if len(field.Names) == 0 {+ continue // embedded field, skip+ }+ typeText := goTypeToString(field.Type)+ if typeText == "" {+ continue+ }+ for _, name := range field.Names {+ if !name.IsExported() {+ continue+ }+ fields = append(fields, name.Name+":"+typeText)+ }+ }+ return fields+}++// goTypeToString converts a Go AST type expression to a string representation+// suitable for the LSP type resolver (e.g., "*Echo", "Binder", "[]string").+func goTypeToString(expr ast.Expr) string {+ switch t := expr.(type) {+ case *ast.Ident:+ return t.Name+ case *ast.StarExpr:+ inner := goTypeToString(t.X)+ if inner == "" {+ return ""+ }+ return "*" + inner+ case *ast.ArrayType:+ elem := goTypeToString(t.Elt)+ if elem == "" {+ return ""+ }+ return "[]" + elem+ case *ast.SelectorExpr:+ pkg := goTypeToString(t.X)+ if pkg == "" {+ return ""+ }+ return pkg + "." + t.Sel.Name+ case *ast.MapType:+ k := goTypeToString(t.Key)+ v := goTypeToString(t.Value)+ if k == "" || v == "" {+ return ""+ }+ return fmt.Sprintf("map[%s]%s", k, v)+ case *ast.InterfaceType:+ return "interface{}"+ case *ast.FuncType:+ return "func"+ default:+ return ""+ }+}++// enrichInterfaceMethodNames parses Go source to extract interface method names.+// Populates MethodNames on Interface CrossFileDef entries as "|"-separated strings.+func enrichInterfaceMethodNames(repoPath, relPath string, defs []cbm.CrossFileDef) {+ ifaceNames := make(map[string]int) // shortName -> index in defs+ for i := range defs {+ d := &defs[i]+ if d.IsInterface || d.Label == "Interface" {+ ifaceNames[d.ShortName] = i+ }+ }+ if len(ifaceNames) == 0 {+ return+ }++ src, err := os.ReadFile(filepath.Join(repoPath, relPath))+ if err != nil {+ return+ }++ fset := token.NewFileSet()+ f, err := parser.ParseFile(fset, relPath, src, 0)+ if err != nil {+ return+ }++ for _, decl := range f.Decls {+ gd, ok := decl.(*ast.GenDecl)+ if !ok || gd.Tok != token.TYPE {+ continue+ }+ enrichIfaceMethodsFromGenDecl(gd, ifaceNames, defs)+ }+}++// enrichIfaceMethodsFromGenDecl processes a single GenDecl to extract interface method names.+func enrichIfaceMethodsFromGenDecl(gd *ast.GenDecl, ifaceNames map[string]int, defs []cbm.CrossFileDef) {+ for _, spec := range gd.Specs {+ ts, ok := spec.(*ast.TypeSpec)+ if !ok {+ continue+ }+ idx, found := ifaceNames[ts.Name.Name]+ if !found {+ continue+ }+ iface, ok := ts.Type.(*ast.InterfaceType)+ if !ok {+ continue+ }+ if methods := extractExportedIfaceMethods(iface); len(methods) > 0 {+ defs[idx].MethodNames = strings.Join(methods, "|")+ }+ }+}++// extractExportedIfaceMethods returns exported method names from an interface type.+func extractExportedIfaceMethods(iface *ast.InterfaceType) []string {+ if iface.Methods == nil {+ return nil+ }+ var methods []string+ for _, m := range iface.Methods.List {+ for _, name := range m.Names {+ if name.IsExported() {+ methods = append(methods, name.Name)+ }+ }+ }+ return methods+}++// readGoModulePath reads the module path from go.mod in the given directory.+func readGoModulePath(repoPath string) string {+ data, err := os.ReadFile(filepath.Join(repoPath, "go.mod"))+ if err != nil {+ return ""+ }+ for _, line := range strings.Split(string(data), "\n") {+ line = strings.TrimSpace(line)+ if strings.HasPrefix(line, "module ") {+ return strings.TrimSpace(strings.TrimPrefix(line, "module "))+ }+ }+ return ""+}++// readFileSource reads a file's source content from the repo.+func readFileSource(repoPath, relPath string) []byte {+ data, err := os.ReadFile(filepath.Join(repoPath, relPath))+ if err != nil {+ return nil+ }+ return data+}diff --git a/internal/pipeline/memleak_test.go b/internal/pipeline/memleak_test.gonew file mode 100644index 000000000..68b7d034c--- /dev/null+++ b/internal/pipeline/memleak_test.go@@ -0,0 +1,169 @@+package pipeline++import (+ "context"+ "os"+ "path/filepath"+ "runtime"+ "runtime/debug"+ "testing"++ "github.com/DeusData/codebase-memory-mcp/internal/discover"+ "github.com/DeusData/codebase-memory-mcp/internal/store"+)++// TestMemoryStability indexes a small fixture repo N times and asserts+// that heap usage does not grow unboundedly between iterations.+// Uses HeapInuse as the primary metric (cross-platform). RSS via+// syscall.Getrusage would also capture C-side allocations but is+// Unix-only; HeapInuse catches Go-side leaks which are the main concern.+func TestMemoryStability(t *testing.T) {+ // Create a minimal fixture repo with enough files to exercise the pipeline.+ fixtureDir := t.TempDir()+ writeFixtureFiles(t, fixtureDir)++ dbDir := t.TempDir()+ const projectName = "memleak-test"+ const iterations = 5++ heapSamples := make([]uint64, iterations)++ for i := 0; i < iterations; i++ {+ st, err := store.OpenInDir(dbDir, projectName)+ if err != nil {+ t.Fatalf("iter %d: open store: %v", i, err)+ }++ p := New(context.Background(), st, fixtureDir, discover.ModeFull)+ if err := p.Run(); err != nil {+ st.Close()+ t.Fatalf("iter %d: pipeline.Run: %v", i, err)+ }+ st.Close()++ // Force GC + return memory to OS+ runtime.GC()+ debug.FreeOSMemory()++ var m runtime.MemStats+ runtime.ReadMemStats(&m)+ heapSamples[i] = m.HeapInuse++ t.Logf("iter %d: heap_inuse=%d MB, heap_alloc=%d MB, sys=%d MB",+ i, m.HeapInuse/(1<<20), m.HeapAlloc/(1<<20), m.Sys/(1<<20))+ }++ // Compare first iteration (after warm-up) to last.+ // Allow 30% growth to account for CI runner variance and GC timing.+ baseline := heapSamples[0]+ final := heapSamples[iterations-1]++ if baseline == 0 {+ t.Log("baseline heap is 0, skipping growth check")+ return+ }++ growthPct := float64(final-baseline) / float64(baseline) * 100+ t.Logf("heap growth: baseline=%d MB, final=%d MB, growth=%.1f%%",+ baseline/(1<<20), final/(1<<20), growthPct)++ if final > baseline && growthPct > 30.0 {+ t.Errorf("heap grew %.1f%% over %d iterations (baseline=%d, final=%d) — possible memory leak",+ growthPct, iterations, baseline, final)+ }+}++// writeFixtureFiles creates a small multi-language fixture repo.+func writeFixtureFiles(t *testing.T, dir string) {+ t.Helper()++ files := map[string]string{+ "main.go": `package main++import "fmt"++func main() {+ fmt.Println(greet("world"))+}++func greet(name string) string {+ return "hello " + name+}+`,+ "util.go": `package main++func add(a, b int) int {+ return a + b+}++func multiply(a, b int) int {+ return a * b+}+`,+ "handler.go": `package main++import "net/http"++func handleHealth(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(200)+ w.Write([]byte("ok"))+}++func handleReady(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(200)+}+`,+ "lib/calc.py": `+def calculate(x, y):+ return x + y++def divide(x, y):+ if y == 0:+ raise ValueError("division by zero")+ return x / y++class Calculator:+ def __init__(self):+ self.history = []++ def add(self, a, b):+ result = calculate(a, b)+ self.history.append(result)+ return result+`,+ "src/app.js": `+function fetchData(url) {+ return fetch(url).then(res => res.json());+}++function processData(data) {+ return data.map(item => item.value);+}++class DataService {+ constructor(baseUrl) {+ this.baseUrl = baseUrl;+ }++ async getAll() {+ return fetchData(this.baseUrl + '/items');+ }+}+`,+ }++ for relPath, content := range files {+ absPath := filepath.Join(dir, relPath)+ if err := os.MkdirAll(filepath.Dir(absPath), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(absPath, []byte(content), 0o600); err != nil {+ t.Fatal(err)+ }+ }++ // Create a .git directory marker so discover treats it as a repo root.+ if err := os.MkdirAll(filepath.Join(dir, ".git"), 0o755); err != nil {+ t.Fatal(err)+ }+}diff --git a/internal/pipeline/pipeline.go b/internal/pipeline/pipeline.goindex eb3c1833c..c4ba68e43 100644--- a/internal/pipeline/pipeline.go+++ b/internal/pipeline/pipeline.go@@ -11,6 +11,7 @@ import ("path/filepath""regexp""runtime"+ "runtime/debug""strings""sync""time"@@ -44,6 +45,8 @@ type Pipeline struct {importMaps map[string]map[string]string// returnTypes maps function QN -> return type QN for return-type-based type inferencereturnTypes ReturnTypeMap+ // goLSPIdx indexes Go cross-file definitions for LSP resolution in pass3+ goLSPIdx *goLSPDefIndex}// New creates a new Pipeline.@@ -180,6 +183,7 @@ func (p *Pipeline) Run() error {return fmt.Errorf("discover: %w", err)}slog.Info("pipeline.discovered", "files", len(files))+ logHeapStats("pre_index")// Use MEMORY journal mode during fresh indexing for faster bulk writes.p.Store.BeginBulkWrite(p.ctx)@@ -202,11 +206,15 @@ func (p *Pipeline) Run() error {// Only checkpoint + optimize when actual data was written.// No-op incremental reindexes skip this to avoid ANALYZE overhead.if wroteData {+ walBefore := p.Store.WALSize()p.Store.Checkpoint(p.ctx)+ walAfter := p.Store.WALSize()+ slog.Info("wal.checkpoint", "before_mb", walBefore/(1<<20), "after_mb", walAfter/(1<<20))}nc, _ := p.Store.CountNodes(p.ProjectName)ec, _ := p.Store.CountEdges(p.ProjectName)+ logHeapStats("post_index")slog.Info("pipeline.done", "nodes", nc, "edges", ec, "total_elapsed", time.Since(runStart))return nil}@@ -256,6 +264,7 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {t = time.Now()p.passDefinitions(files) // includes Variable extraction + enrichmentslog.Info("pass.timing", "pass", "definitions", "elapsed", time.Since(t))+ logHeapStats("post_definitions")if err := p.checkCancel(); err != nil {return err}@@ -291,8 +300,18 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {t = time.Now()p.buildReturnTypeMap()+ p.goLSPIdx = p.buildGoLSPDefIndex()+ if p.goLSPIdx != nil {+ p.goLSPIdx.integrateThirdPartyDeps(p.RepoPath, p.importMaps)+ }p.passCalls()slog.Info("pass.timing", "pass", "calls", "elapsed", time.Since(t))+ // Release heavy fields no longer needed after call resolution.+ // Definitions + Calls + TypeAssigns + Imports dominate extractionCache memory+ // (~160 KB/file → 16 GB for 100K-file repos). Nil them to halve peak RSS.+ p.releaseExtractionFields(fieldsPostCalls)+ p.goLSPIdx = nil // no longer needed after call resolution+ logHeapStats("post_calls")if err := p.checkCancel(); err != nil {return err}@@ -300,11 +319,14 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {t = time.Now()p.passUsages()slog.Info("pass.timing", "pass", "usages", "elapsed", time.Since(t))+ p.releaseExtractionFields(fieldsPostUsages)if err := p.checkCancel(); err != nil {return err}p.runSemanticEdgePasses()+ // All semantic fields consumed — release remaining before implements.+ p.releaseExtractionFields(fieldsPostSemantic)if err := p.checkCancel(); err != nil {return err}@@ -316,6 +338,7 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {slog.Info("pass.timing", "pass", "implements", "elapsed", time.Since(t))p.cleanupASTCache()+ logHeapStats("post_cleanup")// Flush in-memory buffer to SQLite with deferred index creation.if err := p.buf.FlushTo(p.ctx, p.Store); err != nil {@@ -324,7 +347,12 @@ func (p *Pipeline) runFullPasses(files []discover.FileInfo) error {p.buf = nil// Post-flush passes use Store directly (need indexes).- t = time.Now()+ return p.runPostFlushPasses(files)+}++// runPostFlushPasses runs passes that require SQLite indexes (post graph-buffer flush).+func (p *Pipeline) runPostFlushPasses(files []discover.FileInfo) error {+ t := time.Now()p.passTests() // TESTS/TESTS_FILE edges (DB-only)slog.Info("pass.timing", "pass", "tests", "elapsed", time.Since(t))@@ -462,8 +490,15 @@ func (p *Pipeline) runIncrementalPasses(// Re-resolve calls + usages for changed + dependent filesp.buildReturnTypeMap()+ p.goLSPIdx = p.buildGoLSPDefIndex()+ if p.goLSPIdx != nil {+ p.goLSPIdx.integrateThirdPartyDeps(p.RepoPath, p.importMaps)+ }p.passCallsForFiles(filesToResolve)+ p.releaseExtractionFields(fieldsPostCalls)+ p.goLSPIdx = nilp.passUsagesForFiles(filesToResolve)+ p.releaseExtractionFields(fieldsPostUsages)if err := p.checkCancel(); err != nil {return err}@@ -473,6 +508,7 @@ func (p *Pipeline) runIncrementalPasses(p.passThrows()p.passReadsWrites()p.passConfigures()+ p.releaseExtractionFields(fieldsPostSemantic)if err := p.checkCancel(); err != nil {return err}@@ -515,27 +551,55 @@ func (p *Pipeline) runIncrementalPasses(}// classifyFiles splits files into changed and unchanged based on stored hashes.-// File hashing is parallelized across CPU cores.+// Uses stat (mtime+size) as a fast pre-filter: files whose mtime and size match+// the stored values are assumed unchanged without reading/hashing. Only files+// with changed stat (or missing from the store) are hashed.func (p *Pipeline) classifyFiles(files []discover.FileInfo) (changed, unchanged []discover.FileInfo) {storedHashes, err := p.Store.GetFileHashes(p.ProjectName)if err != nil || len(storedHashes) == 0 {return files, nil // no hashes → full index}+ // Stage 1: stat pre-filter — separate files into "stat-unchanged" and "needs-hash"+ var needsHash []discover.FileInfo+ for _, f := range files {+ stored, ok := storedHashes[f.RelPath]+ if !ok {+ needsHash = append(needsHash, f) // new file+ continue+ }+ fi, statErr := os.Stat(f.Path)+ if statErr != nil {+ needsHash = append(needsHash, f) // stat failed → hash it+ continue+ }+ if fi.ModTime().UnixNano() == stored.MtimeNs && fi.Size() == stored.Size && stored.MtimeNs != 0 {+ // Stat matches — trust the stored hash+ unchanged = append(unchanged, f)+ } else {+ needsHash = append(needsHash, f)+ }+ }++ if len(needsHash) == 0 {+ return changed, unchanged // nothing to hash+ }++ // Stage 2: hash only files that need ittype hashResult struct {Hash stringErr error}- results := make([]hashResult, len(files))+ results := make([]hashResult, len(needsHash))numWorkers := runtime.NumCPU()- if numWorkers > len(files) {- numWorkers = len(files)+ if numWorkers > len(needsHash) {+ numWorkers = len(needsHash)}g := new(errgroup.Group)g.SetLimit(numWorkers)- for i, f := range files {+ for i, f := range needsHash {g.Go(func() error {hash, hashErr := fileHash(f.Path)results[i] = hashResult{Hash: hash, Err: hashErr}@@ -544,13 +608,13 @@ func (p *Pipeline) classifyFiles(files []discover.FileInfo) (changed, unchanged}_ = g.Wait()- for i, f := range files {+ for i, f := range needsHash {r := results[i]if r.Err != nil {changed = append(changed, f)continue}- if stored, ok := storedHashes[f.RelPath]; ok && stored == r.Hash {+ if stored, ok := storedHashes[f.RelPath]; ok && stored.SHA256 == r.Hash {unchanged = append(unchanged, f)} else {changed = append(changed, f)@@ -641,6 +705,11 @@ func (p *Pipeline) passCallsForFiles(files []discover.FileInfo) {p.extractionCache[f.RelPath] = ext}edges := p.resolveFileCallsCBM(f.RelPath, ext)+ // Release Definitions/Imports per-file after call resolution+ if ext.Result != nil {+ ext.Result.Definitions = nil+ ext.Result.Imports = nil+ }for _, re := range edges {callerNode, _ := p.Store.FindNodeByQN(p.ProjectName, re.CallerQN)targetNode, _ := p.Store.FindNodeByQN(p.ProjectName, re.TargetQN)@@ -676,15 +745,67 @@ func (p *Pipeline) removeDeletedFiles(currentFiles []discover.FileInfo) {}}+// fieldGroup identifies which FileResult fields to release after a pass.+type fieldGroup int++const (+ fieldsPostCalls fieldGroup = iota // Definitions, Calls, ResolvedCalls, TypeAssigns, Imports+ fieldsPostUsages // Usages+ fieldsPostSemantic // TypeRefs, Throws, ReadWrites, EnvAccesses+)++// releaseExtractionFields nils out consumed FileResult slices to reduce peak memory.+// Each FileResult field is used by specific passes; once a pass completes, its fields+// can be released. For a 100K-file repo, Definitions+Calls alone hold ~10 GB.+func (p *Pipeline) releaseExtractionFields(group fieldGroup) {+ for _, ext := range p.extractionCache {+ if ext.Result == nil {+ continue+ }+ switch group {+ case fieldsPostCalls:+ ext.Result.Definitions = nil+ ext.Result.Calls = nil+ ext.Result.ResolvedCalls = nil+ ext.Result.TypeAssigns = nil+ ext.Result.Imports = nil+ case fieldsPostUsages:+ ext.Result.Usages = nil+ case fieldsPostSemantic:+ ext.Result.TypeRefs = nil+ ext.Result.Throws = nil+ ext.Result.ReadWrites = nil+ ext.Result.EnvAccesses = nil+ }+ }+}+func (p *Pipeline) cleanupASTCache() {// Release extraction cache (Go GC handles the cbm.FileResult structs)p.extractionCache = nil+ // Prompt the Go runtime to return freed pages to the OS.+ // Especially useful under GOMEMLIMIT to keep RSS closer to actual usage.+ debug.FreeOSMemory()+}++// logHeapStats logs current Go heap metrics for memory diagnostics.+func logHeapStats(stage string) {+ var m runtime.MemStats+ runtime.ReadMemStats(&m)+ slog.Info("mem.stats",+ "stage", stage,+ "heap_inuse_mb", m.HeapInuse/(1<<20),+ "heap_alloc_mb", m.HeapAlloc/(1<<20),+ "sys_mb", m.Sys/(1<<20),+ )}func (p *Pipeline) updateFileHashes(files []discover.FileInfo) {type hashResult struct {- Hash string- Err error+ Hash string+ MtimeNs int64+ Size int64+ Err error}results := make([]hashResult, len(files))@@ -698,7 +819,14 @@ func (p *Pipeline) updateFileHashes(files []discover.FileInfo) {for i, f := range files {g.Go(func() error {hash, hashErr := fileHash(f.Path)- results[i] = hashResult{Hash: hash, Err: hashErr}+ r := hashResult{Hash: hash, Err: hashErr}+ if hashErr == nil {+ if fi, statErr := os.Stat(f.Path); statErr == nil {+ r.MtimeNs = fi.ModTime().UnixNano()+ r.Size = fi.Size()+ }+ }+ results[i] = rreturn nil})}@@ -712,6 +840,8 @@ func (p *Pipeline) updateFileHashes(files []discover.FileInfo) {Project: p.ProjectName,RelPath: f.RelPath,SHA256: results[i].Hash,+ MtimeNs: results[i].MtimeNs,+ Size: results[i].Size,})}}@@ -1135,6 +1265,14 @@ func (p *Pipeline) passCalls() {return gctx.Err()}results[i] = p.resolveFileCallsCBM(fe.relPath, fe.ext)+ // Release heavy fields per-file immediately after call resolution.+ // Definitions + Imports are only needed for Go LSP cross-file inside+ // resolveFileCallsCBM. Releasing here reduces peak from O(all_files)+ // to O(concurrent_workers) for these fields.+ if fe.ext.Result != nil {+ fe.ext.Result.Definitions = nil+ fe.ext.Result.Imports = nil+ }return nil})}@@ -1146,17 +1284,7 @@ func (p *Pipeline) passCalls() {// flushResolvedEdges converts QN-based resolved edges to ID-based edges and batch-inserts them.func (p *Pipeline) flushResolvedEdges(results [][]resolvedEdge) {- // Collect all unique QNs- qnSet := make(map[string]struct{})- totalEdges := 0- for _, fileEdges := range results {- for _, re := range fileEdges {- qnSet[re.CallerQN] = struct{}{}- qnSet[re.TargetQN] = struct{}{}- totalEdges++- }- }-+ qnSet, totalEdges := collectEdgeQNs(results)if totalEdges == 0 {return}@@ -1172,7 +1300,80 @@ func (p *Pipeline) flushResolvedEdges(results [][]resolvedEdge) {return}- // Build edges+ // Create stub nodes for LSP-resolved targets that don't exist in the graph.+ p.createLSPStubNodes(results, qnToID)++ // Build and insert edges+ edges := buildEdgesFromResults(results, qnToID, p.ProjectName, totalEdges)+ if err := p.insertEdgeBatch(edges); err != nil {+ slog.Warn("pass3.batch_edges.err", "err", err)+ }+}++// collectEdgeQNs collects all unique qualified names and counts total edges from results.+func collectEdgeQNs(results [][]resolvedEdge) (qnSet map[string]struct{}, totalEdges int) {+ qnSet = make(map[string]struct{})+ for _, fileEdges := range results {+ for _, re := range fileEdges {+ qnSet[re.CallerQN] = struct{}{}+ qnSet[re.TargetQN] = struct{}{}+ totalEdges+++ }+ }+ return qnSet, totalEdges+}++// createLSPStubNodes creates stub nodes for LSP-resolved targets that don't exist in the graph.+// This happens for stdlib/external methods (e.g., context.Context.Done) that+// the LSP resolver correctly identifies but aren't indexed as nodes.+func (p *Pipeline) createLSPStubNodes(results [][]resolvedEdge, qnToID map[string]int64) {+ var stubs []*store.Node+ stubQNs := make(map[string]bool)+ for _, fileEdges := range results {+ for _, re := range fileEdges {+ if _, ok := qnToID[re.TargetQN]; ok {+ continue+ }+ if stubQNs[re.TargetQN] {+ continue+ }+ strategy, _ := re.Properties["resolution_strategy"].(string)+ if !strings.HasPrefix(strategy, "lsp_") {+ continue+ }+ stubQNs[re.TargetQN] = true+ name := re.TargetQN+ if idx := strings.LastIndex(name, "."); idx >= 0 {+ name = name[idx+1:]+ }+ label := "Function"+ if strings.Count(re.TargetQN, ".") >= 2 {+ label = "Method"+ }+ stubs = append(stubs, &store.Node{+ Project: p.ProjectName,+ Label: label,+ Name: name,+ QualifiedName: re.TargetQN,+ Properties: map[string]any{"stub": true, "source": "lsp_resolution"},+ })+ }+ }+ if len(stubs) > 0 {+ stubIDs, err := p.upsertNodeBatch(stubs)+ if err != nil {+ slog.Warn("pass3.stub_nodes.err", "err", err)+ } else {+ for qn, id := range stubIDs {+ qnToID[qn] = id+ }+ slog.Info("pass3.stub_nodes", "count", len(stubs))+ }+ }+}++// buildEdgesFromResults converts QN-based resolved edges to store.Edge using the QN-to-ID map.+func buildEdgesFromResults(results [][]resolvedEdge, qnToID map[string]int64, project string, totalEdges int) []*store.Edge {edges := make([]*store.Edge, 0, totalEdges)for _, fileEdges := range results {for _, re := range fileEdges {@@ -1180,7 +1381,7 @@ func (p *Pipeline) flushResolvedEdges(results [][]resolvedEdge) {tgtID, tgtOK := qnToID[re.TargetQN]if srcOK && tgtOK {edges = append(edges, &store.Edge{- Project: p.ProjectName,+ Project: project,SourceID: srcID,TargetID: tgtID,Type: re.Type,@@ -1189,10 +1390,7 @@ func (p *Pipeline) flushResolvedEdges(results [][]resolvedEdge) {}}}-- if err := p.insertEdgeBatch(edges); err != nil {- slog.Warn("pass3.batch_edges.err", "err", err)- }+ return edges}// resolveCallWithTypes resolves a callee name using the registry, import maps,diff --git a/internal/pipeline/pipeline_cbm.go b/internal/pipeline/pipeline_cbm.goindex e2d742d89..42d07bd7c 100644--- a/internal/pipeline/pipeline_cbm.go+++ b/internal/pipeline/pipeline_cbm.go@@ -135,9 +135,15 @@ func cbmDefToNode(def *cbm.Definition, projectName, moduleQN string) (*store.Nodif len(def.BaseClasses) > 0 {props["base_classes"] = def.BaseClasses}+ if len(def.ParamNames) > 0 {+ props["param_names"] = def.ParamNames+ }if len(def.ParamTypes) > 0 {props["param_types"] = def.ParamTypes}+ if len(def.ReturnTypes) > 0 {+ props["return_types"] = def.ReturnTypes+ }if def.Complexity > 0 {props["complexity"] = def.Complexity}@@ -231,64 +237,145 @@ func (p *Pipeline) resolveFileCallsCBM(relPath string, ext *cachedExtraction) []moduleQN := fqn.ModuleQN(p.ProjectName, relPath)importMap := p.importMaps[moduleQN]+ // Cross-file LSP resolution for Go files+ p.runGoLSPCrossFileResolution(ext, moduleQN, relPath, importMap)+// Build type map from CBM type assignmentstypeMap := inferTypesCBM(ext.Result.TypeAssigns, p.registry, moduleQN, importMap)- var edges []resolvedEdge+ // LSP-resolved calls take priority (high confidence, type-aware).+ edges, lspCallerMethods := collectLSPResolvedEdges(ext.Result.ResolvedCalls)+ // Resolve remaining calls via registry + fuzzy matchingfor _, call := range ext.Result.Calls {- calleeName := call.CalleeName- callerQN := call.EnclosingFuncQN- if calleeName == "" {- continue- }- if callerQN == "" {- callerQN = moduleQN+ if edge, ok := p.resolveCallEdge(call, moduleQN, importMap, typeMap, lspCallerMethods); ok {+ edges = append(edges, edge)}+ }- // Python self.method() resolution- if strings.HasPrefix(calleeName, "self.") {- classQN := extractClassFromMethodQN(callerQN)- if classQN != "" {- candidate := classQN + "." + calleeName[5:]- if p.registry.Exists(candidate) {- edges = append(edges, resolvedEdge{CallerQN: callerQN, TargetQN: candidate, Type: "CALLS"})- continue- }- }- }+ return edges+}- // Type-based method dispatch for qualified calls like obj.method()- result := p.resolveCallWithTypes(calleeName, moduleQN, importMap, typeMap)- if result.QualifiedName == "" {- if fuzzyResult, ok := p.registry.FuzzyResolve(calleeName, moduleQN, importMap); ok {- edges = append(edges, resolvedEdge{- CallerQN: callerQN,- TargetQN: fuzzyResult.QualifiedName,- Type: "CALLS",- Properties: map[string]any{- "confidence": fuzzyResult.Confidence,- "confidence_band": confidenceBand(fuzzyResult.Confidence),- "resolution_strategy": fuzzyResult.Strategy,- },- })- }+// runGoLSPCrossFileResolution re-runs LSP with cross-file definitions from imported packages.+func (p *Pipeline) runGoLSPCrossFileResolution(ext *cachedExtraction, moduleQN, relPath string, importMap map[string]string) {+ if ext.Language != lang.Go || p.goLSPIdx == nil {+ return+ }+ crossDefs := p.goLSPIdx.collectCrossFileDefs(importMap)+ if len(crossDefs) == 0 {+ return+ }+ source := readFileSource(p.RepoPath, relPath)+ if len(source) == 0 {+ return+ }+ fileDefs := cbm.DefsToLSPDefs(ext.Result.Definitions, moduleQN)+ resolved := cbm.RunGoLSPCrossFile(source, moduleQN, fileDefs, crossDefs, ext.Result.Imports)+ if len(resolved) > 0 {+ ext.Result.ResolvedCalls = resolved+ }+}++// collectLSPResolvedEdges converts LSP-resolved calls to edges and builds a caller+method dedup set.+func collectLSPResolvedEdges(resolvedCalls []cbm.ResolvedCall) (edges []resolvedEdge, lspCallerMethods map[string]bool) {+ lspResolved := make(map[string]bool)+ lspCallerMethods = make(map[string]bool)++ for _, rc := range resolvedCalls {+ if rc.CallerQN == "" || rc.CalleeQN == "" || rc.Confidence == 0 {continue}-+ key := rc.CallerQN + "\x00" + rc.CalleeQN+ if lspResolved[key] {+ continue+ }+ lspResolved[key] = trueedges = append(edges, resolvedEdge{- CallerQN: callerQN,- TargetQN: result.QualifiedName,+ CallerQN: rc.CallerQN,+ TargetQN: rc.CalleeQN,Type: "CALLS",Properties: map[string]any{- "confidence": result.Confidence,- "confidence_band": confidenceBand(result.Confidence),- "resolution_strategy": result.Strategy,+ "confidence": float64(rc.Confidence),+ "confidence_band": confidenceBand(float64(rc.Confidence)),+ "resolution_strategy": rc.Strategy,},})++ shortName := rc.CalleeQN+ if idx := strings.LastIndex(shortName, "."); idx >= 0 {+ shortName = shortName[idx+1:]+ }+ lspCallerMethods[rc.CallerQN+"\x00"+shortName] = true}- return edges+ return edges, lspCallerMethods+}++// resolveCallEdge resolves a single call to an edge using the registry and type system.+func (p *Pipeline) resolveCallEdge(+ call cbm.Call, moduleQN string, importMap map[string]string,+ typeMap TypeMap, lspCallerMethods map[string]bool,+) (resolvedEdge, bool) {+ calleeName := call.CalleeName+ callerQN := call.EnclosingFuncQN+ if calleeName == "" {+ return resolvedEdge{}, false+ }+ if callerQN == "" {+ callerQN = moduleQN+ }++ // Skip if LSP already resolved this caller+method+ fuzzyShort := calleeName+ if idx := strings.LastIndex(fuzzyShort, "."); idx >= 0 {+ fuzzyShort = fuzzyShort[idx+1:]+ }+ if lspCallerMethods[callerQN+"\x00"+fuzzyShort] {+ return resolvedEdge{}, false+ }++ // Python self.method() resolution+ if strings.HasPrefix(calleeName, "self.") {+ classQN := extractClassFromMethodQN(callerQN)+ if classQN != "" {+ candidate := classQN + "." + calleeName[5:]+ if p.registry.Exists(candidate) {+ return resolvedEdge{CallerQN: callerQN, TargetQN: candidate, Type: "CALLS"}, true+ }+ }+ }++ // Type-based method dispatch for qualified calls like obj.method()+ result := p.resolveCallWithTypes(calleeName, moduleQN, importMap, typeMap)+ if result.QualifiedName == "" {+ if fuzzyResult, ok := p.registry.FuzzyResolve(calleeName, moduleQN, importMap); ok && fuzzyResult.Confidence >= 0.10 {+ return resolvedEdge{+ CallerQN: callerQN,+ TargetQN: fuzzyResult.QualifiedName,+ Type: "CALLS",+ Properties: map[string]any{+ "confidence": fuzzyResult.Confidence,+ "confidence_band": confidenceBand(fuzzyResult.Confidence),+ "resolution_strategy": fuzzyResult.Strategy,+ },+ }, true+ }+ return resolvedEdge{}, false+ }++ if result.Confidence < 0.10 {+ return resolvedEdge{}, false+ }+ return resolvedEdge{+ CallerQN: callerQN,+ TargetQN: result.QualifiedName,+ Type: "CALLS",+ Properties: map[string]any{+ "confidence": result.Confidence,+ "confidence_band": confidenceBand(result.Confidence),+ "resolution_strategy": result.Strategy,+ },+ }, true}// resolveFileUsagesCBM resolves usage references using pre-extracted CBM data.diff --git a/internal/store/router.go b/internal/store/router.goindex 80c30b3cc..9b42953aa 100644--- a/internal/store/router.go+++ b/internal/store/router.go@@ -1,12 +1,15 @@package storeimport (+ "context""fmt""log/slog""os""path/filepath""strings""sync"+ "sync/atomic"+ "time")// ProjectInfo holds metadata about a discovered project database.@@ -16,14 +19,29 @@ type ProjectInfo struct {RootPath string}+// storeEntry wraps a Store with idle-tracking and reference counting.+type storeEntry struct {+ store *Store+ lastUsed time.Time+ refs atomic.Int32 // eviction blocked while >0+}++// ReleaseFunc must be called when the caller is done with the store.+type ReleaseFunc func()+// StoreRouter manages per-project SQLite databases.// Each project gets its own .db file in the cache directory.+// Idle stores are evicted after idleTimeout (configurable) to free memory.type StoreRouter struct {- dir string // ~/.cache/codebase-memory-mcp/- stores map[string]*Store // project name → open Store (lazy)- mu sync.Mutex+ dir string // ~/.cache/codebase-memory-mcp/+ entries map[string]*storeEntry // project name → entry (lazy)+ mu sync.Mutex+ idleTimeout time.Duration+ onDelete func(name string) // optional callback on project deletion}+const defaultIdleTimeout = 30 * time.Second+// NewRouter creates a StoreRouter, ensuring the cache directory exists.// Runs migration from single-DB layout if needed.func NewRouter() (*StoreRouter, error) {@@ -33,8 +51,9 @@ func NewRouter() (*StoreRouter, error) {}r := &StoreRouter{- dir: dir,- stores: make(map[string]*Store),+ dir: dir,+ entries: make(map[string]*storeEntry),+ idleTimeout: defaultIdleTimeout,}// Run one-time migration from single DB to per-project DBs@@ -52,12 +71,20 @@ func NewRouterWithDir(dir string) (*StoreRouter, error) {return nil, fmt.Errorf("mkdir: %w", err)}return &StoreRouter{- dir: dir,- stores: make(map[string]*Store),+ dir: dir,+ entries: make(map[string]*storeEntry),+ idleTimeout: defaultIdleTimeout,}, nil}+// OnDelete registers a callback invoked after a project is deleted.+func (r *StoreRouter) OnDelete(fn func(name string)) {+ r.onDelete = fn+}+// ForProject returns the Store for the given project, opening it lazily.+// Updates lastUsed and increments the ref count. Callers SHOULD use+// UseStore or AcquireStore instead for automatic ref management.func (r *StoreRouter) ForProject(name string) (*Store, error) {if name == "*" || name == "all" {return nil, fmt.Errorf("invalid project name: %q", name)@@ -65,18 +92,63 @@ func (r *StoreRouter) ForProject(name string) (*Store, error) {r.mu.Lock()defer r.mu.Unlock()- if s, ok := r.stores[name]; ok {- return s, nil+ return r.getOrOpenLocked(name)+}++// getOrOpenLocked returns the store, opening it if needed. Must hold r.mu.+func (r *StoreRouter) getOrOpenLocked(name string) (*Store, error) {+ if e, ok := r.entries[name]; ok {+ e.lastUsed = time.Now()+ return e.store, nil}s, err := OpenInDir(r.dir, name)if err != nil {return nil, fmt.Errorf("open store %q: %w", name, err)}- r.stores[name] = s+ r.entries[name] = &storeEntry{+ store: s,+ lastUsed: time.Now(),+ }return s, nil}+// UseStore opens the store for project, calls fn, then releases. Handles ref counting.+func (r *StoreRouter) UseStore(project string, fn func(*Store) error) error {+ st, release, err := r.AcquireStore(project)+ if err != nil {+ return err+ }+ defer release()+ return fn(st)+}++// AcquireStore returns a store with an incremented ref count plus a release function.+// The evictor will not close the store while refs > 0.+func (r *StoreRouter) AcquireStore(project string) (*Store, ReleaseFunc, error) {+ if project == "*" || project == "all" {+ return nil, nil, fmt.Errorf("invalid project name: %q", project)+ }+ r.mu.Lock()+ defer r.mu.Unlock()++ st, err := r.getOrOpenLocked(project)+ if err != nil {+ return nil, nil, err+ }++ e := r.entries[project]+ e.refs.Add(1)++ released := false+ return st, func() {+ if !released {+ released = true+ e.refs.Add(-1)+ }+ }, 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()@@ -85,7 +157,11 @@ func (r *StoreRouter) AllStores() map[string]*Store {entries, err := os.ReadDir(r.dir)if err != nil {slog.Warn("router.all_stores.readdir", "err", err)- return r.stores+ result := make(map[string]*Store, len(r.entries))+ for k, v := range r.entries {+ result[k] = v.store+ }+ return result}for _, e := range entries {@@ -96,7 +172,7 @@ func (r *StoreRouter) AllStores() map[string]*Store {if name == "codebase-memory" {continue // skip legacy single DB}- if _, ok := r.stores[name]; ok {+ if _, ok := r.entries[name]; ok {continue}s, err := OpenInDir(r.dir, name)@@ -104,13 +180,15 @@ func (r *StoreRouter) AllStores() map[string]*Store {slog.Warn("router.all_stores.open", "project", name, "err", err)continue}- r.stores[name] = s+ r.entries[name] = &storeEntry{+ store: s,+ lastUsed: time.Now(),+ }}- // Return a copy to avoid external mutation- result := make(map[string]*Store, len(r.stores))- for k, v := range r.stores {- result[k] = v+ result := make(map[string]*Store, len(r.entries))+ for k, v := range r.entries {+ result[k] = v.store}return result}@@ -153,12 +231,11 @@ func (r *StoreRouter) ListProjects() ([]*ProjectInfo, error) {// 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)+ if e, ok := r.entries[name]; ok {+ e.store.Close()+ delete(r.entries, name)}+ r.mu.Unlock()dbPath := filepath.Join(r.dir, name+".db")for _, suffix := range []string{"", "-wal", "-shm"} {@@ -168,6 +245,10 @@ func (r *StoreRouter) DeleteProject(name string) error {}}slog.Info("router.delete", "project", name)++ if r.onDelete != nil {+ r.onDelete(name)+ }return nil}@@ -188,10 +269,52 @@ func (r *StoreRouter) CloseAll() {r.mu.Lock()defer r.mu.Unlock()- for name, s := range r.stores {- if err := s.Close(); err != nil {+ for name, e := range r.entries {+ if err := e.store.Close(); err != nil {slog.Warn("router.close", "project", name, "err", err)}}- r.stores = make(map[string]*Store)+ r.entries = make(map[string]*storeEntry)+}++// StartEvictor runs a background goroutine that closes idle stores.+// Ticks every 5 seconds. Evicts stores idle for > idleTimeout with refs == 0.+// Exits when ctx is cancelled.+func (r *StoreRouter) StartEvictor(ctx context.Context) {+ go func() {+ ticker := time.NewTicker(5 * time.Second)+ defer ticker.Stop()++ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ r.evictIdle()+ }+ }+ }()+}++// evictIdle closes stores that have been idle longer than idleTimeout and have no refs.+func (r *StoreRouter) evictIdle() {+ r.mu.Lock()+ defer r.mu.Unlock()++ now := time.Now()+ for name, e := range r.entries {+ idle := now.Sub(e.lastUsed)+ if idle <= r.idleTimeout {+ continue+ }+ if e.refs.Load() > 0 {+ continue // in use — skip+ }+ e.store.Checkpoint(context.Background())+ if err := e.store.Close(); err != nil {+ slog.Warn("store.evict.close", "project", name, "err", err)+ }+ delete(r.entries, name)+ slog.Info("store.evict", "project", name, "idle_s", int(idle.Seconds()))+ }}diff --git a/internal/tools/tools.go b/internal/tools/tools.goindex 8e1bb4f93..4b28e9e62 100644--- a/internal/tools/tools.go+++ b/internal/tools/tools.go@@ -38,7 +38,9 @@ var releaseURL = "https://api.github.com/repos/DeusData/codebase-memory-mcp/reletype Server struct {mcp *mcp.Serverrouter *store.StoreRouter+ config *store.ConfigStorewatcher *watcher.Watcher+ ctx context.Context // server lifetime context — cancelled on shutdownindexMu sync.Mutexhandlers map[string]mcp.ToolHandler@@ -49,14 +51,26 @@ type Server struct {indexStatus atomic.ValueindexStartedAt atomic.Value // time.Time — when current/last index startedupdateNotice atomic.Value // string — set once by checkForUpdate, cleared after first injection+ updateOnce sync.Once // ensures checkForUpdate runs at most once per session+}++// ServerOption configures a Server.+type ServerOption func(*Server)++// WithConfig attaches a ConfigStore for reading runtime settings.+func WithConfig(c *store.ConfigStore) ServerOption {+ return func(s *Server) { s.config = c }}// NewServer creates a new MCP server with all tools registered.-func NewServer(r *store.StoreRouter) *Server {+func NewServer(r *store.StoreRouter, opts ...ServerOption) *Server {srv := &Server{router: r,handlers: make(map[string]mcp.ToolHandler),}+ for _, opt := range opts {+ opt(srv)+ }srv.mcp = mcp.NewServer(&mcp.Implementation{@@ -75,8 +89,9 @@ func NewServer(r *store.StoreRouter) *Server {}// StartWatcher launches the background file-change polling goroutine.-// It stops when ctx is cancelled.+// It stores ctx for use by startAutoIndex and stops when ctx is cancelled.func (s *Server) StartWatcher(ctx context.Context) {+ s.ctx = ctxgo s.watcher.Run(ctx)}@@ -113,7 +128,7 @@ func (s *Server) SessionProject() string {// SetSessionRoot sets the session root path directly (for CLI mode).func (s *Server) SetSessionRoot(rootPath string) {- go s.checkForUpdate()+ go s.updateOnce.Do(s.checkForUpdate)s.sessionOnce.Do(func() {s.sessionRoot = rootPathif rootPath != "" {@@ -126,7 +141,7 @@ func (s *Server) SetSessionRoot(rootPath string) {// onInitialized is called when the client sends notifications/initialized.func (s *Server) onInitialized(ctx context.Context, req *mcp.InitializedRequest) {- go s.checkForUpdate()+ go s.updateOnce.Do(s.checkForUpdate)s.sessionOnce.Do(func() {s.sessionRoot = s.detectSessionRoot(ctx, req.Session)if s.sessionRoot != "" {@@ -138,7 +153,7 @@ func (s *Server) onInitialized(ctx context.Context, req *mcp.InitializedRequest)// onRootsChanged re-detects session root if not yet set.func (s *Server) onRootsChanged(ctx context.Context, req *mcp.RootsListChangedRequest) {- go s.checkForUpdate()+ go s.updateOnce.Do(s.checkForUpdate)s.sessionOnce.Do(func() {s.sessionRoot = s.detectSessionRoot(ctx, req.Session)if s.sessionRoot != "" {@@ -193,11 +208,52 @@ func parseFileURI(uri string) (string, bool) {return filepath.FromSlash(path), true}+// defaultAutoIndexLimit is the maximum number of source files that auto-index+// will process for a never-before-indexed project. Override with config key+// "auto_index_limit". Projects above this limit require explicit index_repository.+const defaultAutoIndexLimit = 50000+// startAutoIndex triggers background indexing for the session project.+// Respects config: auto_index must be true (default: false).+// For never-indexed projects: only auto-indexes if file count <= auto_index_limit.+// For previously-indexed projects: always re-indexes (incremental, fast).func (s *Server) startAutoIndex() {hasDB := s.router.HasProject(s.sessionProject)+ // Auto-index for new projects requires explicit opt-in via config.+ // Previously-indexed projects always get incremental re-index (cheap).if !hasDB {+ autoIndex := false+ fileLimit := defaultAutoIndexLimit+ if s.config != nil {+ autoIndex = s.config.GetBool(store.ConfigAutoIndex, false)+ fileLimit = s.config.GetInt(store.ConfigAutoIndexLimit, defaultAutoIndexLimit)+ }++ if !autoIndex {+ slog.Info("autoindex.skip",+ "reason", "auto_index_disabled",+ "hint", "run: codebase-memory-mcp config set auto_index true",+ )+ return+ }++ // Check file count before committing to index.+ // Prevents OOM when the server starts in a large monorepo.+ files, err := discover.Discover(s.ctx, s.sessionRoot, nil)+ if err != nil {+ slog.Warn("autoindex.discover.err", "err", err)+ return+ }+ if len(files) > fileLimit {+ slog.Warn("autoindex.skip",+ "reason", "too_many_files",+ "files", len(files),+ "limit", fileLimit,+ "hint", "call index_repository explicitly or increase auto_index_limit",+ )+ return+ }s.indexStatus.Store("indexing")} else {s.indexStatus.Store("ready")@@ -220,7 +276,7 @@ func (s *Server) startAutoIndex() {slog.Warn("autoindex.store.err", "err", err)return}- p := pipeline.New(context.Background(), st, s.sessionRoot, discover.ModeFull)+ p := pipeline.New(s.ctx, st, s.sessionRoot, discover.ModeFull)if err := p.Run(); err != nil {slog.Warn("autoindex.err", "err", err)return@@ -667,7 +723,7 @@ func (s *Server) registerSearchTools() {func (s *Server) registerQueryTool() {s.addTool(&mcp.Tool{Name: "query_graph",- Description: "Execute a Cypher-like graph query. String matching in WHERE is case-sensitive by default. For case-insensitive regex: use (?i) flag — WHERE f.name =~ '(?i)handler'. CONTAINS and STARTS WITH are always case-sensitive — use =~ with (?i) for case-insensitive substring matching: WHERE f.name =~ '(?i).*order.*'. Best practice: use regex alternatives for word form variance — WHERE f.name =~ '(?i)sponsor|sponsoring|sponsored'. Tip: prefer search_graph for simple name searches (case-insensitive by default) — use query_graph only when you need Cypher's relationship patterns or edge properties. WARNING: 200-row cap applies BEFORE aggregation — COUNT queries on large codebases silently undercount. For fan-out/fan-in counting, use search_graph with min_degree/max_degree instead. Best for: relationship patterns, filtered joins, path queries, and edge property filtering. Supports WHERE on edge properties: r.url_path CONTAINS 'orders', r.confidence >= 0.6, r.method = 'POST', r.confidence_band = 'high', r.validated_by_trace = true, r.coupling_score >= 0.5. This is the correct tool for listing cross-service edges — use MATCH (a)-[r:HTTP_CALLS]->(b) RETURN a.name, b.name, r.url_path, r.confidence, r.confidence_band to see HTTP links with URLs and confidence scores (bands: high>=0.7, medium>=0.45, speculative>=0.25), or MATCH (a)-[r:ASYNC_CALLS]->(b) for async dispatch edges. For change coupling: MATCH (a)-[r:FILE_CHANGES_WITH]->(b) RETURN a.name, b.name, r.coupling_score, r.co_change_count. For interface method overrides: MATCH (s)-[r:OVERRIDE]->(i) to find struct methods implementing interface methods. For read references (callbacks, variable assignments): MATCH (a)-[r:USAGE]->(b). Always use LIMIT. Edge types: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, DEFINES, DEFINES_METHOD, HANDLES, IMPLEMENTS, OVERRIDE, USAGE, FILE_CHANGES_WITH.",+ Description: "Execute a Cypher-like graph query. String matching in WHERE is case-sensitive by default. For case-insensitive regex: use (?i) flag — WHERE f.name =~ '(?i)handler'. CONTAINS and STARTS WITH are always case-sensitive — use =~ with (?i) for case-insensitive substring matching: WHERE f.name =~ '(?i).*order.*'. Best practice: use regex alternatives for word form variance — WHERE f.name =~ '(?i)sponsor|sponsoring|sponsored'. Tip: prefer search_graph for simple name searches (case-insensitive by default) — use query_graph only when you need Cypher's relationship patterns or edge properties. Default row cap is 200 — use max_rows parameter to increase (up to 10000) for COUNT/aggregation queries on large codebases. Best for: relationship patterns, filtered joins, path queries, and edge property filtering. Supports WHERE on edge properties: r.url_path CONTAINS 'orders', r.confidence >= 0.6, r.method = 'POST', r.confidence_band = 'high', r.validated_by_trace = true, r.coupling_score >= 0.5. This is the correct tool for listing cross-service edges — use MATCH (a)-[r:HTTP_CALLS]->(b) RETURN a.name, b.name, r.url_path, r.confidence, r.confidence_band to see HTTP links with URLs and confidence scores (bands: high>=0.7, medium>=0.45, speculative>=0.25), or MATCH (a)-[r:ASYNC_CALLS]->(b) for async dispatch edges. For change coupling: MATCH (a)-[r:FILE_CHANGES_WITH]->(b) RETURN a.name, b.name, r.coupling_score, r.co_change_count. For interface method overrides: MATCH (s)-[r:OVERRIDE]->(i) to find struct methods implementing interface methods. For read references (callbacks, variable assignments): MATCH (a)-[r:USAGE]->(b). Always use LIMIT. Edge types: CALLS, HTTP_CALLS, ASYNC_CALLS, IMPORTS, DEFINES, DEFINES_METHOD, HANDLES, IMPLEMENTS, OVERRIDE, USAGE, FILE_CHANGES_WITH.",InputSchema: json.RawMessage(`{"type": "object","properties": {@@ -678,6 +734,10 @@ func (s *Server) registerQueryTool() {"project": {"type": "string","description": "Project to query. Defaults to session project."+ },+ "max_rows": {+ "type": "integer",+ "description": "Maximum result rows (default 200, max 10000). Overrides the internal row cap. Use higher values for COUNT/aggregation queries on large codebases."}},"required": ["query"]diff --git a/internal/watcher/watcher.go b/internal/watcher/watcher.goindex 6d03f0632..4dce88b8f 100644--- a/internal/watcher/watcher.go+++ b/internal/watcher/watcher.go@@ -1,18 +1,51 @@package watcherimport (+ "bytes""context"+ "io/fs""log/slog""os"+ "os/exec"+ "path/filepath"+ "strings"+ "sync/atomic""time"+ "github.com/fsnotify/fsnotify"+"github.com/DeusData/codebase-memory-mcp/internal/discover""github.com/DeusData/codebase-memory-mcp/internal/store")+// watchStrategy determines how the watcher detects file changes for a project.+type watchStrategy int+const (- baseInterval = 1 * time.Second- maxInterval = 60 * time.Second+ strategyAuto watchStrategy = iota // auto-detect at first poll+ strategyGit // git status + HEAD tracking+ strategyFSNotify // fsnotify event-driven+ strategyDirMtime // directory mtime polling (fallback)+)++func (s watchStrategy) String() string {+ switch s {+ case strategyGit:+ return "git"+ case strategyFSNotify:+ return "fsnotify"+ case strategyDirMtime:+ return "dirmtime"+ default:+ return "auto"+ }+}++const (+ baseInterval = 1 * time.Second+ maxInterval = 60 * time.Second+ fullSnapshotInterval = 5 // polls between forced full snapshots+ projectsCacheTTL = 60 * time.Second)type fileSnapshot struct {@@ -21,29 +54,80 @@ type fileSnapshot struct {}type projectState struct {- snapshot map[string]fileSnapshot- interval time.Duration- nextPoll time.Time+ snapshot map[string]fileSnapshot+ pollsSinceFull int+ interval time.Duration+ nextPoll time.Time++ // Strategy (set during baseline, may downgrade at runtime).+ strategy watchStrategy++ // Git strategy state.+ lastGitHead string++ // FSNotify strategy state.+ fsWatcher *fsnotify.Watcher+ fsChanged atomic.Bool+ fsCancel context.CancelFunc+ fsDone chan struct{} // closed when drainFSEvents exits++ // Dir-mtime strategy state.+ dirMtimes map[string]time.Time+}++// close releases per-project resources (fsnotify watcher, goroutines).+func (ps *projectState) close() {+ if ps.fsCancel != nil {+ ps.fsCancel()+ }+ if ps.fsWatcher != nil {+ ps.fsWatcher.Close()+ }+ if ps.fsDone != nil {+ <-ps.fsDone // wait for drain goroutine to exit+ }+ ps.fsCancel = nil+ ps.fsWatcher = nil+ ps.fsDone = nil}// IndexFunc is the callback signature for triggering a re-index.type IndexFunc func(ctx context.Context, projectName, rootPath string) error// Watcher polls indexed projects for file changes and triggers re-indexing.+// Change detection uses a 3-tier strategy per project:+//+// 1. Git — git status + HEAD tracking (for git repos)+// 2. FSNotify — event-driven via OS file notifications (for non-git dirs)+// 3. Dir-mtime — directory mtime polling (fallback if fsnotify setup fails)type Watcher struct {- router *store.StoreRouter- indexFn IndexFunc- projects map[string]*projectState- ctx context.Context+ router *store.StoreRouter+ indexFn IndexFunc+ projects map[string]*projectState+ ctx context.Context+ cachedProjects []*store.ProjectInfo+ projectsCacheTime time.Time++ // testStrategy overrides auto-detection when non-zero (for tests).+ testStrategy watchStrategy}// New creates a Watcher. indexFn is called when file changes are detected.func New(r *store.StoreRouter, indexFn IndexFunc) *Watcher {- return &Watcher{+ w := &Watcher{router: r,indexFn: indexFn,projects: make(map[string]*projectState),+ ctx: context.Background(),}+ // Wire invalidation: when a project is deleted, clear the cache immediately.+ r.OnDelete(func(_ string) { w.InvalidateProjectsCache() })+ return w+}++// InvalidateProjectsCache forces the next pollAll to re-query ListProjects.+func (w *Watcher) InvalidateProjectsCache() {+ w.projectsCacheTime = time.Time{}}// Run blocks until ctx is cancelled. Ticks at baseInterval, polling each@@ -52,6 +136,7 @@ func (w *Watcher) Run(ctx context.Context) {w.ctx = ctxticker := time.NewTicker(baseInterval)defer ticker.Stop()+ defer w.closeAll()for {select {@@ -63,23 +148,47 @@ func (w *Watcher) Run(ctx context.Context) {}}+// closeAll releases resources for all tracked projects.+func (w *Watcher) closeAll() {+ for _, state := range w.projects {+ state.close()+ }+}+// pollAll lists all indexed projects and polls each that is due.+// Prunes watcher state for projects that no longer exist.func (w *Watcher) pollAll() {- projectInfos, err := w.router.ListProjects()- if err != nil {- slog.Warn("watcher.list_projects", "err", err)- return+ // Cache ListProjects to avoid repeated ReadDir+SQLite queries.+ if time.Since(w.projectsCacheTime) > projectsCacheTTL {+ infos, err := w.router.ListProjects()+ if err != nil {+ slog.Warn("watcher.list_projects", "err", err)+ return+ }+ w.cachedProjects = infos+ w.projectsCacheTime = time.Now()+ }+ projectInfos := w.cachedProjects++ // Prune stale entries.+ activeNames := make(map[string]struct{}, len(projectInfos))+ for _, info := range projectInfos {+ activeNames[info.Name] = struct{}{}+ }+ for name, state := range w.projects {+ if _, ok := activeNames[name]; !ok {+ slog.Info("watcher.prune", "project", name)+ state.close()+ delete(w.projects, name)+ }}now := time.Now()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 storeproj, projErr := st.GetProject(info.Name)if projErr != nil || proj == nil {continue@@ -99,63 +208,345 @@ func (w *Watcher) pollAll() {}}-// pollProject captures a snapshot of the file tree and compares with previous.-// First poll: captures baseline without triggering indexing.-// Subsequent polls: triggers indexFn if any file changed.+// --- Strategy probing ---++// probeStrategy determines the best change detection strategy for a project.+// Order: git → fsnotify → dirmtime.+func (w *Watcher) probeStrategy(ctx context.Context, rootPath string) watchStrategy {+ if w.testStrategy != strategyAuto {+ return w.testStrategy+ }+ if isGitRepo(ctx, rootPath) {+ return strategyGit+ }+ // FSNotify is the intent; actual setup may fail → falls back in initBaseline.+ return strategyFSNotify+}++// --- Core poll logic ---+func (w *Watcher) pollProject(proj *store.Project, state *projectState) {- // Verify root path still existsif _, err := os.Stat(proj.RootPath); err != nil {slog.Warn("watcher.root_gone", "project", proj.Name, "path", proj.RootPath)state.nextPoll = time.Now().Add(maxInterval)return}- snap, err := captureSnapshot(proj.RootPath)+ // First poll — capture baseline and select strategy.+ if state.snapshot == nil {+ w.initBaseline(proj, state)+ return+ }++ state.pollsSinceFull++++ // Check sentinel based on strategy.+ changed, strategyFailed := w.checkSentinel(proj, state)++ if strategyFailed {+ w.downgradeStrategy(proj, state)+ changed, _ = w.checkSentinel(proj, state)+ }++ // Git sentinel catches everything — no forced full snapshot needed.+ // FSNotify + dir-mtime may miss in-place edits, so force periodically.+ forceFull := state.strategy != strategyGit && state.pollsSinceFull >= fullSnapshotInterval++ if !changed && !forceFull {+ state.nextPoll = time.Now().Add(state.interval)+ return+ }++ w.fullSnapshotAndIndex(proj, state)+}++func (w *Watcher) initBaseline(proj *store.Project, state *projectState) {+ snap, err := captureSnapshot(w.ctx, proj.RootPath)if err != nil {slog.Warn("watcher.snapshot", "project", proj.Name, "err", err)- state.nextPoll = time.Now().Add(state.interval)+ state.nextPoll = time.Now().Add(baseInterval)return}- interval := pollInterval(len(snap))+ state.snapshot = snap+ state.pollsSinceFull = 0+ state.interval = pollInterval(len(snap))+ state.nextPoll = time.Now().Add(state.interval)- if state.snapshot == nil {- // First poll — capture baseline, no index trigger- slog.Debug("watcher.baseline", "project", proj.Name, "files", len(snap))- state.snapshot = snap- state.interval = interval- state.nextPoll = time.Now().Add(interval)+ // Select and initialize strategy.+ state.strategy = w.probeStrategy(w.ctx, proj.RootPath)++ switch state.strategy {+ case strategyGit:+ head, _ := gitHead(w.ctx, proj.RootPath)+ state.lastGitHead = head+ slog.Debug("watcher.baseline", "project", proj.Name, "strategy", "git", "files", len(snap))++ case strategyFSNotify:+ if err := w.initFSNotify(state, proj.RootPath); err != nil {+ slog.Debug("watcher.fsnotify.fallback", "project", proj.Name, "err", err)+ state.strategy = strategyDirMtime+ state.dirMtimes, _ = checkDirMtimes(w.ctx, proj.RootPath)+ slog.Debug("watcher.baseline", "project", proj.Name, "strategy", "dirmtime", "files", len(snap), "dirs", len(state.dirMtimes))+ } else {+ slog.Debug("watcher.baseline", "project", proj.Name, "strategy", "fsnotify", "files", len(snap))+ }++ case strategyDirMtime:+ state.dirMtimes, _ = checkDirMtimes(w.ctx, proj.RootPath)+ slog.Debug("watcher.baseline", "project", proj.Name, "strategy", "dirmtime", "files", len(snap), "dirs", len(state.dirMtimes))+ }+}++// checkSentinel returns (changed, strategyFailed).+func (w *Watcher) checkSentinel(proj *store.Project, state *projectState) (changed, strategyFailed bool) {+ switch state.strategy {+ case strategyGit:+ changed, newHead, err := gitSentinel(w.ctx, proj.RootPath, state.lastGitHead)+ if err != nil {+ slog.Warn("watcher.git.err", "project", proj.Name, "err", err)+ return false, true+ }+ state.lastGitHead = newHead+ return changed, false++ case strategyFSNotify:+ return state.fsChanged.CompareAndSwap(true, false), false++ case strategyDirMtime:+ dirMtimes, _ := checkDirMtimes(w.ctx, proj.RootPath)+ changed := !dirMtimesEqual(state.dirMtimes, dirMtimes)+ state.dirMtimes = dirMtimes+ return changed, false++ default:+ return false, true+ }+}++// downgradeStrategy moves to the next fallback tier.+func (w *Watcher) downgradeStrategy(proj *store.Project, state *projectState) {+ old := state.strategy+ switch old {+ case strategyGit:+ // Try fsnotify, then dir-mtime.+ state.strategy = strategyFSNotify+ if err := w.initFSNotify(state, proj.RootPath); err != nil {+ state.strategy = strategyDirMtime+ state.dirMtimes, _ = checkDirMtimes(w.ctx, proj.RootPath)+ }+ case strategyFSNotify:+ state.close()+ state.strategy = strategyDirMtime+ state.dirMtimes, _ = checkDirMtimes(w.ctx, proj.RootPath)+ default:+ return // already at bottom tier+ }+ slog.Info("watcher.strategy.downgrade", "project", proj.Name, "from", old.String(), "to", state.strategy.String())+}++func (w *Watcher) fullSnapshotAndIndex(proj *store.Project, state *projectState) {+ snap, err := captureSnapshot(w.ctx, proj.RootPath)+ if err != nil {+ slog.Warn("watcher.snapshot", "project", proj.Name, "err", err)+ state.nextPoll = time.Now().Add(state.interval)return}+ interval := pollInterval(len(snap))+ state.pollsSinceFull = 0+if snapshotsEqual(state.snapshot, snap) {state.interval = intervalstate.nextPoll = time.Now().Add(interval)return}- slog.Info("watcher.changed", "project", proj.Name, "files", len(snap))+ slog.Info("watcher.changed", "project", proj.Name, "strategy", state.strategy.String(), "files", len(snap))if err := w.indexFn(w.ctx, proj.Name, proj.RootPath); err != nil {slog.Warn("watcher.index", "project", proj.Name, "err", err)- // Keep old snapshot so we retry next cyclestate.nextPoll = time.Now().Add(interval)return}- // Successful index — update snapshot and recalculate intervalstate.snapshot = snapstate.interval = pollInterval(len(snap))state.nextPoll = time.Now().Add(state.interval)++ // Update git HEAD after successful index.+ if state.strategy == strategyGit {+ if head, err := gitHead(w.ctx, proj.RootPath); err == nil {+ state.lastGitHead = head+ }+ }+}++// --- Git sentinel ---++// isGitRepo checks if rootPath is inside a git repository.+func isGitRepo(ctx context.Context, rootPath string) bool {+ ctx, cancel := context.WithTimeout(ctx, 2*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, "git", "-C", rootPath, "rev-parse", "--git-dir")+ cmd.Stdout = nil+ cmd.Stderr = nil+ return cmd.Run() == nil+}++// gitHead returns the current HEAD commit hash.+func gitHead(ctx context.Context, rootPath string) (string, error) {+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()+ cmd := exec.CommandContext(ctx, "git", "-C", rootPath, "rev-parse", "HEAD")+ out, err := cmd.Output()+ if err != nil {+ return "", err+ }+ return strings.TrimSpace(string(out)), nil+}++// gitSentinel checks for working tree changes or HEAD movement since lastHead.+func gitSentinel(ctx context.Context, rootPath, lastHead string) (changed bool, newHead string, err error) {+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)+ defer cancel()++ head, err := gitHead(ctx, rootPath)+ if err != nil {+ return false, "", err+ }+ if lastHead != "" && head != lastHead {+ return true, head, nil // HEAD moved (commit, checkout, pull)+ }++ // Check working tree.+ cmd := exec.CommandContext(ctx, "git", "--no-optional-locks", "-C", rootPath,+ "status", "--porcelain", "--untracked-files=normal")+ out, err := cmd.Output()+ if err != nil {+ return false, head, err+ }+ return len(bytes.TrimSpace(out)) > 0, head, nil+}++// --- FSNotify sentinel ---++// initFSNotify sets up an fsnotify watcher for all directories under rootPath.+// Starts a drain goroutine that sets state.fsChanged on events.+func (w *Watcher) initFSNotify(state *projectState, rootPath string) error {+ fsw, err := fsnotify.NewWatcher()+ if err != nil {+ return err+ }++ walkErr := filepath.WalkDir(rootPath, func(path string, d fs.DirEntry, walkDirErr error) error {+ if walkDirErr != nil {+ return walkDirErr+ }+ if !d.IsDir() {+ return nil+ }+ name := d.Name()+ if name == ".git" || name == "node_modules" || name == "__pycache__" || name == ".venv" || name == "vendor" {+ return filepath.SkipDir+ }+ if addErr := fsw.Add(path); addErr != nil {+ return addErr // FD limit or other OS error → fall back+ }+ return nil+ })+ if walkErr != nil {+ fsw.Close()+ return walkErr+ }++ ctx, cancel := context.WithCancel(w.ctx)+ done := make(chan struct{})+ state.fsWatcher = fsw+ state.fsCancel = cancel+ state.fsDone = done+ go drainFSEvents(ctx, fsw, &state.fsChanged, done)+ return nil+}++// drainFSEvents reads fsnotify events and sets the changed flag.+// Exits when ctx is cancelled or the watcher is closed.+func drainFSEvents(ctx context.Context, fsw *fsnotify.Watcher, changed *atomic.Bool, done chan struct{}) {+ defer close(done)+ for {+ select {+ case <-ctx.Done():+ return+ case ev, ok := <-fsw.Events:+ if !ok {+ return+ }+ changed.Store(true)+ // Watch newly created directories for future events.+ if ev.Has(fsnotify.Create) {+ if info, err := os.Stat(ev.Name); err == nil && info.IsDir() {+ _ = fsw.Add(ev.Name)+ }+ }+ case _, ok := <-fsw.Errors:+ if !ok {+ return+ }+ }+ }+}++// --- Dir-mtime sentinel ---++// checkDirMtimes walks only directories under rootPath and records their mtimes.+// Cost: ~200 syscalls for a project with 200 dirs (vs 10K+ for full file walk).+func checkDirMtimes(ctx context.Context, rootPath string) (map[string]time.Time, error) {+ mtimes := make(map[string]time.Time, 256)+ err := filepath.WalkDir(rootPath, func(path string, d fs.DirEntry, walkDirErr error) error {+ if walkDirErr != nil {+ return walkDirErr+ }+ if ctx.Err() != nil {+ return ctx.Err()+ }+ if !d.IsDir() {+ return nil+ }+ name := d.Name()+ if name == ".git" || name == "node_modules" || name == "__pycache__" || name == ".venv" || name == "vendor" {+ return filepath.SkipDir+ }+ info, statErr := d.Info()+ if statErr != nil {+ return statErr+ }+ mtimes[path] = info.ModTime()+ return nil+ })+ return mtimes, err+}++// dirMtimesEqual returns true if two dir mtime maps are identical.+func dirMtimesEqual(a, b map[string]time.Time) bool {+ if len(a) != len(b) {+ return false+ }+ for path, aTime := range a {+ if bTime, ok := b[path]; !ok || !aTime.Equal(bTime) {+ return false+ }+ }+ return true}+// --- Snapshot functions ---+// captureSnapshot walks the file tree using discover.Discover and captures// mtime+size for each file.-func captureSnapshot(rootPath string) (map[string]fileSnapshot, error) {- files, err := discover.Discover(context.Background(), rootPath, nil)+func captureSnapshot(ctx context.Context, rootPath string) (map[string]fileSnapshot, error) {+ files, err := discover.Discover(ctx, rootPath, nil)if err != nil {return nil, err}-snap := make(map[string]fileSnapshot, len(files))for _, f := range files {info, statErr := os.Stat(f.Path)diff --git a/internal/watcher/watcher_test.go b/internal/watcher/watcher_test.goindex a75a2e985..c11a3f2f1 100644--- a/internal/watcher/watcher_test.go+++ b/internal/watcher/watcher_test.go@@ -3,6 +3,7 @@ package watcherimport ("context""os"+ "os/exec""path/filepath""sync/atomic""testing"@@ -11,6 +12,24 @@ import ("github.com/DeusData/codebase-memory-mcp/internal/store")+// --- Test helpers ---++// mustWriteFile is a test helper that writes a file and fails the test on error.+func mustWriteFile(t *testing.T, path string, data []byte) {+ t.Helper()+ if err := os.WriteFile(path, data, 0o600); err != nil {+ t.Fatal(err)+ }+}++// mustMkdirAll is a test helper that creates directories and fails the test on error.+func mustMkdirAll(t *testing.T, path string) {+ t.Helper()+ if err := os.MkdirAll(path, 0o755); err != nil {+ t.Fatal(err)+ }+}+// 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()@@ -32,6 +51,56 @@ func newTestRouter(t *testing.T, projectName, rootPath string) *store.StoreRoutereturn r}+func gitAvailable() bool {+ _, err := exec.LookPath("git")+ return err == nil+}++// initGitRepo initializes a git repo in dir with an initial commit.+func initGitRepo(t *testing.T, dir string) {+ t.Helper()+ gitRun(t, dir, "init")+ gitRun(t, dir, "config", "user.email", "[email protected]")+ gitRun(t, dir, "config", "user.name", "test")+}++// gitCommitAll stages all files and commits.+func gitCommitAll(t *testing.T, dir, msg string) {+ t.Helper()+ gitRun(t, dir, "add", "-A")+ gitRun(t, dir, "commit", "-m", msg)+}++func gitRun(t *testing.T, dir string, args ...string) {+ t.Helper()+ cmd := exec.CommandContext(context.Background(), "git", args...)+ cmd.Dir = dir+ cmd.Env = append(os.Environ(),+ "GIT_AUTHOR_NAME=test",+ "[email protected]",+ "GIT_COMMITTER_NAME=test",+ "[email protected]",+ )+ if out, err := cmd.CombinedOutput(); err != nil {+ t.Fatalf("git %v: %v\n%s", args, err, out)+ }+}++func newWatcherWithStrategy(r *store.StoreRouter, indexFn IndexFunc, strategy watchStrategy) *Watcher {+ w := New(r, indexFn)+ w.testStrategy = strategy+ return w+}++// resetPollTimers allows immediate re-polling.+func resetPollTimers(w *Watcher) {+ for _, state := range w.projects {+ state.nextPoll = time.Time{}+ }+}++// --- Snapshot unit tests ---+func TestSnapshotsEqual(t *testing.T) {now := time.Now()@@ -114,12 +183,11 @@ func TestPollInterval(t *testing.T) {func TestCaptureSnapshot(t *testing.T) {tmpDir := t.TempDir()- // Create a Go file that discover.Discover will pick upif err := os.WriteFile(filepath.Join(tmpDir, "main.go"), []byte("package main\n"), 0o600); err != nil {t.Fatal(err)}- snap, err := captureSnapshot(tmpDir)+ snap, err := captureSnapshot(context.Background(), tmpDir)if err != nil {t.Fatal(err)}@@ -147,7 +215,7 @@ func TestCaptureSnapshotDetectsChanges(t *testing.T) {t.Fatal(err)}- snap1, err := captureSnapshot(tmpDir)+ snap1, err := captureSnapshot(context.Background(), tmpDir)if err != nil {t.Fatal(err)}@@ -159,7 +227,7 @@ func TestCaptureSnapshotDetectsChanges(t *testing.T) {t.Fatal(err)}- snap2, err := captureSnapshot(tmpDir)+ snap2, err := captureSnapshot(context.Background(), tmpDir)if err != nil {t.Fatal(err)}@@ -169,6 +237,341 @@ func TestCaptureSnapshotDetectsChanges(t *testing.T) {}}+// --- Strategy selection tests ---++func TestStrategyString(t *testing.T) {+ tests := []struct {+ s watchStrategy+ want string+ }{+ {strategyAuto, "auto"},+ {strategyGit, "git"},+ {strategyFSNotify, "fsnotify"},+ {strategyDirMtime, "dirmtime"},+ }+ for _, tt := range tests {+ if got := tt.s.String(); got != tt.want {+ t.Errorf("%d.String() = %q, want %q", tt.s, got, tt.want)+ }+ }+}++func TestProbeStrategyGit(t *testing.T) {+ if !gitAvailable() {+ t.Skip("git not available")+ }+ tmpDir := t.TempDir()+ initGitRepo(t, tmpDir)++ w := &Watcher{ctx: context.Background()}+ got := w.probeStrategy(context.Background(), tmpDir)+ if got != strategyGit {+ t.Errorf("expected strategyGit for git repo, got %v", got)+ }+}++func TestProbeStrategyNonGit(t *testing.T) {+ tmpDir := t.TempDir()++ w := &Watcher{ctx: context.Background()}+ got := w.probeStrategy(context.Background(), tmpDir)+ // Non-git dir should probe fsnotify (intent — actual setup may fail).+ if got != strategyFSNotify {+ t.Errorf("expected strategyFSNotify for non-git dir, got %v", got)+ }+}++func TestProbeStrategyOverride(t *testing.T) {+ tmpDir := t.TempDir()++ w := &Watcher{ctx: context.Background(), testStrategy: strategyDirMtime}+ got := w.probeStrategy(context.Background(), tmpDir)+ if got != strategyDirMtime {+ t.Errorf("expected strategyDirMtime with override, got %v", got)+ }+}++// --- Git sentinel unit tests ---++func TestIsGitRepo(t *testing.T) {+ if !gitAvailable() {+ t.Skip("git not available")+ }++ t.Run("git_repo", func(t *testing.T) {+ dir := t.TempDir()+ initGitRepo(t, dir)+ if !isGitRepo(context.Background(), dir) {+ t.Error("expected true for git repo")+ }+ })++ t.Run("non_git", func(t *testing.T) {+ dir := t.TempDir()+ if isGitRepo(context.Background(), dir) {+ t.Error("expected false for non-git dir")+ }+ })+}++func TestGitSentinelClean(t *testing.T) {+ if !gitAvailable() {+ t.Skip("git not available")+ }+ dir := t.TempDir()+ initGitRepo(t, dir)+ mustWriteFile(t, filepath.Join(dir, "main.go"), []byte("package main\n"))+ gitCommitAll(t, dir, "init")++ head, err := gitHead(context.Background(), dir)+ if err != nil {+ t.Fatal(err)+ }++ changed, newHead, err := gitSentinel(context.Background(), dir, head)+ if err != nil {+ t.Fatal(err)+ }+ if changed {+ t.Error("clean repo should not report changes")+ }+ if newHead != head {+ t.Error("HEAD should not change on clean repo")+ }+}++func TestGitSentinelDetectsEdit(t *testing.T) {+ if !gitAvailable() {+ t.Skip("git not available")+ }+ dir := t.TempDir()+ initGitRepo(t, dir)+ goFile := filepath.Join(dir, "main.go")+ mustWriteFile(t, goFile, []byte("package main\n"))+ gitCommitAll(t, dir, "init")++ head, _ := gitHead(context.Background(), dir)++ // Modify tracked file.+ mustWriteFile(t, goFile, []byte("package main\n\nfunc main() {}\n"))++ changed, _, err := gitSentinel(context.Background(), dir, head)+ if err != nil {+ t.Fatal(err)+ }+ if !changed {+ t.Error("modified tracked file should be detected")+ }+}++func TestGitSentinelDetectsNewFile(t *testing.T) {+ if !gitAvailable() {+ t.Skip("git not available")+ }+ dir := t.TempDir()+ initGitRepo(t, dir)+ mustWriteFile(t, filepath.Join(dir, "main.go"), []byte("package main\n"))+ gitCommitAll(t, dir, "init")++ head, _ := gitHead(context.Background(), dir)++ // Add untracked file.+ mustWriteFile(t, filepath.Join(dir, "util.go"), []byte("package main\n"))++ changed, _, err := gitSentinel(context.Background(), dir, head)+ if err != nil {+ t.Fatal(err)+ }+ if !changed {+ t.Error("new untracked file should be detected")+ }+}++func TestGitSentinelDetectsCommit(t *testing.T) {+ if !gitAvailable() {+ t.Skip("git not available")+ }+ dir := t.TempDir()+ initGitRepo(t, dir)+ mustWriteFile(t, filepath.Join(dir, "main.go"), []byte("package main\n"))+ gitCommitAll(t, dir, "init")++ headBefore, _ := gitHead(context.Background(), dir)++ // Make a commit.+ mustWriteFile(t, filepath.Join(dir, "main.go"), []byte("package main\n\nfunc main() {}\n"))+ gitCommitAll(t, dir, "add main")++ changed, newHead, err := gitSentinel(context.Background(), dir, headBefore)+ if err != nil {+ t.Fatal(err)+ }+ if !changed {+ t.Error("commit should be detected via HEAD change")+ }+ if newHead == headBefore {+ t.Error("HEAD should differ after commit")+ }+}++// --- FSNotify sentinel tests ---++func TestFSNotifyDetectsFileCreate(t *testing.T) {+ tmpDir := t.TempDir()+ mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))++ state := &projectState{}+ w := &Watcher{ctx: context.Background()}++ if err := w.initFSNotify(state, tmpDir); err != nil {+ t.Skipf("fsnotify not available: %v", err)+ }+ t.Cleanup(state.close)++ // Create a new file — should trigger an event.+ mustWriteFile(t, filepath.Join(tmpDir, "new.go"), []byte("package main\n"))++ // Wait for the event with timeout.+ deadline := time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) {+ if state.fsChanged.Load() {+ return // success+ }+ time.Sleep(10 * time.Millisecond)+ }+ t.Error("fsnotify did not detect file creation within 2s")+}++func TestFSNotifyDetectsFileDelete(t *testing.T) {+ tmpDir := t.TempDir()+ delFile := filepath.Join(tmpDir, "todelete.go")+ mustWriteFile(t, delFile, []byte("package main\n"))++ state := &projectState{}+ w := &Watcher{ctx: context.Background()}++ if err := w.initFSNotify(state, tmpDir); err != nil {+ t.Skipf("fsnotify not available: %v", err)+ }+ t.Cleanup(state.close)++ os.Remove(delFile)++ deadline := time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) {+ if state.fsChanged.Load() {+ return+ }+ time.Sleep(10 * time.Millisecond)+ }+ t.Error("fsnotify did not detect file deletion within 2s")+}++func TestFSNotifyWatchesNewSubdir(t *testing.T) {+ tmpDir := t.TempDir()+ mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))++ state := &projectState{}+ w := &Watcher{ctx: context.Background()}++ if err := w.initFSNotify(state, tmpDir); err != nil {+ t.Skipf("fsnotify not available: %v", err)+ }+ t.Cleanup(state.close)++ // Create a new subdirectory — drain goroutine should auto-add a watch for it.+ subDir := filepath.Join(tmpDir, "pkg")+ mustMkdirAll(t, subDir)++ // Wait for the dir creation event.+ deadline := time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) {+ if state.fsChanged.Load() {+ break+ }+ time.Sleep(10 * time.Millisecond)+ }++ // Reset flag and create a file in the new subdir.+ state.fsChanged.Store(false)+ time.Sleep(50 * time.Millisecond) // let the Add() complete+ mustWriteFile(t, filepath.Join(subDir, "lib.go"), []byte("package pkg\n"))++ deadline = time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) {+ if state.fsChanged.Load() {+ return+ }+ time.Sleep(10 * time.Millisecond)+ }+ t.Error("fsnotify did not detect file creation in new subdirectory within 2s")+}++func TestFSNotifyCleanup(t *testing.T) {+ tmpDir := t.TempDir()++ state := &projectState{}+ w := &Watcher{ctx: context.Background()}++ if err := w.initFSNotify(state, tmpDir); err != nil {+ t.Skipf("fsnotify not available: %v", err)+ }++ // Verify resources exist.+ if state.fsWatcher == nil || state.fsDone == nil || state.fsCancel == nil {+ t.Fatal("fsnotify resources not initialized")+ }++ // Close and verify goroutine exits.+ state.close()++ if state.fsWatcher != nil || state.fsDone != nil || state.fsCancel != nil {+ t.Error("close() did not nil out resources")+ }+}++func TestFSNotifyNoEventMeansNoChange(t *testing.T) {+ tmpDir := t.TempDir()+ mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))++ state := &projectState{}+ w := &Watcher{ctx: context.Background()}++ if err := w.initFSNotify(state, tmpDir); err != nil {+ t.Skipf("fsnotify not available: %v", err)+ }+ t.Cleanup(state.close)++ // No file changes — flag should remain false.+ time.Sleep(50 * time.Millisecond)+ if state.fsChanged.Load() {+ t.Error("expected no change without file operations")+ }+}++// --- Dir-mtime sentinel tests ---++func TestDirMtimesEqual(t *testing.T) {+ now := time.Now()+ a := map[string]time.Time{"/a": now, "/b": now}+ b := map[string]time.Time{"/a": now, "/b": now}+ if !dirMtimesEqual(a, b) {+ t.Error("identical maps should be equal")+ }++ c := map[string]time.Time{"/a": now.Add(time.Second), "/b": now}+ if dirMtimesEqual(a, c) {+ t.Error("different mtime should not be equal")+ }++ d := map[string]time.Time{"/a": now}+ if dirMtimesEqual(a, d) {+ t.Error("different size should not be equal")+ }+}++// --- Full watcher flow tests (dir-mtime strategy) ---+func TestWatcherTriggersOnChange(t *testing.T) {tmpDir := t.TempDir()goFile := filepath.Join(tmpDir, "main.go")@@ -177,7 +580,6 @@ func TestWatcherTriggersOnChange(t *testing.T) {}r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)- defer r.CloseAll()var indexCount atomic.Int32indexFn := func(_ context.Context, _, _ string) error {@@ -185,7 +587,8 @@ func TestWatcherTriggersOnChange(t *testing.T) {return nil}- w := New(r, indexFn)+ w := newWatcherWithStrategy(r, indexFn, strategyDirMtime)+ t.Cleanup(w.closeAll)// First poll — baseline capture, no indexw.pollAll()@@ -194,10 +597,7 @@ func TestWatcherTriggersOnChange(t *testing.T) {}// Poll again without changes — no index- // Reset nextPoll to allow immediate re-poll- for _, state := range w.projects {- state.nextPoll = time.Time{}- }+ resetPollTimers(w)w.pollAll()if indexCount.Load() != 0 {t.Errorf("no-change poll should not trigger index, got %d", indexCount.Load())@@ -209,9 +609,10 @@ func TestWatcherTriggersOnChange(t *testing.T) {t.Fatal(err)}- // Reset nextPoll and poll again — should trigger+ // Force full snapshot (file mtime change doesn't affect dir mtime)for _, state := range w.projects {state.nextPoll = time.Time{}+ state.pollsSinceFull = fullSnapshotInterval}w.pollAll()if indexCount.Load() != 1 {@@ -219,6 +620,287 @@ func TestWatcherTriggersOnChange(t *testing.T) {}}+func TestWatcherNewFileTriggersIndex_DirMtime(t *testing.T) {+ tmpDir := t.TempDir()+ goFile := filepath.Join(tmpDir, "main.go")+ if err := os.WriteFile(goFile, []byte("package main\n"), 0o600); err != nil {+ t.Fatal(err)+ }++ r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)++ var indexCount atomic.Int32+ w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {+ indexCount.Add(1)+ return nil+ }, strategyDirMtime)+ t.Cleanup(w.closeAll)++ // Baseline+ w.pollAll()++ // Add a new file (changes parent dir mtime)+ if err := os.WriteFile(filepath.Join(tmpDir, "util.go"), []byte("package main\n"), 0o600); err != nil {+ t.Fatal(err)+ }++ resetPollTimers(w)+ w.pollAll()+ if indexCount.Load() != 1 {+ t.Errorf("new file should trigger index, got %d", indexCount.Load())+ }+}++// --- Full watcher flow tests (git strategy) ---++func TestWatcherGitDetectsEdit(t *testing.T) {+ if !gitAvailable() {+ t.Skip("git not available")+ }++ tmpDir := t.TempDir()+ goFile := filepath.Join(tmpDir, "main.go")+ mustWriteFile(t, goFile, []byte("package main\n"))+ initGitRepo(t, tmpDir)+ gitCommitAll(t, tmpDir, "init")++ r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)++ var indexCount atomic.Int32+ w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {+ indexCount.Add(1)+ return nil+ }, strategyGit)+ t.Cleanup(w.closeAll)++ // Baseline+ w.pollAll()+ if indexCount.Load() != 0 {+ t.Fatalf("baseline should not trigger index, got %d", indexCount.Load())+ }++ // Modify tracked file.+ mustWriteFile(t, goFile, []byte("package main\n\nfunc main() {}\n"))++ resetPollTimers(w)+ w.pollAll()+ if indexCount.Load() != 1 {+ t.Errorf("git strategy should detect edit, got index_count=%d", indexCount.Load())+ }+}++func TestWatcherGitDetectsCommit(t *testing.T) {+ if !gitAvailable() {+ t.Skip("git not available")+ }++ tmpDir := t.TempDir()+ goFile := filepath.Join(tmpDir, "main.go")+ mustWriteFile(t, goFile, []byte("package main\n"))+ initGitRepo(t, tmpDir)+ gitCommitAll(t, tmpDir, "init")++ r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)++ var indexCount atomic.Int32+ w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {+ indexCount.Add(1)+ return nil+ }, strategyGit)+ t.Cleanup(w.closeAll)++ // Baseline+ w.pollAll()++ // Make a commit (modifies HEAD but working tree is clean after).+ mustWriteFile(t, goFile, []byte("package main\n\nfunc main() {}\n"))+ gitCommitAll(t, tmpDir, "add main func")++ resetPollTimers(w)+ w.pollAll()+ if indexCount.Load() != 1 {+ t.Errorf("git strategy should detect commit via HEAD change, got %d", indexCount.Load())+ }+}++func TestWatcherGitNoChanges(t *testing.T) {+ if !gitAvailable() {+ t.Skip("git not available")+ }++ tmpDir := t.TempDir()+ mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))+ initGitRepo(t, tmpDir)+ gitCommitAll(t, tmpDir, "init")++ r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)++ var indexCount atomic.Int32+ w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {+ indexCount.Add(1)+ return nil+ }, strategyGit)+ t.Cleanup(w.closeAll)++ // Baseline+ w.pollAll()++ // Poll again without changes — no index. Git strategy does NOT force full snapshot.+ resetPollTimers(w)+ w.pollAll()+ if indexCount.Load() != 0 {+ t.Errorf("clean git repo should not trigger index, got %d", indexCount.Load())+ }++ // Even after many polls, no forced full snapshot (git is authoritative).+ for i := 0; i < fullSnapshotInterval+2; i++ {+ resetPollTimers(w)+ w.pollAll()+ }+ if indexCount.Load() != 0 {+ t.Errorf("git strategy should never force full snapshot, got %d", indexCount.Load())+ }+}++// --- Full watcher flow tests (fsnotify strategy) ---++func TestWatcherFSNotifyDetectsNewFile(t *testing.T) {+ tmpDir := t.TempDir()+ mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))++ r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)++ var indexCount atomic.Int32+ w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {+ indexCount.Add(1)+ return nil+ }, strategyFSNotify)+ t.Cleanup(w.closeAll)++ // Baseline (sets up fsnotify watcher).+ w.pollAll()+ projName := filepath.Base(tmpDir)+ state := w.projects[projName]+ if state == nil {+ t.Fatal("project state not created")+ }+ if state.strategy != strategyFSNotify && state.strategy != strategyDirMtime {+ t.Fatalf("unexpected strategy: %v", state.strategy)+ }+ if state.strategy == strategyDirMtime {+ t.Skip("fsnotify not available, fell back to dirmtime")+ }++ // Create a new file.+ mustWriteFile(t, filepath.Join(tmpDir, "util.go"), []byte("package main\n"))++ // Wait for fsnotify event.+ deadline := time.Now().Add(2 * time.Second)+ for time.Now().Before(deadline) {+ if state.fsChanged.Load() {+ break+ }+ time.Sleep(10 * time.Millisecond)+ }++ resetPollTimers(w)+ w.pollAll()+ if indexCount.Load() != 1 {+ t.Errorf("fsnotify strategy should detect new file, got %d", indexCount.Load())+ }+}++// --- Fallback / degradation tests ---++func TestStrategyDowngradeGitToDirMtime(t *testing.T) {+ if !gitAvailable() {+ t.Skip("git not available")+ }++ tmpDir := t.TempDir()+ mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))+ initGitRepo(t, tmpDir)+ gitCommitAll(t, tmpDir, "init")++ r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)++ var indexCount atomic.Int32+ w := New(r, func(_ context.Context, _, _ string) error {+ indexCount.Add(1)+ return nil+ })+ t.Cleanup(w.closeAll)++ // Baseline — should auto-detect git strategy.+ w.pollAll()+ projName := filepath.Base(tmpDir)+ state := w.projects[projName]+ if state == nil {+ t.Fatal("project state not created")+ }+ if state.strategy != strategyGit {+ t.Fatalf("expected strategyGit, got %v", state.strategy)+ }++ // Remove .git directory — git commands will fail.+ os.RemoveAll(filepath.Join(tmpDir, ".git"))++ // Modify a file so the full snapshot comparison triggers.+ mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n\nfunc main() {}\n"))++ resetPollTimers(w)+ w.pollAll()++ // Strategy should have downgraded (git failed → fsnotify or dirmtime).+ if state.strategy == strategyGit {+ t.Error("strategy should have downgraded from git after .git removal")+ }+}++func TestFSNotifyFallbackToDirMtime(t *testing.T) {+ // When fsnotify is the selected strategy but initFSNotify fails,+ // baseline should fall back to dirmtime.+ tmpDir := t.TempDir()+ mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))++ r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)++ var indexCount atomic.Int32+ w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {+ indexCount.Add(1)+ return nil+ }, strategyFSNotify)+ t.Cleanup(w.closeAll)++ // initBaseline will try fsnotify. Even if it succeeds, verify the flow works.+ // If fsnotify fails on this platform, it falls back to dirmtime.+ w.pollAll()++ projName := filepath.Base(tmpDir)+ state := w.projects[projName]+ if state == nil {+ t.Fatal("project state not created")+ }++ // Either fsnotify or dirmtime is acceptable.+ if state.strategy != strategyFSNotify && state.strategy != strategyDirMtime {+ t.Errorf("expected fsnotify or dirmtime, got %v", state.strategy)+ }++ // Regardless of strategy, adding a file and forcing full snapshot should work.+ mustWriteFile(t, filepath.Join(tmpDir, "new.go"), []byte("package main\n"))+ for _, s := range w.projects {+ s.nextPoll = time.Time{}+ s.pollsSinceFull = fullSnapshotInterval+ }+ w.pollAll()+ if indexCount.Load() != 1 {+ t.Errorf("should detect change with fallback strategy, got %d", indexCount.Load())+ }+}++// --- Lifecycle tests ---+func TestWatcherCancellation(t *testing.T) {dbDir := t.TempDir()r, err := store.NewRouterWithDir(dbDir)@@ -249,13 +931,13 @@ func TestWatcherCancellation(t *testing.T) {func TestWatcherSkipsMissingRoot(t *testing.T) {r := newTestRouter(t, "ghost", "/nonexistent/path")- defer r.CloseAll()var indexCount atomic.Int32w := New(r, func(_ context.Context, _, _ string) error {indexCount.Add(1)return nil})+ t.Cleanup(w.closeAll)w.pollAll()if indexCount.Load() != 0 {@@ -263,35 +945,34 @@ func TestWatcherSkipsMissingRoot(t *testing.T) {}}-func TestWatcherNewFileTriggersIndex(t *testing.T) {+func TestWatcherPrunesDeletedProjects(t *testing.T) {tmpDir := t.TempDir()- goFile := filepath.Join(tmpDir, "main.go")- if err := os.WriteFile(goFile, []byte("package main\n"), 0o600); err != nil {- t.Fatal(err)- }+ mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))r := newTestRouter(t, filepath.Base(tmpDir), tmpDir)- defer r.CloseAll()- var indexCount atomic.Int32- w := New(r, func(_ context.Context, _, _ string) error {- indexCount.Add(1)+ w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {return nil- })+ }, strategyDirMtime)+ t.Cleanup(w.closeAll)// Baselinew.pollAll()+ projName := filepath.Base(tmpDir)+ if _, ok := w.projects[projName]; !ok {+ t.Fatal("project should exist after baseline")+ }- // Add a new file- if err := os.WriteFile(filepath.Join(tmpDir, "util.go"), []byte("package main\n"), 0o600); err != nil {+ // Delete the project.+ if err := r.DeleteProject(projName); err != nil {t.Fatal(err)}- for _, state := range w.projects {- state.nextPoll = time.Time{}- }+ // Invalidate cache so next pollAll sees the deletion.+ w.InvalidateProjectsCache()w.pollAll()- if indexCount.Load() != 1 {- t.Errorf("new file should trigger index, got %d", indexCount.Load())++ if _, ok := w.projects[projName]; ok {+ t.Error("pruned project should not exist in watcher state")}}