Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): clean stale agent branches during repo gc (MUL-2550) (#3039)
0xMomoef75f80d9d88
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex d38c14dc37..243537cc9e 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -81,6 +81,7 @@ type workspaceState struct {type repoCacheBackend interface {Lookup(workspaceID, url string) stringSync(workspaceID string, repos []repocache.RepoInfo) error+ WithRepoLock(barePath string, fn func() error) errorCreateWorktree(params repocache.WorktreeParams) (*repocache.WorktreeResult, error)}diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex a4e2c93100..9e937c4d50 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -564,7 +564,10 @@ func dirSize(root string) int64 {return total}-const gitCmdTimeout = 30 * time.Second+const (+ gitCmdTimeout = 30 * time.Second+ gitMaintenanceTimeout = 10 * time.Minute+)// pruneRepoWorktrees runs `git worktree prune` on all bare repos in the cache.func (d *Daemon) pruneRepoWorktrees(workspacesRoot string) {@@ -597,17 +600,140 @@ func (d *Daemon) pruneRepoWorktrees(workspacesRoot string) {}func (d *Daemon) pruneWorktree(barePath string) {- ctx, cancel := context.WithTimeout(context.Background(), gitCmdTimeout)- defer cancel()- cmd := exec.CommandContext(ctx, "git", "-C", barePath, "worktree", "prune")+ if d.repoCache != nil {+ if err := d.repoCache.WithRepoLock(barePath, func() error {+ d.pruneWorktreeLocked(barePath)+ return nil+ }); err != nil {+ d.logger.Warn("gc: repo lock failed", "repo", barePath, "error", err)+ return+ }+ return+ }++ d.pruneWorktreeLocked(barePath)+}- if out, err := cmd.CombinedOutput(); err != nil {+func (d *Daemon) pruneWorktreeLocked(barePath string) {+ if out, err := runGitGCCommand(barePath, "worktree", "prune"); err != nil {d.logger.Warn("gc: worktree prune failed","repo", barePath,- "output", strings.TrimSpace(string(out)),+ "output", out,"error", err,)}++ activeBranches, err := agentWorktreeBranches(barePath)+ if err != nil {+ d.logger.Warn("gc: worktree branch scan failed", "repo", barePath, "error", err)+ return+ }++ agentBranches, err := listAgentBranches(barePath)+ if err != nil {+ d.logger.Warn("gc: agent branch scan failed", "repo", barePath, "error", err)+ return+ }++ deleted := 0+ for _, branch := range agentBranches {+ if _, ok := activeBranches[branch]; ok {+ continue+ }+ if out, err := runGitGCCommand(barePath, "branch", "-D", "--", branch); err != nil {+ d.logger.Warn("gc: agent branch delete failed",+ "repo", barePath,+ "branch", branch,+ "output", out,+ "error", err,+ )+ continue+ }+ deleted+++ }+ if deleted == 0 {+ return+ }+ d.logger.Info("gc: deleted stale agent branches", "repo", barePath, "count", deleted)++ // Heavier maintenance only runs when we actually removed refs, so we don't+ // turn every GC tick into a full `git gc --prune` on every cached repo. The+ // prune step gets its own longer timeout because it can take minutes on a+ // real bare cache; under the shared 30s budget it would be killed mid-run.+ maintenance := []struct {+ args []string+ timeout time.Duration+ }{+ {args: []string{"reflog", "expire", "--expire=30.days", "--all"}, timeout: gitCmdTimeout},+ {args: []string{"gc", "--prune=30.days"}, timeout: gitMaintenanceTimeout},+ }+ for _, step := range maintenance {+ if out, err := runGitCommand(barePath, step.timeout, step.args...); err != nil {+ d.logger.Warn("gc: git maintenance failed",+ "repo", barePath,+ "command", strings.Join(step.args, " "),+ "output", out,+ "error", err,+ )+ }+ }+}++func runGitGCCommand(barePath string, args ...string) (string, error) {+ return runGitCommand(barePath, gitCmdTimeout, args...)+}++func runGitCommand(barePath string, timeout time.Duration, args ...string) (string, error) {+ ctx, cancel := context.WithTimeout(context.Background(), timeout)+ defer cancel()++ cmdArgs := append([]string{"-C", barePath}, args...)+ cmd := exec.CommandContext(ctx, "git", cmdArgs...)+ out, err := cmd.CombinedOutput()+ return strings.TrimSpace(string(out)), err+}++func agentWorktreeBranches(barePath string) (map[string]struct{}, error) {+ out, err := runGitGCCommand(barePath, "worktree", "list", "--porcelain")+ if err != nil {+ return nil, err+ }++ branches := make(map[string]struct{})+ for _, line := range strings.Split(out, "\n") {+ line = strings.TrimSpace(line)+ if !strings.HasPrefix(line, "branch refs/heads/") {+ continue+ }+ branch := strings.TrimPrefix(line, "branch refs/heads/")+ if strings.HasPrefix(branch, "agent/") {+ branches[branch] = struct{}{}+ }+ }+ return branches, nil+}++func listAgentBranches(barePath string) ([]string, error) {+ // Trailing slash narrows the pattern to the `agent/` namespace only. Without+ // it, `for-each-ref` would also return a branch literally named `agent`,+ // which `agentWorktreeBranches` ignores — that branch would then be deleted.+ out, err := runGitGCCommand(barePath, "for-each-ref", "--format=%(refname:short)", "refs/heads/agent/")+ if err != nil {+ return nil, err+ }+ if out == "" {+ return nil, nil+ }++ var branches []string+ for _, line := range strings.Split(out, "\n") {+ branch := strings.TrimSpace(line)+ if branch == "" {+ continue+ }+ branches = append(branches, branch)+ }+ return branches, nil}// isBareRepo checks if a path looks like a bare git repository.diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.goindex d826c1864d..f89b2f3e9d 100644--- a/server/internal/daemon/gc_test.go+++ b/server/internal/daemon/gc_test.go@@ -8,11 +8,14 @@ import ("net/http""net/http/httptest""os"+ "os/exec""path/filepath"+ "strings""testing""time""github.com/multica-ai/multica/server/internal/daemon/execenv"+ "github.com/multica-ai/multica/server/internal/daemon/repocache")// newGCTestDaemon creates a minimal Daemon for GC testing with a mock HTTP server.@@ -654,6 +657,218 @@ func TestIsBareRepo(t *testing.T) {})}+func TestPruneWorktree_RemovesOnlyStaleAgentBranches(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ sourceRepo := createGCGitRepo(t)+ barePath := filepath.Join(t.TempDir(), "cache.git")++ runGitForGC(t, "", "clone", "--bare", sourceRepo, barePath)++ activeWorktree := filepath.Join(t.TempDir(), "active")+ activeBranch := "agent/live/12345678"+ staleBranch := "agent/stale/87654321"+ keepBranch := "main"++ runGitForGC(t, "", "-C", barePath, "worktree", "add", "-b", activeBranch, activeWorktree, "HEAD")+ runGitForGC(t, "", "-C", barePath, "branch", staleBranch, "HEAD")++ d.pruneWorktree(barePath)++ if gitRefExists(t, barePath, "refs/heads/"+staleBranch) {+ t.Fatalf("expected stale branch %q to be deleted", staleBranch)+ }+ if !gitRefExists(t, barePath, "refs/heads/"+activeBranch) {+ t.Fatalf("expected active branch %q to be preserved", activeBranch)+ }+ if !gitRefExists(t, barePath, "refs/heads/"+keepBranch) {+ t.Fatalf("expected non-agent branch %q to be preserved", keepBranch)+ }+}++// TestPruneWorktree_IgnoresLiteralAgentBranch ensures the GC pattern is scoped+// to the `agent/` namespace. A repo whose only `agent`-shaped ref is the+// literal `refs/heads/agent` (no slash) must be left untouched — the+// `for-each-ref` query is narrowed to `refs/heads/agent/` for that reason.+func TestPruneWorktree_IgnoresLiteralAgentBranch(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ sourceRepo := createGCGitRepo(t)+ barePath := filepath.Join(t.TempDir(), "cache.git")++ runGitForGC(t, "", "clone", "--bare", sourceRepo, barePath)+ runGitForGC(t, "", "-C", barePath, "branch", "agent", "HEAD")++ d.pruneWorktree(barePath)++ if !gitRefExists(t, barePath, "refs/heads/agent") {+ t.Fatal("expected literal `agent` branch outside the daemon namespace to be preserved")+ }+}++// TestPruneWorktree_SkipsMaintenanceWhenNothingDeleted pins the gate that+// keeps the heavy `gc --prune` step from running on every GC tick. Uses an+// unreachable loose blob backdated past the prune horizon as a sentinel: it+// survives when no agent branch was deleted (no maintenance), and disappears+// once a stale agent branch is reaped (maintenance ran).+func TestPruneWorktree_SkipsMaintenanceWhenNothingDeleted(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ sourceRepo := createGCGitRepo(t)+ barePath := filepath.Join(t.TempDir(), "cache.git")++ runGitForGC(t, "", "clone", "--bare", sourceRepo, barePath)++ // Park an active agent worktree so the scan has something to filter, and+ // to make sure pruneWorktree exercises the full code path.+ activeWorktree := filepath.Join(t.TempDir(), "active")+ runGitForGC(t, "", "-C", barePath, "worktree", "add", "-b", "agent/live/12345678", activeWorktree, "HEAD")++ sentinelPath := writeOldLooseBlob(t, barePath, "sentinel-content", 60*24*time.Hour)++ // No stale agent branch → no deletion → no `gc --prune`. The sentinel+ // blob must survive.+ d.pruneWorktree(barePath)+ if _, err := os.Stat(sentinelPath); err != nil {+ t.Fatalf("expected sentinel blob to survive when nothing was deleted: %v", err)+ }++ // Introduce a stale agent branch → deletion happens → maintenance runs →+ // `gc --prune=30.days` reaps the sentinel blob.+ runGitForGC(t, "", "-C", barePath, "branch", "agent/stale/87654321", "HEAD")+ d.pruneWorktree(barePath)+ if _, err := os.Stat(sentinelPath); !os.IsNotExist(err) {+ t.Fatalf("expected sentinel blob to be pruned after maintenance ran, stat err=%v", err)+ }+}++// writeOldLooseBlob writes a dangling loose-object blob to the bare repo and+// backdates its mtime so `git gc --prune=30.days` will consider it prunable.+// Returns the absolute path to the loose object on disk.+func writeOldLooseBlob(t *testing.T, barePath, content string, age time.Duration) string {+ t.Helper()+ cmd := exec.Command("git", "-C", barePath, "hash-object", "-w", "--stdin")+ cmd.Stdin = strings.NewReader(content)+ out, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("hash-object failed: %v: %s", err, out)+ }+ sha := strings.TrimSpace(string(out))+ if len(sha) < 4 {+ t.Fatalf("unexpected sha output: %q", sha)+ }+ loose := filepath.Join(barePath, "objects", sha[:2], sha[2:])+ if _, err := os.Stat(loose); err != nil {+ t.Fatalf("expected loose object at %s: %v", loose, err)+ }+ old := time.Now().Add(-age)+ if err := os.Chtimes(loose, old, old); err != nil {+ t.Fatalf("chtimes failed: %v", err)+ }+ return loose+}++func TestPruneWorktree_SerializesWithCreateWorktree(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ sourceRepo := createGCGitRepo(t)+ cache := repocache.New(filepath.Join(d.cfg.WorkspacesRoot, ".repos"), slog.Default())+ if err := cache.Sync("ws1", []repocache.RepoInfo{{URL: sourceRepo}}); err != nil {+ t.Fatalf("cache sync failed: %v", err)+ }++ barePath := cache.Lookup("ws1", sourceRepo)+ if barePath == "" {+ t.Fatal("expected bare repo to be cached")+ }++ runGitForGC(t, "", "-C", barePath, "branch", "agent/stale/87654321", "HEAD")++ blockingCache := &blockingRepoCache{+ inner: cache,+ entered: make(chan struct{}),+ release: make(chan struct{}),+ }+ d.repoCache = blockingCache++ pruneDone := make(chan struct{})+ go func() {+ d.pruneWorktree(barePath)+ close(pruneDone)+ }()++ select {+ case <-blockingCache.entered:+ case <-time.After(5 * time.Second):+ t.Fatal("timed out waiting for pruneWorktree to acquire repo lock")+ }++ createDone := make(chan error, 1)+ go func() {+ _, err := blockingCache.CreateWorktree(repocache.WorktreeParams{+ WorkspaceID: "ws1",+ RepoURL: sourceRepo,+ WorkDir: t.TempDir(),+ AgentName: "tester",+ TaskID: "11111111-1111-1111-1111-111111111111",+ })+ createDone <- err+ }()++ select {+ case err := <-createDone:+ t.Fatalf("CreateWorktree should wait for GC lock, returned early with err=%v", err)+ case <-time.After(200 * time.Millisecond):+ }++ close(blockingCache.release)++ select {+ case err := <-createDone:+ if err != nil {+ t.Fatalf("CreateWorktree failed after GC lock released: %v", err)+ }+ case <-time.After(5 * time.Second):+ t.Fatal("timed out waiting for CreateWorktree after releasing GC lock")+ }++ select {+ case <-pruneDone:+ case <-time.After(5 * time.Second):+ t.Fatal("timed out waiting for pruneWorktree to finish")+ }+}++type blockingRepoCache struct {+ inner *repocache.Cache+ entered chan struct{}+ release chan struct{}+}++func (c *blockingRepoCache) Lookup(workspaceID, url string) string {+ return c.inner.Lookup(workspaceID, url)+}++func (c *blockingRepoCache) Sync(workspaceID string, repos []repocache.RepoInfo) error {+ return c.inner.Sync(workspaceID, repos)+}++func (c *blockingRepoCache) WithRepoLock(barePath string, fn func() error) error {+ return c.inner.WithRepoLock(barePath, func() error {+ close(c.entered)+ <-c.release+ return fn()+ })+}++func (c *blockingRepoCache) CreateWorktree(params repocache.WorktreeParams) (*repocache.WorktreeResult, error) {+ return c.inner.CreateWorktree(params)+}+// TestShouldCleanTaskDir_KindDispatch covers the four GCMeta kinds across// active / terminal / 404 / non-terminal axes. Each entry stands up a mock// server returning the expected payload (or 404) and asserts the action.@@ -900,6 +1115,48 @@ func TestShouldCleanTaskDir_EmptyParentIDFallsBackToOrphanMTime(t *testing.T) {}}+func createGCGitRepo(t *testing.T) string {+ t.Helper()++ repoDir := t.TempDir()+ runGitForGC(t, repoDir, "init", "-b", "main")+ if err := os.WriteFile(filepath.Join(repoDir, "README.md"), []byte("hello\n"), 0o644); err != nil {+ t.Fatalf("write README: %v", err)+ }+ runGitForGC(t, repoDir, "add", "README.md")+ runGitForGC(t, repoDir, "commit", "-m", "initial commit")+ return repoDir+}++func runGitForGC(t *testing.T, dir string, args ...string) string {+ t.Helper()++ fullArgs := args+ if dir != "" {+ fullArgs = append([]string{"-C", dir}, args...)+ }+ cmd := exec.Command("git", fullArgs...)+ cmd.Env = append(os.Environ(),+ "GIT_AUTHOR_NAME=test", "[email protected]",+ "GIT_COMMITTER_NAME=test", "[email protected]",+ )+ out, err := cmd.CombinedOutput()+ if err != nil {+ t.Fatalf("git %s failed: %s: %v", strings.Join(fullArgs, " "), out, err)+ }+ return strings.TrimSpace(string(out))+}++func gitRefExists(t *testing.T, repoPath, ref string) bool {+ t.Helper()++ cmd := exec.Command("git", "-C", repoPath, "show-ref", "--verify", "--quiet", ref)+ if err := cmd.Run(); err != nil {+ return false+ }+ return true+}+// TestShouldCleanTaskDir_ChatHardDeletedFreshMtime locks acceptance #3:// when a user hard-deletes a chat session, the workdir must be reclaimed// on the next GC cycle (≤ GCInterval), not deferred to GCOrphanTTL. Adiff --git a/server/internal/daemon/health_test.go b/server/internal/daemon/health_test.goindex 81818ce5c1..a4a9f8bd74 100644--- a/server/internal/daemon/health_test.go+++ b/server/internal/daemon/health_test.go@@ -249,6 +249,10 @@ func (c *blockingLookupRepoCache) Sync(string, []repocache.RepoInfo) error {return nil}+func (c *blockingLookupRepoCache) WithRepoLock(_ string, fn func() error) error {+ return fn()+}+func (c *blockingLookupRepoCache) CreateWorktree(repocache.WorktreeParams) (*repocache.WorktreeResult, error) {return nil, nil}diff --git a/server/internal/daemon/repocache/cache.go b/server/internal/daemon/repocache/cache.goindex 0583c881b2..c4b23194bc 100644--- a/server/internal/daemon/repocache/cache.go+++ b/server/internal/daemon/repocache/cache.go@@ -149,9 +149,21 @@ func (c *Cache) Lookup(workspaceID, url string) string {return ""}+// WithRepoLock serializes caller-supplied mutations on a bare repo against all+// other same-repo operations that use the cache's lock (Sync, Fetch,+// CreateWorktree, and daemon GC maintenance).+func (c *Cache) WithRepoLock(barePath string, fn func() error) error {+ repoLock := c.lockForRepo(barePath)+ repoLock.Lock()+ defer repoLock.Unlock()+ return fn()+}+// Fetch runs `git fetch origin` on a cached bare clone to get latest refs.func (c *Cache) Fetch(barePath string) error {- return gitFetch(barePath)+ return c.WithRepoLock(barePath, func() error {+ return gitFetch(barePath)+ })}// bareDirName returns a filesystem-safe, collision-free directory name for