Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): address GC review feedback
yushen20809052f504
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 7c1acfeb45..f5519a92d9 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -871,6 +871,15 @@ func (d *Daemon) handleTask(ctx context.Context, task Task) {}}}++ // Write GC metadata after the task finishes so the periodic GC loop+ // can look up the issue later. Written last so that a mid-task crash+ // leaves the directory as an orphan (cleaned up by GCOrphanTTL).+ if result.EnvRoot != "" {+ if err := execenv.WriteGCMeta(result.EnvRoot, task.IssueID, task.WorkspaceID); err != nil {+ taskLog.Warn("write gc meta failed (non-fatal)", "error", err)+ }+ }}func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLog *slog.Logger) (TaskResult, error) {@@ -929,11 +938,6 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLo// the same (agent, issue) pair. The work_dir path is stored in DB on// task completion and passed back via PriorWorkDir on the next claim.- // Write GC metadata so the periodic GC loop can look up the issue later.- if err := env.WriteGCMeta(task.IssueID, task.WorkspaceID); err != nil {- taskLog.Warn("write gc meta failed (non-fatal)", "error", err)- }-prompt := BuildPrompt(task)// Pass the daemon's auth credentials and context so the spawned agent CLI@@ -1157,6 +1161,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLoComment: result.Output,SessionID: result.SessionID,WorkDir: env.WorkDir,+ EnvRoot: env.RootDir,Usage: usageEntries,}, nilcase "timeout":@@ -1166,7 +1171,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, taskLoif errMsg == "" {errMsg = fmt.Sprintf("%s execution %s", provider, result.Status)}- return TaskResult{Status: "blocked", Comment: errMsg, Usage: usageEntries}, nil+ return TaskResult{Status: "blocked", Comment: errMsg, EnvRoot: env.RootDir, Usage: usageEntries}, nil}}diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 8fbee24dd4..4a2e28b2a5 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -168,9 +168,9 @@ type GCMeta struct {const gcMetaFile = ".gc_meta.json"-// WriteGCMeta writes GC metadata into the environment root directory.-func (env *Environment) WriteGCMeta(issueID, workspaceID string) error {- if env == nil {+// WriteGCMeta writes GC metadata into the given directory.+func WriteGCMeta(envRoot, issueID, workspaceID string) error {+ if envRoot == "" {return nil}meta := GCMeta{@@ -182,7 +182,7 @@ func (env *Environment) WriteGCMeta(issueID, workspaceID string) error {if err != nil {return fmt.Errorf("marshal gc meta: %w", err)}- return os.WriteFile(filepath.Join(env.RootDir, gcMetaFile), data, 0o644)+ return os.WriteFile(filepath.Join(envRoot, gcMetaFile), data, 0o644)}// ReadGCMeta reads GC metadata from a task directory root.diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex c587c50867..7e741de9c9 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -920,3 +920,46 @@ func TestEnsureSymlinkRepairsBrokenLink(t *testing.T) {t.Errorf("content = %q, want %q", data, "real")}}++func TestWriteReadGCMeta(t *testing.T) {+ t.Parallel()+ dir := t.TempDir()++ issueID := "a1b2c3d4-e5f6-7890-abcd-ef1234567890"+ wsID := "ws-test-001"++ if err := WriteGCMeta(dir, issueID, wsID); err != nil {+ t.Fatalf("WriteGCMeta: %v", err)+ }++ meta, err := ReadGCMeta(dir)+ if err != nil {+ t.Fatalf("ReadGCMeta: %v", err)+ }++ if meta.IssueID != issueID {+ t.Errorf("IssueID = %q, want %q", meta.IssueID, issueID)+ }+ if meta.WorkspaceID != wsID {+ t.Errorf("WorkspaceID = %q, want %q", meta.WorkspaceID, wsID)+ }+ if meta.CompletedAt.IsZero() {+ t.Error("CompletedAt should not be zero")+ }+}++func TestWriteGCMeta_EmptyRoot(t *testing.T) {+ t.Parallel()+ if err := WriteGCMeta("", "issue", "ws"); err != nil {+ t.Fatalf("expected nil for empty root, got %v", err)+ }+}++func TestReadGCMeta_NoFile(t *testing.T) {+ t.Parallel()+ dir := t.TempDir()+ _, err := ReadGCMeta(dir)+ if err == nil {+ t.Fatal("expected error for missing file")+ }+}diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex be32c8d94a..6e1e4e80ee 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -101,6 +101,14 @@ func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string) (cleaned, skippeskipped++}}++ // Remove the workspace directory itself if it's now empty.+ if cleaned+orphaned > 0 {+ remaining, _ := os.ReadDir(wsDir)+ if len(remaining) == 0 {+ os.Remove(wsDir)+ }+ }return}@@ -169,6 +177,8 @@ func (d *Daemon) cleanTaskDir(taskDir string) {}}+const gitCmdTimeout = 30 * time.Second+// pruneRepoWorktrees runs `git worktree prune` on all bare repos in the cache.func (d *Daemon) pruneRepoWorktrees(workspacesRoot string) {reposRoot := filepath.Join(workspacesRoot, ".repos")@@ -194,7 +204,8 @@ func (d *Daemon) pruneRepoWorktrees(workspacesRoot string) {if !isBareRepo(barePath) {continue}- cmd := exec.Command("git", "-C", barePath, "worktree", "prune")+ ctx, cancel := context.WithTimeout(context.Background(), gitCmdTimeout)+ cmd := exec.CommandContext(ctx, "git", "-C", barePath, "worktree", "prune")if out, err := cmd.CombinedOutput(); err != nil {d.logger.Warn("gc: worktree prune failed","repo", barePath,@@ -202,12 +213,18 @@ func (d *Daemon) pruneRepoWorktrees(workspacesRoot string) {"error", err,)}+ cancel()}}}// isBareRepo checks if a path looks like a bare git repository.func isBareRepo(path string) bool {- _, err := os.Stat(filepath.Join(path, "HEAD"))- return err == nil+ if _, err := os.Stat(filepath.Join(path, "HEAD")); err != nil {+ return false+ }+ if _, err := os.Stat(filepath.Join(path, "objects")); err != nil {+ return false+ }+ return true}diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.gonew file mode 100644index 0000000000..5b9da75cf3--- /dev/null+++ b/server/internal/daemon/gc_test.go@@ -0,0 +1,300 @@+package daemon++import (+ "context"+ "encoding/json"+ "fmt"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/daemon/execenv"+)++// newTestDaemon creates a minimal Daemon for GC testing with a mock HTTP server.+func newTestDaemon(t *testing.T, handler http.Handler) *Daemon {+ t.Helper()+ srv := httptest.NewServer(handler)+ t.Cleanup(srv.Close)++ root := t.TempDir()+ cfg := Config{+ WorkspacesRoot: root,+ GCEnabled: true,+ GCInterval: 1 * time.Hour,+ GCTTL: 5 * 24 * time.Hour,+ GCOrphanTTL: 30 * 24 * time.Hour,+ }+ d := New(cfg, slog.Default())+ d.client = NewClient(srv.URL)+ d.client.SetToken("test-token")+ return d+}++// createTaskDir creates a task directory with optional GC metadata.+func createTaskDir(t *testing.T, root, wsID, dirName string, meta *execenv.GCMeta) string {+ t.Helper()+ taskDir := filepath.Join(root, wsID, dirName)+ if err := os.MkdirAll(taskDir, 0o755); err != nil {+ t.Fatal(err)+ }+ if meta != nil {+ data, _ := json.Marshal(meta)+ if err := os.WriteFile(filepath.Join(taskDir, ".gc_meta.json"), data, 0o644); err != nil {+ t.Fatal(err)+ }+ }+ return taskDir+}++func TestShouldCleanTaskDir_DoneIssueOverTTL(t *testing.T) {+ t.Parallel()+ issueID := "11111111-1111-1111-1111-111111111111"++ mux := http.NewServeMux()+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]any{+ "status": "done",+ "updated_at": time.Now().Add(-10 * 24 * time.Hour), // 10 days ago+ })+ })++ d := newTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "task1", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now().Add(-10 * 24 * time.Hour),+ })++ action := d.shouldCleanTaskDir(context.Background(), taskDir)+ if action != gcActionClean {+ t.Fatalf("expected gcActionClean, got %d", action)+ }+}++func TestShouldCleanTaskDir_CanceledIssueOverTTL(t *testing.T) {+ t.Parallel()+ issueID := "22222222-2222-2222-2222-222222222222"++ mux := http.NewServeMux()+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]any{+ "status": "canceled",+ "updated_at": time.Now().Add(-6 * 24 * time.Hour),+ })+ })++ d := newTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "task2", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now(),+ })++ action := d.shouldCleanTaskDir(context.Background(), taskDir)+ if action != gcActionClean {+ t.Fatalf("expected gcActionClean, got %d", action)+ }+}++func TestShouldCleanTaskDir_OpenIssueSkipped(t *testing.T) {+ t.Parallel()+ issueID := "33333333-3333-3333-3333-333333333333"++ mux := http.NewServeMux()+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]any{+ "status": "in_progress",+ "updated_at": time.Now().Add(-30 * 24 * time.Hour),+ })+ })++ d := newTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "task3", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now(),+ })++ action := d.shouldCleanTaskDir(context.Background(), taskDir)+ if action != gcActionSkip {+ t.Fatalf("expected gcActionSkip for open issue, got %d", action)+ }+}++func TestShouldCleanTaskDir_DoneButRecentSkipped(t *testing.T) {+ t.Parallel()+ issueID := "44444444-4444-4444-4444-444444444444"++ mux := http.NewServeMux()+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]any{+ "status": "done",+ "updated_at": time.Now().Add(-1 * 24 * time.Hour), // 1 day ago, within TTL+ })+ })++ d := newTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "task4", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now(),+ })++ action := d.shouldCleanTaskDir(context.Background(), taskDir)+ if action != gcActionSkip {+ t.Fatalf("expected gcActionSkip for recently-done issue, got %d", action)+ }+}++func TestShouldCleanTaskDir_NoMetaRecentSkipped(t *testing.T) {+ t.Parallel()++ d := newTestDaemon(t, http.NewServeMux())+ // No meta, fresh directory — should skip.+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "task5", nil)++ action := d.shouldCleanTaskDir(context.Background(), taskDir)+ if action != gcActionSkip {+ t.Fatalf("expected gcActionSkip for recent orphan, got %d", action)+ }+}++func TestShouldCleanTaskDir_NoMetaOldOrphan(t *testing.T) {+ t.Parallel()++ d := newTestDaemon(t, http.NewServeMux())+ d.cfg.GCOrphanTTL = 0 // treat all orphans as expired+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "task6", nil)++ action := d.shouldCleanTaskDir(context.Background(), taskDir)+ if action != gcActionOrphan {+ t.Fatalf("expected gcActionOrphan, got %d", action)+ }+}++func TestShouldCleanTaskDir_APIErrorSkipped(t *testing.T) {+ t.Parallel()+ issueID := "55555555-5555-5555-5555-555555555555"++ mux := http.NewServeMux()+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusInternalServerError)+ })++ d := newTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "task7", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now(),+ })++ action := d.shouldCleanTaskDir(context.Background(), taskDir)+ if action != gcActionSkip {+ t.Fatalf("expected gcActionSkip on API error, got %d", action)+ }+}++func TestShouldCleanTaskDir_Issue404OldOrphan(t *testing.T) {+ t.Parallel()+ issueID := "66666666-6666-6666-6666-666666666666"++ mux := http.NewServeMux()+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {+ w.WriteHeader(http.StatusNotFound)+ w.Write([]byte(`{"error":"issue not found"}`))+ })++ d := newTestDaemon(t, mux)+ d.cfg.GCOrphanTTL = 0 // treat orphans as immediately eligible+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "task8", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now(),+ })++ action := d.shouldCleanTaskDir(context.Background(), taskDir)+ if action != gcActionOrphan {+ t.Fatalf("expected gcActionOrphan for deleted issue, got %d", action)+ }+}++func TestCleanTaskDir_RemovesDirectory(t *testing.T) {+ t.Parallel()+ d := newTestDaemon(t, http.NewServeMux())+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "doomed", nil)++ if _, err := os.Stat(taskDir); err != nil {+ t.Fatal("task dir should exist before cleanup")+ }++ d.cleanTaskDir(taskDir)++ if _, err := os.Stat(taskDir); !os.IsNotExist(err) {+ t.Fatal("task dir should be removed after cleanup")+ }+}++func TestGcWorkspace_CleansEmptyWorkspaceDir(t *testing.T) {+ t.Parallel()+ issueID := "77777777-7777-7777-7777-777777777777"++ mux := http.NewServeMux()+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]any{+ "status": "done",+ "updated_at": time.Now().Add(-10 * 24 * time.Hour),+ })+ })++ d := newTestDaemon(t, mux)+ wsDir := filepath.Join(d.cfg.WorkspacesRoot, "ws-empty")+ createTaskDir(t, d.cfg.WorkspacesRoot, "ws-empty", "only-task", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws-empty",+ CompletedAt: time.Now(),+ })++ d.gcWorkspace(context.Background(), wsDir)++ if _, err := os.Stat(wsDir); !os.IsNotExist(err) {+ t.Fatal("empty workspace dir should be removed after all tasks cleaned")+ }+}++func TestIsBareRepo(t *testing.T) {+ t.Parallel()++ t.Run("valid bare repo", func(t *testing.T) {+ dir := t.TempDir()+ os.WriteFile(filepath.Join(dir, "HEAD"), []byte("ref: refs/heads/main"), 0o644)+ os.MkdirAll(filepath.Join(dir, "objects"), 0o755)+ if !isBareRepo(dir) {+ t.Fatal("expected isBareRepo=true for dir with HEAD + objects/")+ }+ })++ t.Run("HEAD only", func(t *testing.T) {+ dir := t.TempDir()+ os.WriteFile(filepath.Join(dir, "HEAD"), []byte("ref: refs/heads/main"), 0o644)+ if isBareRepo(dir) {+ t.Fatal("expected isBareRepo=false for dir with only HEAD")+ }+ })++ t.Run("empty dir", func(t *testing.T) {+ dir := t.TempDir()+ if isBareRepo(dir) {+ t.Fatal("expected isBareRepo=false for empty dir")+ }+ })+}diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex b1d46fc890..cdcb939fd1 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -76,5 +76,6 @@ type TaskResult struct {EnvType string `json:"env_type,omitempty"`SessionID string `json:"session_id,omitempty"` // Claude session ID for future resumptionWorkDir string `json:"work_dir,omitempty"` // working directory used during execution+ EnvRoot string `json:"-"` // env root dir for writing GC metadata (not sent to server)Usage []TaskUsageEntry `json:"usage,omitempty"` // per-model token usage}