Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): reclaim disk on long-open issues + correct cancelled-status check (#1931)
Bohan Jiang1d1dedbf6e67
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 9bb9fe54fd..13a97eecb6 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -174,6 +174,22 @@ Daemon behavior is configured via flags or environment variables:| Device name | `--device-name` | `MULTICA_DAEMON_DEVICE_NAME` | hostname || Runtime name | `--runtime-name` | `MULTICA_AGENT_RUNTIME_NAME` | `Local Agent` || Workspaces root | — | `MULTICA_WORKSPACES_ROOT` | `~/multica_workspaces` |+| GC enabled | — | `MULTICA_GC_ENABLED` | `true` (set `false`/`0` to disable) |+| GC scan interval | — | `MULTICA_GC_INTERVAL` | `1h` |+| GC TTL (done/cancelled issues) | — | `MULTICA_GC_TTL` | `24h` |+| GC orphan TTL (no `.gc_meta.json`) | — | `MULTICA_GC_ORPHAN_TTL` | `72h` |+| GC artifact TTL (open issues) | — | `MULTICA_GC_ARTIFACT_TTL` | `12h` (set `0` to disable) |+| GC artifact patterns | — | `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` |++#### Workspace garbage collection++The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and reclaims disk space in three modes:++- **Full task cleanup** — when an issue's status is `done` or `cancelled` and has been idle for `MULTICA_GC_TTL`, the entire task directory is removed.+- **Orphan cleanup** — task directories with no `.gc_meta.json` (e.g. left over from a daemon crash) are removed once they exceed `MULTICA_GC_ORPHAN_TTL`.+- **Artifact-only cleanup** — when a task has been completed for at least `MULTICA_GC_ARTIFACT_TTL` but the issue is still open, regenerable build outputs whose directory basename matches `MULTICA_GC_ARTIFACT_PATTERNS` are removed; the rest of the workdir (source, `.git`, `output/`, `logs/`, `.gc_meta.json`) is preserved so the agent can resume the same workdir on the next task.++Patterns are basename-only — entries containing `/` or `\` are silently dropped — and `.git` subtrees are never descended into. The default list (`node_modules`, `.next`, `.turbo`) is intentionally narrow; extend it per deployment if your repos consistently produce other regenerable directories (for example, `MULTICA_GC_ARTIFACT_PATTERNS=node_modules,.next,.turbo,target,__pycache__`). To disable artifact cleanup entirely, set `MULTICA_GC_ARTIFACT_TTL=0`.Agent-specific overrides:diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 92d66e7958..e01df760b0 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -25,8 +25,17 @@ const (DefaultGCInterval = 1 * time.HourDefaultGCTTL = 24 * time.Hour // 1 day — AI-coding issues rarely stay open longDefaultGCOrphanTTL = 72 * time.Hour // 3 days — orphans with no meta (crashes, pre-GC leftovers)+ DefaultGCArtifactTTL = 12 * time.Hour // 12h — drop regenerable artifacts on completed but still-open issues)+// DefaultGCArtifactPatterns lists basename matches that the GC loop treats as+// regenerable build artifacts. Kept conservative: only directories that are+// always cheap to recreate (`pnpm install`, `next build`, `turbo build`). Things+// like `dist/`, `build/`, `.cache/` or `.venv/` may legitimately hold source or+// release output in some repos and are NOT included by default — set+// MULTICA_GC_ARTIFACT_PATTERNS to extend the list per deployment.+var DefaultGCArtifactPatterns = []string{"node_modules", ".next", ".turbo"}+// Config holds all daemon configuration.type Config struct {ServerBaseURL string@@ -44,8 +53,10 @@ type Config struct {MaxConcurrentTasks int // max tasks running in parallel (default: 20)GCEnabled bool // enable periodic workspace garbage collection (default: true)GCInterval time.Duration // how often the GC loop runs (default: 1h)- GCTTL time.Duration // clean dirs whose issue is done/canceled and updated_at < now()-TTL (default: 24h)- GCOrphanTTL time.Duration // clean orphan dirs with no meta older than this (default: 72h). Dirs whose issue returned 404 are cleaned immediately.+ GCTTL time.Duration // clean dirs whose issue is done/cancelled and updated_at < now()-TTL (default: 24h)+ GCOrphanTTL time.Duration // clean orphan dirs with no meta, or dirs whose issue gc-check returns 404, once they exceed this age (default: 72h). The 404 path uses the same TTL — a scoped-down token can't instantly wipe live workspaces.+ GCArtifactTTL time.Duration // when a task has been completed for at least this long but its issue is still open, drop regenerable artifacts (default: 12h, set 0 to disable)+ GCArtifactPatterns []string // basename patterns whose subtrees are removed during artifact cleanup (default: node_modules, .next, .turbo)PollInterval time.DurationHeartbeatInterval time.DurationAgentTimeout time.Duration@@ -318,6 +329,11 @@ func LoadConfig(overrides Overrides) (Config, error) {if err != nil {return Config{}, err}+ gcArtifactTTL, err := durationFromEnv("MULTICA_GC_ARTIFACT_TTL", DefaultGCArtifactTTL)+ if err != nil {+ return Config{}, err+ }+ gcArtifactPatterns := patternsFromEnv("MULTICA_GC_ARTIFACT_PATTERNS", DefaultGCArtifactPatterns)return Config{ServerBaseURL: serverBaseURL,@@ -333,6 +349,8 @@ func LoadConfig(overrides Overrides) (Config, error) {GCInterval: gcInterval,GCTTL: gcTTL,GCOrphanTTL: gcOrphanTTL,+ GCArtifactTTL: gcArtifactTTL,+ GCArtifactPatterns: gcArtifactPatterns,HealthPort: healthPort,MaxConcurrentTasks: maxConcurrentTasks,PollInterval: pollInterval,@@ -368,6 +386,29 @@ func NormalizeServerBaseURL(raw string) (string, error) {return strings.TrimRight(u.String(), "/"), nil}+// patternsFromEnv reads a comma-separated list from env. Patterns containing+// path separators are silently dropped — the GC artifact cleanup only matches+// directory basenames, never paths, so a pattern like "foo/bar" is meaningless+// and accepting it would just be a footgun.+func patternsFromEnv(name string, defaults []string) []string {+ raw := strings.TrimSpace(os.Getenv(name))+ if raw == "" {+ out := make([]string, len(defaults))+ copy(out, defaults)+ return out+ }+ parts := strings.Split(raw, ",")+ out := make([]string, 0, len(parts))+ for _, p := range parts {+ p = strings.TrimSpace(p)+ if p == "" || strings.ContainsAny(p, "/\\") {+ continue+ }+ out = append(out, p)+ }+ return out+}+func shellArgsFromEnv(name string) ([]string, error) {raw := strings.TrimSpace(os.Getenv(name))if raw == "" {diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.gonew file mode 100644index 0000000000..9282059005--- /dev/null+++ b/server/internal/daemon/config_test.go@@ -0,0 +1,29 @@+package daemon++import (+ "reflect"+ "testing"+)++func TestPatternsFromEnv_DefaultsWhenUnset(t *testing.T) {+ t.Setenv("MULTICA_GC_ARTIFACT_PATTERNS", "")+ defaults := []string{"node_modules", ".next", ".turbo"}+ got := patternsFromEnv("MULTICA_GC_ARTIFACT_PATTERNS", defaults)+ if !reflect.DeepEqual(got, defaults) {+ t.Fatalf("expected defaults %v, got %v", defaults, got)+ }+ // Ensure callers get a copy, not a shared backing array.+ got[0] = "mutated"+ if defaults[0] == "mutated" {+ t.Fatal("patternsFromEnv must not return a slice aliased with defaults")+ }+}++func TestPatternsFromEnv_DropsSeparatorBearingEntries(t *testing.T) {+ t.Setenv("MULTICA_GC_ARTIFACT_PATTERNS", "node_modules, .next ,foo/bar, ../etc, ,target")+ got := patternsFromEnv("MULTICA_GC_ARTIFACT_PATTERNS", nil)+ want := []string{"node_modules", ".next", "target"}+ if !reflect.DeepEqual(got, want) {+ t.Fatalf("expected %v, got %v", want, got)+ }+}diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 4dc77d7526..6228773a6b 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -66,6 +66,9 @@ type Daemon struct {restartBinary string // non-empty after a successful update; path to the new binaryupdating atomic.Bool // prevents concurrent update attemptsactiveTasks atomic.Int64 // number of tasks currently in handleTask; exposed via /health++ activeEnvRootsMu sync.Mutex+ activeEnvRoots map[string]int // env root path -> reference count (handles reuse paths marked twice)}// New creates a new Daemon instance.@@ -81,10 +84,11 @@ func New(cfg Config, logger *slog.Logger) *Daemon {repoCache: repocache.New(cacheRoot, logger),logger: logger,workspaces: make(map[string]*workspaceState),- runtimeIndex: make(map[string]Runtime),- runtimeSetCh: make(chan struct{}, 1),- agentVersions: make(map[string]string),- wsHBLastAck: make(map[string]time.Time),+ runtimeIndex: make(map[string]Runtime),+ runtimeSetCh: make(chan struct{}, 1),+ agentVersions: make(map[string]string),+ wsHBLastAck: make(map[string]time.Time),+ activeEnvRoots: make(map[string]int),}}@@ -1251,6 +1255,21 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iQuickCreatePrompt: task.QuickCreatePrompt,}+ // Mark candidate env roots as active before any env work so the GC loop+ // can't reclaim artifacts inside them mid-execution. We mark both the+ // predicted root for a fresh Prepare and the prior root for Reuse — they+ // usually differ (Reuse keeps the original task's directory).+ predictedRoot := execenv.PredictRootDir(d.cfg.WorkspacesRoot, task.WorkspaceID, task.ID)+ d.markActiveEnvRoot(predictedRoot)+ defer d.unmarkActiveEnvRoot(predictedRoot)+ if task.PriorWorkDir != "" {+ priorRoot := filepath.Dir(task.PriorWorkDir)+ if priorRoot != predictedRoot {+ d.markActiveEnvRoot(priorRoot)+ defer d.unmarkActiveEnvRoot(priorRoot)+ }+ }+// Try to reuse the workdir from a previous task on the same (agent, issue) pair.var env *execenv.EnvironmentcodexVersion := d.agentVersion("codex")@@ -1272,6 +1291,12 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ireturn TaskResult{}, fmt.Errorf("prepare execution environment: %w", err)}}+ // Belt-and-suspenders: also mark whatever root we ended up with, in case+ // future changes diverge from PredictRootDir.+ if env.RootDir != predictedRoot && env.RootDir != "" {+ d.markActiveEnvRoot(env.RootDir)+ defer d.unmarkActiveEnvRoot(env.RootDir)+ }// Inject runtime-specific config (meta skill) so the agent discovers .agent_context/.if err := execenv.InjectRuntimeConfig(env.WorkDir, provider, taskCtx); err != nil {@@ -1798,6 +1823,38 @@ func convertProjectResourcesForEnv(resources []ProjectResourceData) []execenv.Prreturn result}+// markActiveEnvRoot records that a task is currently using the given env root,+// so the GC loop won't reclaim its artifacts mid-execution. Calls are+// reference-counted so a reuse path marked twice (predicted + prior) only+// becomes inactive after both unmark calls.+func (d *Daemon) markActiveEnvRoot(envRoot string) {+ if envRoot == "" {+ return+ }+ d.activeEnvRootsMu.Lock()+ defer d.activeEnvRootsMu.Unlock()+ d.activeEnvRoots[envRoot]+++}++func (d *Daemon) unmarkActiveEnvRoot(envRoot string) {+ if envRoot == "" {+ return+ }+ d.activeEnvRootsMu.Lock()+ defer d.activeEnvRootsMu.Unlock()+ if d.activeEnvRoots[envRoot] <= 1 {+ delete(d.activeEnvRoots, envRoot)+ return+ }+ d.activeEnvRoots[envRoot]--+}++func (d *Daemon) isActiveEnvRoot(envRoot string) bool {+ d.activeEnvRootsMu.Lock()+ defer d.activeEnvRootsMu.Unlock()+ return d.activeEnvRoots[envRoot] > 0+}+// shortID returns the first 8 characters of an ID for readable logs.func shortID(id string) string {if len(id) <= 8 {diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex cc9fe0d877..4fb0e36080 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -87,6 +87,16 @@ type Environment struct {logger *slog.Logger // for cleanup logging}+// PredictRootDir returns the env root path that Prepare would create for the+// given task, without performing any I/O. Callers use this to claim ownership+// of the directory (e.g. against the GC loop) before Prepare/Reuse runs.+func PredictRootDir(workspacesRoot, workspaceID, taskID string) string {+ if workspacesRoot == "" || workspaceID == "" || taskID == "" {+ return ""+ }+ return filepath.Join(workspacesRoot, workspaceID, shortID(taskID))+}+// Prepare creates an isolated execution environment for a task.// The workdir starts empty (no repo checkouts). The agent checks out repos// on demand via `multica repo checkout <url>`.diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex 06baad289c..b77ec0b85d 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -31,6 +31,24 @@ func TestShortID(t *testing.T) {}}+func TestPredictRootDir(t *testing.T) {+ t.Parallel()+ got := PredictRootDir("/root", "ws-uuid", "a1b2c3d4-e5f6-7890-abcd-ef1234567890")+ want := filepath.Join("/root", "ws-uuid", "a1b2c3d4")+ if got != want {+ t.Errorf("PredictRootDir = %q, want %q", got, want)+ }+ if got := PredictRootDir("", "ws", "task"); got != "" {+ t.Errorf("expected empty when workspaces root missing, got %q", got)+ }+ if got := PredictRootDir("/r", "", "task"); got != "" {+ t.Errorf("expected empty when workspace ID missing, got %q", got)+ }+ if got := PredictRootDir("/r", "ws", ""); got != "" {+ t.Errorf("expected empty when task ID missing, got %q", got)+ }+}+func TestSanitizeName(t *testing.T) {t.Parallel()tests := []struct {diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex a73da6c080..40c9280e91 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -14,13 +14,19 @@ import ()// gcLoop periodically scans local workspace directories and removes those-// whose issue is done/canceled and hasn't been updated within the configured TTL.+// whose issue is done/cancelled and hasn't been updated within the configured TTL.func (d *Daemon) gcLoop(ctx context.Context) {if !d.cfg.GCEnabled {d.logger.Info("gc: disabled")return}- d.logger.Info("gc: started", "interval", d.cfg.GCInterval, "ttl", d.cfg.GCTTL, "orphan_ttl", d.cfg.GCOrphanTTL)+ d.logger.Info("gc: started",+ "interval", d.cfg.GCInterval,+ "ttl", d.cfg.GCTTL,+ "orphan_ttl", d.cfg.GCOrphanTTL,+ "artifact_ttl", d.cfg.GCArtifactTTL,+ "artifact_patterns", d.cfg.GCArtifactPatterns,+ )// Run once at startup after a short delay (let the daemon finish initializing).if err := sleepWithContext(ctx, 30*time.Second); err != nil {@@ -41,6 +47,17 @@ func (d *Daemon) gcLoop(ctx context.Context) {}}+// gcStats accumulates byte counts and per-pattern hit counts for one GC cycle.+type gcStats struct {+ cleaned int // whole task dirs removed (issue done/cancelled)+ orphaned int // whole task dirs removed (no meta / unreachable issue)+ skipped int // task dirs left untouched+ artifactDirs int // task dirs that had at least one artifact reclaimed+ artifactRemoved int // count of removed artifact subdirs+ bytesReclaimed int64 // total bytes freed in this cycle+ byPattern map[string]int // basename -> reclaim count, for visibility+}+// runGC performs a single GC scan across all workspace directories.func (d *Daemon) runGC(ctx context.Context) {root := d.cfg.WorkspacesRoot@@ -53,34 +70,40 @@ func (d *Daemon) runGC(ctx context.Context) {return}- var cleaned, skipped, orphaned int+ stats := &gcStats{byPattern: map[string]int{}}for _, wsEntry := range entries {if !wsEntry.IsDir() || wsEntry.Name() == ".repos" {continue}wsDir := filepath.Join(root, wsEntry.Name())- c, s, o := d.gcWorkspace(ctx, wsDir)- cleaned += c- skipped += s- orphaned += o+ d.gcWorkspace(ctx, wsDir, stats)}// Prune stale worktree references from all bare repo caches.d.pruneRepoWorktrees(root)- if cleaned > 0 || orphaned > 0 {- d.logger.Info("gc: cycle complete", "cleaned", cleaned, "orphaned", orphaned, "skipped", skipped)+ if stats.cleaned > 0 || stats.orphaned > 0 || stats.artifactDirs > 0 {+ d.logger.Info("gc: cycle complete",+ "cleaned", stats.cleaned,+ "orphaned", stats.orphaned,+ "skipped", stats.skipped,+ "artifact_dirs", stats.artifactDirs,+ "artifact_removed", stats.artifactRemoved,+ "bytes_reclaimed", stats.bytesReclaimed,+ "by_pattern", stats.byPattern,+ )}}// gcWorkspace scans task directories inside a single workspace directory.-func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string) (cleaned, skipped, orphaned int) {+func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string, stats *gcStats) {taskEntries, err := os.ReadDir(wsDir)if err != nil {d.logger.Warn("gc: read workspace dir failed", "dir", wsDir, "error", err)return}+ cleanedHere := 0for _, entry := range taskEntries {if ctx.Err() != nil {return@@ -92,36 +115,62 @@ func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string) (cleaned, skippeaction := d.shouldCleanTaskDir(ctx, taskDir)switch action {case gcActionClean:+ bytes := dirSize(taskDir)d.cleanTaskDir(taskDir)- cleaned+++ stats.cleaned+++ stats.bytesReclaimed += bytes+ cleanedHere++case gcActionOrphan:+ bytes := dirSize(taskDir)d.cleanTaskDir(taskDir)- orphaned+++ stats.orphaned+++ stats.bytesReclaimed += bytes+ cleanedHere+++ case gcActionCleanArtifacts:+ removed, bytes, perPattern := d.cleanTaskArtifacts(taskDir, d.cfg.GCArtifactPatterns)+ if removed > 0 {+ stats.artifactDirs+++ stats.artifactRemoved += removed+ stats.bytesReclaimed += bytes+ for k, v := range perPattern {+ stats.byPattern[k] += v+ }+ }+ stats.skipped++ // task dir itself preserveddefault:- skipped+++ stats.skipped++}}// Remove the workspace directory itself if it's now empty.- if cleaned+orphaned > 0 {+ if cleanedHere > 0 {remaining, _ := os.ReadDir(wsDir)if len(remaining) == 0 {os.Remove(wsDir)}}- return}type gcAction intconst (- gcActionSkip gcAction = iota- gcActionClean // issue is done/canceled and stale- gcActionOrphan // no meta or unknown issue and dir is old+ gcActionSkip gcAction = iota+ gcActionClean // issue is done/cancelled and stale+ gcActionOrphan // no meta or unknown issue and dir is old+ gcActionCleanArtifacts // task completed long enough ago; drop regenerable artifacts only)// shouldCleanTaskDir decides whether a task directory should be removed.func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcAction {+ // A task currently running on this env root must never be reclaimed —+ // not even on the done/cancelled or orphan-404 paths. A new comment on+ // an already-done issue can dispatch a follow-up task that reuses the+ // prior workdir without bumping the issue's updated_at, so the regular+ // TTL check alone wouldn't notice the resumed activity.+ if d.isActiveEnvRoot(taskDir) {+ return gcActionSkip+ }+meta, err := execenv.ReadGCMeta(taskDir)if err != nil {// No .gc_meta.json — check mtime for orphan cleanup.@@ -158,7 +207,7 @@ func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcActioreturn gcActionSkip}- if (status.Status == "done" || status.Status == "canceled") &&+ if (status.Status == "done" || status.Status == "cancelled") &&time.Since(status.UpdatedAt) > d.cfg.GCTTL {d.logger.Info("gc: eligible for cleanup","dir", filepath.Base(taskDir),@@ -169,6 +218,22 @@ func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcActioreturn gcActionClean}+ // Artifact-only cleanup: issue is still open but the task itself completed+ // long enough ago that its build artifacts are unlikely to be reused.+ // Active-root protection is handled by the early return above; skip here+ // only when artifact GC is disabled or the meta has no completed_at+ // (defensive — that means the task crashed before WriteGCMeta).+ if d.cfg.GCArtifactTTL > 0 && len(d.cfg.GCArtifactPatterns) > 0 &&+ !meta.CompletedAt.IsZero() && time.Since(meta.CompletedAt) > d.cfg.GCArtifactTTL {+ d.logger.Info("gc: eligible for artifact cleanup",+ "dir", filepath.Base(taskDir),+ "issue", meta.IssueID,+ "status", status.Status,+ "completed_at", meta.CompletedAt.Format(time.RFC3339),+ )+ return gcActionCleanArtifacts+ }+return gcActionSkip}@@ -181,6 +246,114 @@ func (d *Daemon) cleanTaskDir(taskDir string) {}}+// cleanTaskArtifacts walks taskDir and deletes every directory whose basename+// matches one of patterns. Returns (removedCount, bytesReclaimed, perPattern).+//+// Safety contract:+// - patterns are basename-only; entries with a path separator are dropped.+// - .git subtrees are never descended into, so the agent's git history stays+// intact even if a pattern would otherwise match.+// - symlinks are skipped entirely — neither the link nor its target is+// touched, so a malicious or stale link can't redirect the GC outside the+// workdir.+// - every removal target is verified to live inside taskDir, so a tampered+// .gc_meta.json can't trick the daemon into deleting outside its sandbox.+func (d *Daemon) cleanTaskArtifacts(taskDir string, patterns []string) (removed int, bytes int64, perPattern map[string]int) {+ perPattern = map[string]int{}+ if taskDir == "" || len(patterns) == 0 {+ return+ }+ patternSet := make(map[string]struct{}, len(patterns))+ for _, p := range patterns {+ p = strings.TrimSpace(p)+ if p == "" || strings.ContainsAny(p, "/\\") {+ continue+ }+ patternSet[p] = struct{}{}+ }+ if len(patternSet) == 0 {+ return+ }++ absRoot, err := filepath.Abs(taskDir)+ if err != nil {+ return+ }++ walkErr := filepath.WalkDir(absRoot, func(path string, entry os.DirEntry, err error) error {+ if err != nil {+ return nil // best-effort — keep walking+ }+ if path == absRoot {+ return nil+ }+ if !entry.IsDir() {+ return nil+ }+ // Never descend into .git — preserves agent commits even if a pattern+ // like "objects" would otherwise match.+ if entry.Name() == ".git" {+ return filepath.SkipDir+ }+ // Refuse to follow symlinked directories. WalkDir reports them as type+ // Dir on some platforms; lstat to be sure.+ info, statErr := os.Lstat(path)+ if statErr != nil {+ return nil+ }+ if info.Mode()&os.ModeSymlink != 0 {+ return filepath.SkipDir+ }+ if _, ok := patternSet[entry.Name()]; !ok {+ return nil+ }+ // Containment check: target must remain inside taskDir.+ rel, relErr := filepath.Rel(absRoot, path)+ if relErr != nil || rel == "" || rel == "." || strings.HasPrefix(rel, "..") {+ return filepath.SkipDir+ }+ size := dirSize(path)+ if rmErr := os.RemoveAll(path); rmErr != nil {+ d.logger.Warn("gc: artifact remove failed", "path", path, "error", rmErr)+ return filepath.SkipDir+ }+ removed+++ bytes += size+ perPattern[entry.Name()]+++ d.logger.Info("gc: artifact removed", "path", path, "bytes", size)+ // Don't descend into the now-deleted subtree.+ return filepath.SkipDir+ })+ if walkErr != nil {+ d.logger.Warn("gc: artifact walk failed", "dir", taskDir, "error", walkErr)+ }+ return+}++// dirSize returns the total size of all regular files under root, in bytes.+// Non-fatal: errors during the walk are ignored so callers can report a+// best-effort byte count without aborting the whole GC cycle.+func dirSize(root string) int64 {+ var total int64+ _ = filepath.WalkDir(root, func(_ string, entry os.DirEntry, err error) error {+ if err != nil {+ return nil+ }+ if entry.IsDir() {+ return nil+ }+ info, infoErr := entry.Info()+ if infoErr != nil {+ return nil+ }+ if info.Mode().IsRegular() {+ total += info.Size()+ }+ return nil+ })+ return total+}+const gitCmdTimeout = 30 * time.Second// pruneRepoWorktrees runs `git worktree prune` on all bare repos in the cache.diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.goindex 340c3b2b97..a4652c4a8f 100644--- a/server/internal/daemon/gc_test.go+++ b/server/internal/daemon/gc_test.go@@ -23,11 +23,13 @@ func newGCTestDaemon(t *testing.T, handler http.Handler) *Daemon {root := t.TempDir()cfg := Config{- WorkspacesRoot: root,- GCEnabled: true,- GCInterval: 1 * time.Hour,- GCTTL: 5 * 24 * time.Hour,- GCOrphanTTL: 30 * 24 * time.Hour,+ WorkspacesRoot: root,+ GCEnabled: true,+ GCInterval: 1 * time.Hour,+ GCTTL: 5 * 24 * time.Hour,+ GCOrphanTTL: 30 * 24 * time.Hour,+ GCArtifactTTL: 12 * time.Hour,+ GCArtifactPatterns: []string{"node_modules", ".next", ".turbo"},}d := New(cfg, slog.Default())d.client = NewClient(srv.URL)@@ -77,7 +79,7 @@ func TestShouldCleanTaskDir_DoneIssueOverTTL(t *testing.T) {}}-func TestShouldCleanTaskDir_CanceledIssueOverTTL(t *testing.T) {+func TestShouldCleanTaskDir_CancelledIssueOverTTL(t *testing.T) {t.Parallel()issueID := "22222222-2222-2222-2222-222222222222"@@ -85,7 +87,7 @@ func TestShouldCleanTaskDir_CanceledIssueOverTTL(t *testing.T) {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",+ "status": "cancelled","updated_at": time.Now().Add(-6 * 24 * time.Hour),})})@@ -292,13 +294,338 @@ func TestGcWorkspace_CleansEmptyWorkspaceDir(t *testing.T) {CompletedAt: time.Now(),})- d.gcWorkspace(context.Background(), wsDir)+ d.gcWorkspace(context.Background(), wsDir, &gcStats{byPattern: map[string]int{}})if _, err := os.Stat(wsDir); !os.IsNotExist(err) {t.Fatal("empty workspace dir should be removed after all tasks cleaned")}}+func TestShouldCleanTaskDir_OpenIssueArtifactCleanup(t *testing.T) {+ t.Parallel()+ issueID := "88888888-8888-8888-8888-888888888888"++ 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(),+ })+ })++ d := newGCTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "open-task", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now().Add(-24 * time.Hour),+ })++ action := d.shouldCleanTaskDir(context.Background(), taskDir)+ if action != gcActionCleanArtifacts {+ t.Fatalf("expected gcActionCleanArtifacts for old completed task on open issue, got %d", action)+ }+}++func TestShouldCleanTaskDir_OpenIssueRecentTaskSkipped(t *testing.T) {+ t.Parallel()+ issueID := "88888888-8888-8888-8888-888888888889"++ 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(),+ })+ })++ d := newGCTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "fresh-task", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now().Add(-1 * time.Minute),+ })++ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {+ t.Fatalf("expected gcActionSkip for fresh completed_at, got %d", action)+ }+}++func TestShouldCleanTaskDir_ActiveEnvRootSkipsArtifactCleanup(t *testing.T) {+ t.Parallel()+ issueID := "88888888-8888-8888-8888-88888888888a"++ 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(),+ })+ })++ d := newGCTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "active-task", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now().Add(-24 * time.Hour),+ })++ d.markActiveEnvRoot(taskDir)+ defer d.unmarkActiveEnvRoot(taskDir)++ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {+ t.Fatalf("expected gcActionSkip while task is active, got %d", action)+ }+}++func TestShouldCleanTaskDir_ActiveEnvRootSkipsFullCleanup(t *testing.T) {+ t.Parallel()+ issueID := "99999999-9999-9999-9999-999999999999"++ 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")+ // Done long enough ago to satisfy GCTTL — this would normally return+ // gcActionClean. But the env root is in use (e.g. follow-up comment+ // dispatched a task that reuses the prior workdir), and CreateComment+ // does not bump issue.updated_at. Active-root guard must override.+ json.NewEncoder(w).Encode(map[string]any{+ "status": "done",+ "updated_at": time.Now().Add(-30 * 24 * time.Hour),+ })+ })++ d := newGCTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "active-done", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now().Add(-30 * 24 * time.Hour),+ })++ d.markActiveEnvRoot(taskDir)+ defer d.unmarkActiveEnvRoot(taskDir)++ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {+ t.Fatalf("expected gcActionSkip on active env root with done+stale issue, got %d", action)+ }+}++func TestShouldCleanTaskDir_ActiveEnvRootSkipsOrphan404(t *testing.T) {+ t.Parallel()+ issueID := "99999999-9999-9999-9999-99999999999a"++ 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":"not found"}`))+ })++ d := newGCTestDaemon(t, mux)+ d.cfg.GCOrphanTTL = 0 // would normally make this an immediate orphan delete+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "active-404", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now(),+ })++ d.markActiveEnvRoot(taskDir)+ defer d.unmarkActiveEnvRoot(taskDir)++ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {+ t.Fatalf("expected gcActionSkip on active env root with 404 issue, got %d", action)+ }+}++func TestShouldCleanTaskDir_ActiveEnvRootSkipsNoMetaOrphan(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ d.cfg.GCOrphanTTL = 0+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "active-no-meta", nil)++ d.markActiveEnvRoot(taskDir)+ defer d.unmarkActiveEnvRoot(taskDir)++ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {+ t.Fatalf("expected gcActionSkip on active env root with no-meta orphan, got %d", action)+ }+}++func TestShouldCleanTaskDir_ArtifactTTLDisabled(t *testing.T) {+ t.Parallel()+ issueID := "88888888-8888-8888-8888-88888888888b"++ 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(),+ })+ })++ d := newGCTestDaemon(t, mux)+ d.cfg.GCArtifactTTL = 0+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "no-artifact-gc", &execenv.GCMeta{+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now().Add(-100 * 24 * time.Hour),+ })++ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {+ t.Fatalf("expected gcActionSkip when artifact GC disabled, got %d", action)+ }+}++func TestCleanTaskArtifacts_RemovesOnlyMatchedDirs(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ taskDir := t.TempDir()++ // Create a synthetic project layout.+ mustMkdir := func(rel string) string {+ p := filepath.Join(taskDir, rel)+ if err := os.MkdirAll(p, 0o755); err != nil {+ t.Fatal(err)+ }+ return p+ }+ mustWrite := func(rel string, content string) {+ p := filepath.Join(taskDir, rel)+ if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(p, []byte(content), 0o644); err != nil {+ t.Fatal(err)+ }+ }++ mustMkdir("workdir/repo/src")+ mustWrite("workdir/repo/src/index.ts", "console.log('hi')")+ mustMkdir("workdir/repo/.git/objects")+ mustWrite("workdir/repo/.git/objects/pack", "binary")+ mustMkdir("workdir/repo/node_modules/lodash")+ mustWrite("workdir/repo/node_modules/lodash/index.js", "module.exports = {}")+ mustMkdir("workdir/repo/.next/cache")+ mustWrite("workdir/repo/.next/cache/page.html", "<html></html>")+ mustMkdir("workdir/repo/.turbo")+ mustWrite("workdir/repo/.turbo/log", "trace")+ mustMkdir("workdir/repo/dist") // not in default patterns — must be preserved+ mustWrite("workdir/repo/dist/main.js", "compiled")+ mustWrite(".gc_meta.json", `{"issue_id":"x"}`)+ mustMkdir("output")+ mustWrite("output/result.txt", "done")++ removed, bytes, perPattern := d.cleanTaskArtifacts(taskDir, []string{"node_modules", ".next", ".turbo"})++ if removed != 3 {+ t.Fatalf("expected 3 artifact dirs removed, got %d", removed)+ }+ if bytes <= 0 {+ t.Fatalf("expected non-zero bytes reclaimed, got %d", bytes)+ }+ if perPattern["node_modules"] != 1 || perPattern[".next"] != 1 || perPattern[".turbo"] != 1 {+ t.Fatalf("unexpected per-pattern counts: %+v", perPattern)+ }++ // Verify protected paths are intact.+ for _, rel := range []string{+ "workdir/repo/src/index.ts",+ "workdir/repo/.git/objects/pack",+ "workdir/repo/dist/main.js",+ "output/result.txt",+ ".gc_meta.json",+ } {+ if _, err := os.Stat(filepath.Join(taskDir, rel)); err != nil {+ t.Errorf("expected %s to be preserved, got %v", rel, err)+ }+ }++ // Verify removed paths are gone.+ for _, rel := range []string{+ "workdir/repo/node_modules",+ "workdir/repo/.next",+ "workdir/repo/.turbo",+ } {+ if _, err := os.Stat(filepath.Join(taskDir, rel)); !os.IsNotExist(err) {+ t.Errorf("expected %s to be removed, stat err=%v", rel, err)+ }+ }+}++func TestCleanTaskArtifacts_RejectsPatternsWithSeparators(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ taskDir := t.TempDir()+ if err := os.MkdirAll(filepath.Join(taskDir, "workdir", "node_modules"), 0o755); err != nil {+ t.Fatal(err)+ }++ removed, _, _ := d.cleanTaskArtifacts(taskDir, []string{"workdir/node_modules", "../etc"})+ if removed != 0 {+ t.Fatalf("expected 0 removals from separator-bearing patterns, got %d", removed)+ }+ if _, err := os.Stat(filepath.Join(taskDir, "workdir", "node_modules")); err != nil {+ t.Fatalf("dir should still exist, got %v", err)+ }+}++func TestCleanTaskArtifacts_DoesNotFollowSymlinks(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ taskDir := t.TempDir()+ outside := t.TempDir()+ keepFile := filepath.Join(outside, "keep.txt")+ if err := os.WriteFile(keepFile, []byte("safe"), 0o644); err != nil {+ t.Fatal(err)+ }++ if err := os.MkdirAll(filepath.Join(taskDir, "workdir"), 0o755); err != nil {+ t.Fatal(err)+ }+ linkPath := filepath.Join(taskDir, "workdir", "node_modules")+ if err := os.Symlink(outside, linkPath); err != nil {+ t.Skipf("symlink not supported: %v", err)+ }++ removed, _, _ := d.cleanTaskArtifacts(taskDir, []string{"node_modules"})+ if removed != 0 {+ t.Fatalf("expected 0 removals (symlinked node_modules), got %d", removed)+ }+ if _, err := os.Stat(keepFile); err != nil {+ t.Fatalf("symlinked target was deleted: %v", err)+ }+}++func TestActiveEnvRootRefcount(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ root := "/tmp/fake/env"++ if d.isActiveEnvRoot(root) {+ t.Fatal("expected inactive before mark")+ }+ d.markActiveEnvRoot(root)+ d.markActiveEnvRoot(root) // second mark from reuse path+ if !d.isActiveEnvRoot(root) {+ t.Fatal("expected active after mark")+ }+ d.unmarkActiveEnvRoot(root)+ if !d.isActiveEnvRoot(root) {+ t.Fatal("expected still active after one unmark")+ }+ d.unmarkActiveEnvRoot(root)+ if d.isActiveEnvRoot(root) {+ t.Fatal("expected inactive after both unmarks")+ }+}+func TestIsBareRepo(t *testing.T) {t.Parallel()