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
Replace scan-all watcher with explicit watch list to fix #49 OOM
Martin Vogel0c80a37b08c2
diff --git a/internal/tools/index.go b/internal/tools/index.goindex 6fdbe3a3c..0bb357225 100644--- a/internal/tools/index.go+++ b/internal/tools/index.go@@ -61,6 +61,9 @@ func (s *Server) handleIndexRepository(ctx context.Context, req *mcp.CallToolReqreturn errResult(fmt.Sprintf("indexing failed: %v", err)), nil}+ // Add to watcher so auto-sync keeps this project fresh.+ s.watcher.Watch(projectName, absPath)+// Update session state if this is the session projectif projectName == s.sessionProject {s.indexStatus.Store("ready")diff --git a/internal/tools/projects.go b/internal/tools/projects.goindex b9dab1a7e..a4fd5ecea 100644--- a/internal/tools/projects.go+++ b/internal/tools/projects.go@@ -84,6 +84,7 @@ func (s *Server) handleDeleteProject(_ context.Context, req *mcp.CallToolRequestif err := s.router.DeleteProject(name); err != nil {return errResult(fmt.Sprintf("delete failed: %v", err)), nil}+ s.watcher.Unwatch(name)return jsonResult(map[string]any{"deleted": name,diff --git a/internal/tools/tools.go b/internal/tools/tools.goindex 4b28e9e62..5f1fcfda3 100644--- a/internal/tools/tools.go+++ b/internal/tools/tools.go@@ -282,6 +282,7 @@ func (s *Server) startAutoIndex() {return}s.indexStatus.Store("ready")+ s.watcher.Watch(s.sessionProject, s.sessionRoot)slog.Info("autoindex.done", "project", s.sessionProject)}()}@@ -302,6 +303,10 @@ func (s *Server) resolveStore(project string) (*store.Store, error) {if !s.router.HasProject(project) {return nil, fmt.Errorf("project %q not found; use list_projects to see available projects", project)}+ // Touch watcher so cross-project queries keep that project fresh.+ if project != s.sessionProject {+ s.watcher.TouchProject(project)+ }return s.router.ForProject(project)}@@ -907,6 +912,10 @@ func (s *Server) findNodeAcrossProjects(name string, projectFilter ...string) (*if !s.router.HasProject(filter) {return nil, "", fmt.Errorf("project %q not found; use list_projects to see available projects", filter)}+ // Touch watcher so cross-project queries keep that project fresh.+ if filter != s.sessionProject {+ s.watcher.TouchProject(filter)+ }st, err := s.router.ForProject(filter)if err != nil {diff --git a/internal/watcher/watcher.go b/internal/watcher/watcher.goindex a8e5fdf97..cfb9c63c5 100644--- a/internal/watcher/watcher.go+++ b/internal/watcher/watcher.go@@ -9,6 +9,7 @@ import ("os/exec""path/filepath""strings"+ "sync""sync/atomic""time"@@ -45,7 +46,6 @@ const (baseInterval = 5 * time.SecondmaxInterval = 60 * time.SecondfullSnapshotInterval = 5 // polls between forced full snapshots- projectsCacheTTL = 60 * time.Second)type fileSnapshot struct {@@ -94,6 +94,12 @@ func (ps *projectState) close() {// IndexFunc is the callback signature for triggering a re-index.type IndexFunc func(ctx context.Context, projectName, rootPath string) error+// watchEntry tracks a project in the explicit watch list.+type watchEntry struct {+ rootPath string+ touchedAt time.Time+}+// Watcher polls indexed projects for file changes and triggers re-indexing.// Change detection uses a 3-tier strategy per project://@@ -101,12 +107,14 @@ type IndexFunc func(ctx context.Context, projectName, rootPath string) error// 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- cachedProjects []*store.ProjectInfo- projectsCacheTime time.Time+ router *store.StoreRouter+ indexFn IndexFunc+ projects map[string]*projectState+ ctx context.Context++ // Explicit watch list — only watched projects get polled.+ mu sync.Mutex+ watchList map[string]watchEntry// testStrategy overrides auto-detection when non-zero (for tests).testStrategy watchStrategy@@ -114,20 +122,53 @@ type Watcher struct {// New creates a Watcher. indexFn is called when file changes are detected.func New(r *store.StoreRouter, indexFn IndexFunc) *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+ return &Watcher{+ router: r,+ indexFn: indexFn,+ projects: make(map[string]*projectState),+ watchList: make(map[string]watchEntry),+ ctx: context.Background(),+ }+}++// Watch adds a project to the watch list. Called after successful index.+func (w *Watcher) Watch(name, rootPath string) {+ w.mu.Lock()+ defer w.mu.Unlock()+ w.watchList[name] = watchEntry{rootPath: rootPath, touchedAt: time.Now()}+ slog.Debug("watcher.watch", "project", name, "path", rootPath)}-// InvalidateProjectsCache forces the next pollAll to re-query ListProjects.-func (w *Watcher) InvalidateProjectsCache() {- w.projectsCacheTime = time.Time{}+// Unwatch removes a project from the watch list. Called on delete.+func (w *Watcher) Unwatch(name string) {+ w.mu.Lock()+ defer w.mu.Unlock()+ delete(w.watchList, name)+ slog.Debug("watcher.unwatch", "project", name)+}++// TouchProject refreshes a project's timestamp in the watch list.+// If the project isn't watched yet, adds it (looks up rootPath from DB).+func (w *Watcher) TouchProject(name string) {+ w.mu.Lock()+ defer w.mu.Unlock()+ if e, ok := w.watchList[name]; ok {+ e.touchedAt = time.Now()+ w.watchList[name] = e+ return+ }+ // Not yet watched — look up rootPath from DB.+ st, release, err := w.router.AcquireStore(name)+ if err != nil {+ return+ }+ proj, projErr := st.GetProject(name)+ release()+ if projErr != nil || proj == nil || proj.RootPath == "" {+ return+ }+ w.watchList[name] = watchEntry{rootPath: proj.RootPath, touchedAt: time.Now()}+ slog.Debug("watcher.touch_add", "project", name, "path", proj.RootPath)}// Run blocks until ctx is cancelled. Ticks at baseInterval, polling each@@ -155,28 +196,20 @@ func (w *Watcher) closeAll() {}}-// pollAll lists all indexed projects and polls each that is due.-// Prunes watcher state for projects that no longer exist.+// pollAll iterates the explicit watch list and polls each project that is due.+// Prunes watcher state for unwatched projects.func (w *Watcher) pollAll() {- // 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()+ w.mu.Lock()+ // Copy watch list under lock to avoid holding lock during poll.+ entries := make(map[string]watchEntry, len(w.watchList))+ for k, v := range w.watchList {+ entries[k] = v}- projectInfos := w.cachedProjects+ w.mu.Unlock()- // Prune stale entries.- activeNames := make(map[string]struct{}, len(projectInfos))- for _, info := range projectInfos {- activeNames[info.Name] = struct{}{}- }+ // Prune projectState for unwatched projects.for name, state := range w.projects {- if _, ok := activeNames[name]; !ok {+ if _, ok := entries[name]; !ok {slog.Info("watcher.prune", "project", name)state.close()delete(w.projects, name)@@ -184,26 +217,30 @@ func (w *Watcher) pollAll() {}now := time.Now()- for _, info := range projectInfos {- state, exists := w.projects[info.Name]+ for name, entry := range entries {+ state, exists := w.projects[name]if exists && now.Before(state.nextPoll) {- continue // not due yet+ continue}- // AcquireStore increments refs so the evictor can't close mid-query.- st, release, stErr := w.router.AcquireStore(info.Name)+ st, release, stErr := w.router.AcquireStore(name)if stErr != nil {continue}- proj, projErr := st.GetProject(info.Name)+ proj, projErr := st.GetProject(name)release()if projErr != nil || proj == nil {continue}+ // Use rootPath from watch list (most current).+ if entry.rootPath != "" {+ proj.RootPath = entry.rootPath+ }+if !exists {state = &projectState{}- w.projects[info.Name] = state+ w.projects[name] = state}w.pollProject(proj, state)diff --git a/internal/watcher/watcher_test.go b/internal/watcher/watcher_test.goindex 7aec630fe..a105f0aac 100644--- a/internal/watcher/watcher_test.go+++ b/internal/watcher/watcher_test.go@@ -590,6 +590,9 @@ func TestWatcherTriggersOnChange(t *testing.T) {w := newWatcherWithStrategy(r, indexFn, strategyDirMtime)t.Cleanup(w.closeAll)+ // Add to watch list (required for pollAll to see it).+ w.Watch(filepath.Base(tmpDir), tmpDir)+// First poll — baseline capture, no indexw.pollAll()if indexCount.Load() != 0 {@@ -635,6 +638,7 @@ func TestWatcherNewFileTriggersIndex_DirMtime(t *testing.T) {return nil}, strategyDirMtime)t.Cleanup(w.closeAll)+ w.Watch(filepath.Base(tmpDir), tmpDir)// Baselinew.pollAll()@@ -672,6 +676,7 @@ func TestWatcherGitDetectsEdit(t *testing.T) {return nil}, strategyGit)t.Cleanup(w.closeAll)+ w.Watch(filepath.Base(tmpDir), tmpDir)// Baselinew.pollAll()@@ -708,6 +713,7 @@ func TestWatcherGitDetectsCommit(t *testing.T) {return nil}, strategyGit)t.Cleanup(w.closeAll)+ w.Watch(filepath.Base(tmpDir), tmpDir)// Baselinew.pollAll()@@ -741,6 +747,7 @@ func TestWatcherGitNoChanges(t *testing.T) {return nil}, strategyGit)t.Cleanup(w.closeAll)+ w.Watch(filepath.Base(tmpDir), tmpDir)// Baselinew.pollAll()@@ -776,6 +783,7 @@ func TestWatcherFSNotifyDetectsNewFile(t *testing.T) {return nil}, strategyFSNotify)t.Cleanup(w.closeAll)+ w.Watch(filepath.Base(tmpDir), tmpDir)// Baseline (sets up fsnotify watcher).w.pollAll()@@ -830,6 +838,7 @@ func TestStrategyDowngradeGitToDirMtime(t *testing.T) {return nil})t.Cleanup(w.closeAll)+ w.Watch(filepath.Base(tmpDir), tmpDir)// Baseline — should auto-detect git strategy.w.pollAll()@@ -871,6 +880,7 @@ func TestFSNotifyFallbackToDirMtime(t *testing.T) {return nil}, strategyFSNotify)t.Cleanup(w.closeAll)+ w.Watch(filepath.Base(tmpDir), tmpDir)// initBaseline will try fsnotify. Even if it succeeds, verify the flow works.// If fsnotify fails on this platform, it falls back to dirmtime.@@ -938,6 +948,7 @@ func TestWatcherSkipsMissingRoot(t *testing.T) {return nil})t.Cleanup(w.closeAll)+ w.Watch("ghost", "/nonexistent/path")w.pollAll()if indexCount.Load() != 0 {@@ -956,23 +967,184 @@ func TestWatcherPrunesDeletedProjects(t *testing.T) {}, strategyDirMtime)t.Cleanup(w.closeAll)+ projName := filepath.Base(tmpDir)+ w.Watch(projName, tmpDir)+// Baselinew.pollAll()- projName := filepath.Base(tmpDir)if _, ok := w.projects[projName]; !ok {t.Fatal("project should exist after baseline")}- // Delete the project.+ // Delete the project and unwatch.if err := r.DeleteProject(projName); err != nil {t.Fatal(err)}+ w.Unwatch(projName)- // Invalidate cache so next pollAll sees the deletion.- w.InvalidateProjectsCache()w.pollAll()if _, ok := w.projects[projName]; ok {t.Error("pruned project should not exist in watcher state")}}++// --- Watch list unit tests ---++func TestWatchAddsProject(t *testing.T) {+ r := newTestRouter(t, "", "")+ w := New(r, func(_ context.Context, _, _ string) error { return nil })++ w.Watch("foo", "/tmp/foo")++ w.mu.Lock()+ defer w.mu.Unlock()+ e, ok := w.watchList["foo"]+ if !ok {+ t.Fatal("Watch should add entry to watchList")+ }+ if e.rootPath != "/tmp/foo" {+ t.Errorf("rootPath = %q, want /tmp/foo", e.rootPath)+ }+ if e.touchedAt.IsZero() {+ t.Error("touchedAt should be set")+ }+}++func TestUnwatchRemovesProject(t *testing.T) {+ r := newTestRouter(t, "", "")+ w := New(r, func(_ context.Context, _, _ string) error { return nil })++ w.Watch("foo", "/tmp/foo")+ w.Unwatch("foo")++ w.mu.Lock()+ defer w.mu.Unlock()+ if _, ok := w.watchList["foo"]; ok {+ t.Error("Unwatch should remove entry from watchList")+ }+}++func TestTouchProjectUpdatesTimestamp(t *testing.T) {+ r := newTestRouter(t, "", "")+ w := New(r, func(_ context.Context, _, _ string) error { return nil })++ w.Watch("foo", "/tmp/foo")++ w.mu.Lock()+ before := w.watchList["foo"].touchedAt+ w.mu.Unlock()++ time.Sleep(5 * time.Millisecond)+ w.TouchProject("foo")++ w.mu.Lock()+ after := w.watchList["foo"].touchedAt+ w.mu.Unlock()++ if !after.After(before) {+ t.Error("TouchProject should update touchedAt")+ }+}++func TestTouchProjectAddsUnwatched(t *testing.T) {+ tmpDir := t.TempDir()+ projName := filepath.Base(tmpDir)++ r := newTestRouter(t, projName, tmpDir)+ w := New(r, func(_ context.Context, _, _ string) error { return nil })++ // Not in watch list yet — TouchProject should look up from DB and add.+ w.TouchProject(projName)++ w.mu.Lock()+ defer w.mu.Unlock()+ e, ok := w.watchList[projName]+ if !ok {+ t.Fatal("TouchProject should add unwatched project from DB")+ }+ if e.rootPath != tmpDir {+ t.Errorf("rootPath = %q, want %q", e.rootPath, tmpDir)+ }+}++func TestPollAllOnlyWatched(t *testing.T) {+ tmpDirA := t.TempDir()+ mustWriteFile(t, filepath.Join(tmpDirA, "main.go"), []byte("package main\n"))+ nameA := filepath.Base(tmpDirA)++ tmpDirB := t.TempDir()+ mustWriteFile(t, filepath.Join(tmpDirB, "main.go"), []byte("package main\n"))+ nameB := filepath.Base(tmpDirB)++ // Register both in DB.+ dbDir := t.TempDir()+ r, err := store.NewRouterWithDir(dbDir)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(r.CloseAll)+ stA, err2 := r.ForProject(nameA)+ if err2 != nil {+ t.Fatal(err2)+ }+ if err2 = stA.UpsertProject(nameA, tmpDirA); err2 != nil {+ t.Fatal(err2)+ }+ stB, err2 := r.ForProject(nameB)+ if err2 != nil {+ t.Fatal(err2)+ }+ if err2 = stB.UpsertProject(nameB, tmpDirB); err2 != nil {+ t.Fatal(err2)+ }++ polled := make(map[string]bool)+ w := newWatcherWithStrategy(r, func(_ context.Context, name, _ string) error {+ polled[name] = true+ return nil+ }, strategyDirMtime)+ t.Cleanup(w.closeAll)++ // Only watch A.+ w.Watch(nameA, tmpDirA)++ // Baseline+ w.pollAll()++ // Verify only A has state.+ if _, ok := w.projects[nameA]; !ok {+ t.Error("project A should have state after poll")+ }+ if _, ok := w.projects[nameB]; ok {+ t.Error("project B should NOT have state (not watched)")+ }+}++func TestPollAllPrunesUnwatched(t *testing.T) {+ tmpDir := t.TempDir()+ mustWriteFile(t, filepath.Join(tmpDir, "main.go"), []byte("package main\n"))+ projName := filepath.Base(tmpDir)++ r := newTestRouter(t, projName, tmpDir)+ w := newWatcherWithStrategy(r, func(_ context.Context, _, _ string) error {+ return nil+ }, strategyDirMtime)+ t.Cleanup(w.closeAll)++ w.Watch(projName, tmpDir)++ // Baseline — creates projectState.+ w.pollAll()+ if _, ok := w.projects[projName]; !ok {+ t.Fatal("project should exist after baseline")+ }++ // Unwatch, then poll — state should be pruned.+ w.Unwatch(projName)+ w.pollAll()++ if _, ok := w.projects[projName]; ok {+ t.Error("unwatched project should be pruned from projects map")+ }+}