Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-6085: fix(daemon): add completed-task environment retention TTL (#6949)

iiwish8787003cab4a
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 601a91c042..1332ec2d28 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -258,6 +258,7 @@ Daemon behavior is configured via flags or environment variables:
| GC enabled | — | `MULTICA_GC_ENABLED` | `true` (set `false`/`0` to disable) |
| GC scan interval | — | `MULTICA_GC_INTERVAL` | `2h` |
| GC TTL (done/cancelled issues) | — | `MULTICA_GC_TTL` | `24h` |
+| GC completed-task TTL (issue tasks) | — | `MULTICA_GC_COMPLETED_TASK_TTL` | `0` (disabled) |
| GC orphan TTL (no `.gc_meta.json`) | — | `MULTICA_GC_ORPHAN_TTL` | `72h` |
| GC artifact TTL (completed tasks) | — | `MULTICA_GC_ARTIFACT_TTL` | `12h` (set `0` to disable) |
| GC artifact patterns | — | `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` |
@@ -268,9 +269,10 @@ Daemon behavior is configured via flags or environment variables:
#### Workspace garbage collection
-The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and reclaims disk space in four modes:
+The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and applies several disk-reclamation policies:
- **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.
+- **Completed-task retention bound** — set `MULTICA_GC_COMPLETED_TASK_TTL` to fully remove an inactive issue task once its `.gc_meta.json` `completed_at` age exceeds the configured duration, even while the parent issue remains open. The default `0` disables this opt-in policy. Cleanup waits for a successful parent-issue status check, never removes an active environment, and never fully removes a `local_directory` environment. A later rerun provisions a fresh environment instead of resuming the removed checkout.
- **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 daemon also reclaims the exact managed path `codex-home/.sandbox-bin`; old task metadata without `completed_at` becomes eligible for this managed-only cleanup after its `.gc_meta.json` file has been idle for `MULTICA_GC_ORPHAN_TTL`. The rest of the task (source, `.git`, `output/`, `logs/`, `.gc_meta.json`, Codex auth/config/session state) is preserved so the agent can resume it.
- **Managed-cache reclamation** — the exact managed path above is reclaimed for *every* task kind once the task has been completed for `MULTICA_GC_ARTIFACT_TTL`, not just for issue tasks whose issue is still open. It applies even while the parent record says the directory itself must stay — an active chat session, a still-running autopilot run — and even when the parent record could not be reached this cycle, because the contents are regenerable and the next run re-provisions them on demand. A task currently running on the directory is never touched. Set `MULTICA_GC_ARTIFACT_TTL=0` to disable this along with the rest of artifact cleanup.
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index e84fb88486..eb4972c99b 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -68,6 +68,7 @@ const (
DefaultMaxConcurrentTasks = 20
DefaultGCInterval = 2 * time.Hour
DefaultGCTTL = 24 * time.Hour // 1 day — AI-coding issues rarely stay open long
+ DefaultGCCompletedTaskTTL = 0 // disabled — operators may bound completed issue-task env retention independently of issue status
DefaultGCOrphanTTL = 72 * time.Hour // 3 days — orphans with no meta (crashes, pre-GC leftovers)
DefaultGCArtifactTTL = 12 * time.Hour // 12h — drop regenerable artifacts once a task has been completed this long
DefaultGCCodexSessionTTL = 14 * 24 * time.Hour // 14 days — reclaim per-issue Codex session stores untouched this long
@@ -103,6 +104,7 @@ type Config struct {
GCEnabled bool // enable periodic workspace garbage collection (default: true)
GCInterval time.Duration // how often the GC loop runs (default: 2h)
GCTTL time.Duration // clean dirs whose issue is done/cancelled and updated_at < now()-TTL (default: 24h)
+ GCCompletedTaskTTL time.Duration // fully clean inactive issue-task envs completed at least this long ago, regardless of parent issue status (default: 0, disabled; local_directory envs are never fully removed)
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 // once a task has been completed for at least this long, drop regenerable artifacts: pattern-matched build outputs when the parent record keeps the directory (an open issue), and the exact daemon-managed Codex cache for every task kind (default: 12h, set 0 to disable both)
GCArtifactPatterns []string // basename patterns whose subtrees are removed during artifact cleanup (default: node_modules, .next, .turbo)
@@ -452,6 +454,10 @@ func LoadConfig(overrides Overrides) (Config, error) {
if err != nil {
return Config{}, err
}
+ gcCompletedTaskTTL, err := durationFromEnv("MULTICA_GC_COMPLETED_TASK_TTL", DefaultGCCompletedTaskTTL)
+ if err != nil {
+ return Config{}, err
+ }
gcOrphanTTL, err := durationFromEnv("MULTICA_GC_ORPHAN_TTL", DefaultGCOrphanTTL)
if err != nil {
return Config{}, err
@@ -524,6 +530,7 @@ func LoadConfig(overrides Overrides) (Config, error) {
GCEnabled: gcEnabled,
GCInterval: gcInterval,
GCTTL: gcTTL,
+ GCCompletedTaskTTL: gcCompletedTaskTTL,
GCOrphanTTL: gcOrphanTTL,
GCArtifactTTL: gcArtifactTTL,
GCArtifactPatterns: gcArtifactPatterns,
diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.go
index 49d21142a6..b17d5520ad 100644
--- a/server/internal/daemon/config_test.go
+++ b/server/internal/daemon/config_test.go
@@ -112,6 +112,39 @@ func TestDefaultGCIntervalIsTwoHours(t *testing.T) {
}
}
+func TestLoadConfig_CompletedTaskTTLDefaultsDisabledAndReadsEnv(t *testing.T) {
+ stageFakeAgent(t)
+ t.Setenv("HOME", t.TempDir())
+ t.Setenv("SHELL", filepath.Join(t.TempDir(), "missing-shell"))
+ t.Setenv("MULTICA_GC_COMPLETED_TASK_TTL", "")
+
+ overrides := Overrides{
+ ServerURL: "http://localhost:0",
+ WorkspacesRoot: t.TempDir(),
+ }
+ cfg, err := LoadConfig(overrides)
+ if err != nil {
+ t.Fatalf("LoadConfig with default completed-task TTL: %v", err)
+ }
+ if cfg.GCCompletedTaskTTL != 0 {
+ t.Fatalf("GCCompletedTaskTTL = %s, want disabled", cfg.GCCompletedTaskTTL)
+ }
+
+ t.Setenv("MULTICA_GC_COMPLETED_TASK_TTL", "36h")
+ cfg, err = LoadConfig(overrides)
+ if err != nil {
+ t.Fatalf("LoadConfig with completed-task TTL: %v", err)
+ }
+ if cfg.GCCompletedTaskTTL != 36*time.Hour {
+ t.Fatalf("GCCompletedTaskTTL = %s, want 36h", cfg.GCCompletedTaskTTL)
+ }
+
+ t.Setenv("MULTICA_GC_COMPLETED_TASK_TTL", "not-a-duration")
+ if _, err := LoadConfig(overrides); err == nil || !strings.Contains(err.Error(), "MULTICA_GC_COMPLETED_TASK_TTL") {
+ t.Fatalf("LoadConfig invalid completed-task TTL error = %v, want named validation error", err)
+ }
+}
+
func TestRepoMaintenanceKillSwitchDefaultsOnAndCanDisable(t *testing.T) {
t.Setenv("MULTICA_GC_REPO_MAINTENANCE_ENABLED", "")
if !boolFromEnv("MULTICA_GC_REPO_MAINTENANCE_ENABLED", true) {
diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.go
index f30e2ec132..aecbe5e867 100644
--- a/server/internal/daemon/gc.go
+++ b/server/internal/daemon/gc.go
@@ -20,8 +20,8 @@ import (
// them, so every walk over the root has to decide explicitly what to do with it.
const reposDirName = ".repos"
-// gcLoop periodically scans local workspace directories and removes those
-// whose issue is done/cancelled and hasn't been updated within the configured TTL.
+// gcLoop periodically scans local workspace directories and applies the
+// configured retention policies.
func (d *Daemon) gcLoop(ctx context.Context) {
if !d.cfg.GCEnabled {
d.logger.Info("gc: disabled")
@@ -30,6 +30,7 @@ func (d *Daemon) gcLoop(ctx context.Context) {
d.logger.Info("gc: started",
"interval", d.cfg.GCInterval,
"ttl", d.cfg.GCTTL,
+ "completed_task_ttl", d.cfg.GCCompletedTaskTTL,
"orphan_ttl", d.cfg.GCOrphanTTL,
"artifact_ttl", d.cfg.GCArtifactTTL,
"repo_ttl", d.cfg.GCRepoTTL,
@@ -59,7 +60,7 @@ 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)
+ cleaned int // whole task dirs removed by a parent-lifecycle or completed-task policy
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
@@ -276,14 +277,12 @@ func (d *Daemon) applyGCAction(taskDir string, action gcAction, stats *gcStats)
}
switch action {
case gcActionClean:
- bytes := dirSize(taskDir)
- d.cleanTaskDir(taskDir)
+ bytes := d.cleanTaskDir(taskDir)
stats.cleaned++
stats.bytesReclaimed += bytes
return 1
case gcActionOrphan:
- bytes := dirSize(taskDir)
- d.cleanTaskDir(taskDir)
+ bytes := d.cleanTaskDir(taskDir)
stats.orphaned++
stats.bytesReclaimed += bytes
return 1
@@ -320,7 +319,7 @@ type gcAction int
const (
gcActionSkip gcAction = iota
- gcActionClean // issue is done/cancelled and stale
+ gcActionClean // a parent-lifecycle or completed-task policy selected full cleanup
gcActionOrphan // no meta or unknown issue and dir is old
gcActionCleanArtifacts // task completed long enough ago; drop regenerable artifacts only
gcActionCleanManagedArtifacts // preserve the task and drop exact daemon-managed artifacts only
@@ -517,6 +516,30 @@ func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, res
return gcActionClean
}
+ // Operators may opt into a hard retention bound for completed issue-task
+ // environments even while the parent issue stays open. A successful parent
+ // lookup with a recognized status is intentionally required: transient
+ // network/auth failures and response drift keep data rather than turning an
+ // unavailable or malformed status into a deletion signal.
+ // The active-root guard and reservation protect concurrent reuse. User-owned
+ // local_directory envs stay on the existing artifact-only policy so a shorter
+ // completed-task TTL cannot make artifact cleanup happen early.
+ if d.cfg.GCCompletedTaskTTL > 0 &&
+ !meta.LocalDirectory &&
+ !meta.CompletedAt.IsZero() &&
+ isKnownIssueStatus(result.Status) &&
+ time.Since(meta.CompletedAt) > d.cfg.GCCompletedTaskTTL {
+ d.logger.Info("gc: completed task eligible for full cleanup",
+ "dir", filepath.Base(taskDir),
+ "kind", "issue",
+ "issue", meta.IssueID,
+ "status", result.Status,
+ "completed_at", meta.CompletedAt.Format(time.RFC3339),
+ "completed_task_ttl", d.cfg.GCCompletedTaskTTL,
+ )
+ return gcActionClean
+ }
+
if d.cfg.GCArtifactTTL > 0 && !meta.CompletedAt.IsZero() && time.Since(meta.CompletedAt) > d.cfg.GCArtifactTTL {
d.logger.Info("gc: eligible for artifact cleanup",
"dir", filepath.Base(taskDir),
@@ -549,6 +572,18 @@ func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, res
return gcActionSkip
}
+// isKnownIssueStatus mirrors the issue status constraint enforced by the
+// server. Full task cleanup must fail closed when an older daemon receives a
+// future status or a malformed response from the GC check endpoint.
+func isKnownIssueStatus(status string) bool {
+ switch status {
+ case "backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled":
+ return true
+ default:
+ return false
+ }
+}
+
func gcMetaFileAge(taskDir string) (time.Duration, bool) {
info, err := os.Stat(filepath.Join(taskDir, ".gc_meta.json"))
if err != nil {
@@ -716,13 +751,17 @@ func isAgentTaskTerminal(status string) bool {
}
}
-// cleanTaskDir removes a task directory and logs the result.
-func (d *Daemon) cleanTaskDir(taskDir string) {
+// cleanTaskDir removes a task directory, logs the reclaimed bytes, and returns
+// that count for the cycle summary. A failed removal reports zero reclaimed.
+func (d *Daemon) cleanTaskDir(taskDir string) int64 {
+ bytes := dirSize(taskDir)
if err := os.RemoveAll(taskDir); err != nil {
d.logger.Warn("gc: remove task dir failed", "dir", taskDir, "error", err)
+ return 0
} else {
- d.logger.Info("gc: removed", "dir", taskDir)
+ d.logger.Info("gc: removed", "dir", taskDir, "bytes_reclaimed", bytes)
}
+ return bytes
}
// linkedDirModes are the mode bits that mark a directory entry as a link to
diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.go
index c2e7f6b4cd..0390ee8ce4 100644
--- a/server/internal/daemon/gc_test.go
+++ b/server/internal/daemon/gc_test.go
@@ -197,15 +197,16 @@ func TestShouldCleanTaskDir_APIErrorSkipped(t *testing.T) {
})
d := newGCTestDaemon(t, mux)
+ d.cfg.GCCompletedTaskTTL = time.Hour
taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "task7", &execenv.GCMeta{
IssueID: issueID,
WorkspaceID: "ws1",
- CompletedAt: time.Now(),
+ CompletedAt: time.Now().Add(-2 * time.Hour),
})
action := d.shouldCleanTaskDir(context.Background(), taskDir)
if action != gcActionSkip {
- t.Fatalf("expected gcActionSkip on API error, got %d", action)
+ t.Fatalf("expected gcActionSkip on API error despite completed-task TTL, got %d", action)
}
}
@@ -265,12 +266,15 @@ func TestCleanTaskDir_RemovesDirectory(t *testing.T) {
t.Parallel()
d := newGCTestDaemon(t, http.NewServeMux())
taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "doomed", nil)
+ writeFile(t, filepath.Join(taskDir, "workdir", "payload.bin"), 64)
if _, err := os.Stat(taskDir); err != nil {
t.Fatal("task dir should exist before cleanup")
}
- d.cleanTaskDir(taskDir)
+ if bytes := d.cleanTaskDir(taskDir); bytes < 64 {
+ t.Fatalf("reclaimed bytes = %d, want at least payload size", bytes)
+ }
if _, err := os.Stat(taskDir); !os.IsNotExist(err) {
t.Fatal("task dir should be removed after cleanup")
@@ -366,6 +370,40 @@ func TestGCWorkspace_BatchesAndDeduplicatesIssueChecks(t *testing.T) {
}
}
+func TestGCWorkspace_CompletedTaskTTLRemovesOpenIssue(t *testing.T) {
+ t.Parallel()
+ issueID := "77777777-7777-7777-7777-777777777770"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/api/daemon/workspaces/ws-completed/issues/gc-check", func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{"issues": []map[string]any{
+ {"id": issueID, "found": true, "status": "in_review", "updated_at": time.Now()},
+ }})
+ })
+
+ d := newGCTestDaemon(t, mux)
+ d.cfg.GCCompletedTaskTTL = 24 * time.Hour
+ d.cfg.GCArtifactTTL = 0
+ wsDir := filepath.Join(d.cfg.WorkspacesRoot, "ws-completed")
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws-completed", "completed-open", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue,
+ IssueID: issueID,
+ WorkspaceID: "ws-completed",
+ CompletedAt: time.Now().Add(-25 * time.Hour),
+ })
+ writeFile(t, filepath.Join(taskDir, "workdir", "checkout.bin"), 128)
+
+ stats := &gcStats{byPattern: map[string]int{}}
+ d.gcWorkspace(context.Background(), wsDir, stats)
+
+ if _, err := os.Stat(taskDir); !os.IsNotExist(err) {
+ t.Fatalf("completed open-issue task dir should be removed, stat error = %v", err)
+ }
+ if stats.cleaned != 1 || stats.skipped != 0 || stats.bytesReclaimed < 128 {
+ t.Fatalf("unexpected stats after completed-task cleanup: %+v", stats)
+ }
+}
+
func TestGCWorkspace_OldServerFallbackIsCached(t *testing.T) {
issueA := "77777777-7777-7777-7777-777777777773"
issueB := "77777777-7777-7777-7777-777777777774"
@@ -423,6 +461,7 @@ func TestGCWorkspace_BatchFailureDoesNotFanOutOrClean(t *testing.T) {
})
d := newGCTestDaemon(t, mux)
+ d.cfg.GCCompletedTaskTTL = time.Hour
wsDir := filepath.Join(d.cfg.WorkspacesRoot, "ws-fail")
taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws-fail", "task", &execenv.GCMeta{
IssueID: issueID, WorkspaceID: "ws-fail", CompletedAt: time.Now().Add(-10 * 24 * time.Hour),
@@ -533,6 +572,154 @@ func TestShouldCleanTaskDir_OpenIssueArtifactCleanup(t *testing.T) {
}
}
+func TestShouldCleanTaskDir_CompletedTaskTTLRemovesOpenIssue(t *testing.T) {
+ t.Parallel()
+ issueID := "88888888-8888-8888-8888-888888888880"
+
+ 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_review",
+ "updated_at": time.Now(),
+ })
+ })
+
+ d := newGCTestDaemon(t, mux)
+ d.cfg.GCCompletedTaskTTL = 24 * time.Hour
+ d.cfg.GCArtifactTTL = 0
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "completed-open", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue,
+ IssueID: issueID,
+ WorkspaceID: "ws1",
+ CompletedAt: time.Now().Add(-25 * time.Hour),
+ })
+
+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionClean {
+ t.Fatalf("expected completed-task TTL to clean open issue env, got %d", action)
+ }
+
+ recentTaskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "recently-completed-open", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue,
+ IssueID: issueID,
+ WorkspaceID: "ws1",
+ CompletedAt: time.Now().Add(-23 * time.Hour),
+ })
+ if action := d.shouldCleanTaskDir(context.Background(), recentTaskDir); action != gcActionSkip {
+ t.Fatalf("expected completed-task TTL to preserve a recent open-issue env, got %d", action)
+ }
+}
+
+func TestShouldCleanTaskDir_CompletedTaskTTLUnknownIssueStatusFailsClosed(t *testing.T) {
+ t.Parallel()
+ issueID := "88888888-8888-8888-8888-888888888884"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{
+ "status": "future_or_malformed_status", "updated_at": time.Now(),
+ })
+ })
+
+ d := newGCTestDaemon(t, mux)
+ d.cfg.GCCompletedTaskTTL = time.Hour
+ d.cfg.GCArtifactTTL = 0
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "completed-unknown-status", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue,
+ IssueID: issueID,
+ WorkspaceID: "ws1",
+ CompletedAt: time.Now().Add(-2 * time.Hour),
+ })
+
+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {
+ t.Fatalf("expected unknown issue status to fail closed, got %d", action)
+ }
+}
+
+func TestShouldCleanTaskDir_CompletedTaskTTLRequiresCompletionTime(t *testing.T) {
+ t.Parallel()
+ issueID := "88888888-8888-8888-8888-888888888881"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{
+ "status": "blocked", "updated_at": time.Now(),
+ })
+ })
+
+ d := newGCTestDaemon(t, mux)
+ d.cfg.GCCompletedTaskTTL = time.Hour
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "missing-completion", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue, IssueID: issueID, WorkspaceID: "ws1",
+ })
+
+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {
+ t.Fatalf("expected task without completed_at to remain, got %d", action)
+ }
+}
+
+func TestShouldCleanTaskDir_CompletedTaskTTLKeepsLocalDirectoryArtifactTTLSeparate(t *testing.T) {
+ t.Parallel()
+ issueID := "88888888-8888-8888-8888-888888888882"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{
+ "status": "in_progress", "updated_at": time.Now(),
+ })
+ })
+
+ d := newGCTestDaemon(t, mux)
+ d.cfg.GCCompletedTaskTTL = time.Hour
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "local-directory-recent", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue,
+ IssueID: issueID,
+ WorkspaceID: "ws1",
+ CompletedAt: time.Now().Add(-2 * time.Hour),
+ LocalDirectory: true,
+ })
+
+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {
+ t.Fatalf("expected completed-task TTL not to accelerate local_directory artifact cleanup, got %d", action)
+ }
+
+ artifactEligibleDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "local-directory-artifact-eligible", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue,
+ IssueID: issueID,
+ WorkspaceID: "ws1",
+ CompletedAt: time.Now().Add(-13 * time.Hour),
+ LocalDirectory: true,
+ })
+ if action := d.shouldCleanTaskDir(context.Background(), artifactEligibleDir); action != gcActionCleanArtifacts {
+ t.Fatalf("expected existing artifact TTL to remain effective for local_directory env, got %d", action)
+ }
+}
+
+func TestShouldCleanTaskDir_CompletedTaskTTLPreservesActiveEnv(t *testing.T) {
+ t.Parallel()
+ issueID := "88888888-8888-8888-8888-888888888883"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {
+ json.NewEncoder(w).Encode(map[string]any{
+ "status": "todo", "updated_at": time.Now(),
+ })
+ })
+
+ d := newGCTestDaemon(t, mux)
+ d.cfg.GCCompletedTaskTTL = time.Hour
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "active-completed", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue, IssueID: issueID, WorkspaceID: "ws1",
+ CompletedAt: time.Now().Add(-2 * time.Hour),
+ })
+ d.markActiveEnvRoot(taskDir)
+ defer d.unmarkActiveEnvRoot(taskDir)
+
+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {
+ t.Fatalf("expected active env to remain despite completed-task TTL, got %d", action)
+ }
+}
+
func TestShouldCleanTaskDir_OpenIssueRecentTaskSkipped(t *testing.T) {
t.Parallel()
issueID := "88888888-8888-8888-8888-888888888889"