Skip to content

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

Go

MUL-6038: fix(daemon): reclaim the managed Codex sandbox cache for every task kind (#6794)

Bohan Jiang78c1e24e903e
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index ec321ed7ab..dc6c143338 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -217,7 +217,7 @@ Daemon behavior is configured via flags or environment variables:
| GC scan interval | — | `MULTICA_GC_INTERVAL` | `2h` |
| 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 TTL (completed tasks) | — | `MULTICA_GC_ARTIFACT_TTL` | `12h` (set `0` to disable) |
| GC artifact patterns | — | `MULTICA_GC_ARTIFACT_PATTERNS` | `node_modules,.next,.turbo` |
| GC repo cache TTL (`.repos`) | — | `MULTICA_GC_REPO_TTL` | `720h` (30d; set `0` to disable) |
| GC repo maintenance | — | `MULTICA_GC_REPO_MAINTENANCE_ENABLED` | `true` (set `false`/`0` to disable heavy Git maintenance only) |
@@ -230,6 +230,7 @@ The daemon periodically scans `MULTICA_WORKSPACES_ROOT` and reclaims disk space
- **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 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.
- **Repo cache eviction** — the bare git clones under `.repos/` are shared object stores: each task workdir is a `git worktree` off one of them rather than its own clone, so a task's `.git` is only a pointer file. They are evicted only when all of the following hold: the repo is no longer attached to any workspace this daemon watches, it has no worktrees left, and no task has created a worktree from it for `MULTICA_GC_REPO_TTL`. A cache created before this stamp existed is not treated as ancient — its clock starts at the first GC cycle that sees it, so upgrading does not wipe every cache. Evicting is safe by construction: the next task that needs the repo re-clones it on demand, so a wrong eviction costs a clone, not a failure.
diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.go
index b5114326eb..159408c023 100644
--- a/server/internal/daemon/config.go
+++ b/server/internal/daemon/config.go
@@ -68,7 +68,7 @@ const (
DefaultGCInterval = 2 * time.Hour
DefaultGCTTL = 24 * time.Hour // 1 day — AI-coding issues rarely stay open long
DefaultGCOrphanTTL = 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
+ 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
DefaultGCHermesMemoryTTL = 90 * 24 * time.Hour // 90 days — reclaim per-agent Hermes memory stores untouched this long (long: reclaiming these is visible amnesia, and they are a few markdown files)
DefaultGCRepoTTL = 30 * 24 * time.Hour // 30 days — evict a bare repo cache no task has checked out this long
@@ -102,7 +102,7 @@ type Config struct {
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)
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)
+ 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)
GCRepoTTL time.Duration // evict a cached bare repo under .repos once no task has created a worktree from it for this long, it has no worktrees left, and it is no longer attached to any watched workspace (default: 30d, set 0 to disable)
GCRepoMaintenanceEnabled bool // run reflog expiry and git gc after stale agent refs are removed (default: true; disable independently as an operational kill switch)
diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.go
index 470816da8e..e2483857bf 100644
--- a/server/internal/daemon/gc.go
+++ b/server/internal/daemon/gc.go
@@ -237,11 +237,16 @@ func (d *Daemon) gcWorkspaceIssues(ctx context.Context, workspaceID string, cand
issueID := strings.TrimSpace(candidate.meta.IssueID)
result, ok := results[issueID]
if !ok || result.Err != nil {
- stats.skipped++
+ // No usable answer about the parent issue this cycle, so the task
+ // data stays. The regenerable Codex cache is still fair game —
+ // see applyManagedArtifactFallback.
+ action := d.applyManagedArtifactFallback(candidate.taskDir, candidate.meta, gcActionSkip)
+ cleaned += d.applyGCAction(candidate.taskDir, action, stats)
continue
}
action := d.gcDecisionIssueResult(candidate.taskDir, candidate.meta, result)
action = d.applyLocalDirectoryGCOverride(candidate.meta, action)
+ action = d.applyManagedArtifactFallback(candidate.taskDir, candidate.meta, action)
cleaned += d.applyGCAction(candidate.taskDir, action, stats)
}
return cleaned
@@ -331,7 +336,56 @@ func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcActio
}
action := d.shouldCleanTaskDirForKind(ctx, taskDir, meta)
- return d.applyLocalDirectoryGCOverride(meta, action)
+ action = d.applyLocalDirectoryGCOverride(meta, action)
+ return d.applyManagedArtifactFallback(taskDir, meta, action)
+}
+
+// applyManagedArtifactFallback upgrades a skip into managed-artifact cleanup
+// once the task's own regenerable Codex cache is past GCArtifactTTL.
+//
+// Whether a task's *data* may be removed is a per-kind question: it depends on
+// the parent record, and shouldCleanTaskDirForKind is what answers it. Whether
+// the daemon's *own regenerable cache* may be reclaimed is not a per-kind
+// question at all — codex-home/.sandbox-bin is a ~285 MiB copy of the Codex
+// binary that the next run re-provisions on demand, whoever the parent is.
+// Wiring that reclaim into the issue path alone (#5654) left every other kind
+// holding the cache indefinitely; for chat that is genuinely unbounded, since a
+// session stays "active" with no time limit and Desktop's chat is the main
+// interactive surface (#6782).
+//
+// Deliberately a one-way upgrade from gcActionSkip. Clean and Orphan already
+// remove strictly more than this, and applyLocalDirectoryGCOverride owns the
+// demotions in the other direction — so this can only ever widen what a cycle
+// reclaims, never narrow it.
+//
+// Note this also fires when the GC check API call itself failed (a transient
+// network error resolves to gcActionSkip). That is intended: the cache is
+// regenerable, so it does not need a confirmed parent record the way deleting
+// task data does. The isActiveEnvRoot short-circuit above and the env-root
+// reservation in applyGCAction still keep a running task's cache intact.
+func (d *Daemon) applyManagedArtifactFallback(taskDir string, meta *execenv.GCMeta, action gcAction) gcAction {
+ if action != gcActionSkip || d.cfg.GCArtifactTTL <= 0 {
+ return action
+ }
+ // A zero CompletedAt means the task never reported completion through
+ // WriteGCMeta. Leave those to the per-kind legacy handling rather than
+ // guessing from an unrelated clock.
+ if meta.CompletedAt.IsZero() || time.Since(meta.CompletedAt) <= d.cfg.GCArtifactTTL {
+ return action
+ }
+ // completed_at never moves again for a task that stays non-terminal, so
+ // without this the decision stays "reclaim" forever and every cycle pays
+ // for a reservation and a removal pass that finds nothing. Racing a
+ // re-provision here is harmless: the next cycle picks it up.
+ if !hasManagedArtifact(taskDir) {
+ return action
+ }
+ d.logger.Info("gc: eligible for managed artifact cleanup",
+ "dir", filepath.Base(taskDir),
+ "kind", string(meta.Kind),
+ "completed_at", meta.CompletedAt.Format(time.RFC3339),
+ )
+ return gcActionCleanManagedArtifacts
}
func (d *Daemon) applyLocalDirectoryGCOverride(meta *execenv.GCMeta, action gcAction) gcAction {
@@ -523,10 +577,18 @@ func (d *Daemon) gcDecisionChat(ctx context.Context, taskDir string, meta *exece
switch status.Status {
case "active":
- // An active chat session must never be reclaimed by mtime — that
- // would silently kill a user's idle session and break "PriorWorkDir"
- // resume on their next message. This is the explicit short-circuit
- // the issue body called out as verifyable behavior #2.
+ // An active chat session's directory must never be reclaimed by mtime
+ // — that would silently kill a user's idle session and break
+ // "PriorWorkDir" resume on their next message.
+ //
+ // This protects the session's own data, not the daemon's regenerable
+ // caches. shouldCleanTaskDir layers applyManagedArtifactFallback on top
+ // of this skip, so a session idle past GCArtifactTTL gives back
+ // codex-home/.sandbox-bin and the next message re-provisions it. That
+ // costs a ~285 MiB Codex bootstrap on resume and is the same trade-off
+ // gcDecisionIssueResult already makes for a completed task whose issue
+ // is still open — without it an active session pins the cache forever
+ // (#6782).
return gcActionSkip
case "archived":
if time.Since(status.UpdatedAt) > d.cfg.GCTTL {
@@ -684,8 +746,97 @@ func (d *Daemon) cleanTaskArtifacts(taskDir string, patterns []string) (removed
return d.cleanTaskArtifactsMatching(taskDir, newArtifactMatcher(patterns, execenv.ManagedReclaimableArtifactSubpaths()))
}
+// cleanManagedTaskArtifacts removes the exact daemon-managed artifact subpaths
+// under taskDir.
+//
+// The managed set is a list of exact relative paths, so these are addressed
+// directly rather than searched for. Walking the whole task tree to find a
+// directory whose location is already known costs a full repo checkout's worth
+// of stat calls, and a task that stays non-terminal — an active chat session —
+// pays it on every GC cycle for as long as it lives, long after the cache is
+// gone. cleanTaskArtifacts still walks, because its basename patterns can match
+// at any depth; this one has nothing to search for.
func (d *Daemon) cleanManagedTaskArtifacts(taskDir string) (removed int, bytes int64, perPattern map[string]int) {
- return d.cleanTaskArtifactsMatching(taskDir, newArtifactMatcher(nil, execenv.ManagedReclaimableArtifactSubpaths()))
+ perPattern = map[string]int{}
+ if taskDir == "" {
+ return
+ }
+ absRoot, err := filepath.Abs(taskDir)
+ if err != nil {
+ return
+ }
+ for _, subpath := range execenv.ManagedReclaimableArtifactSubpaths() {
+ rel, ok := safeRelativePath(subpath)
+ if !ok {
+ continue
+ }
+ target, ok := managedArtifactTarget(absRoot, rel)
+ if !ok {
+ continue
+ }
+ size := dirSize(target)
+ if rmErr := os.RemoveAll(target); rmErr != nil {
+ d.logger.Warn("gc: artifact remove failed", "path", target, "error", rmErr)
+ continue
+ }
+ removed++
+ bytes += size
+ perPattern[managedArtifactPatternPrefix+filepath.ToSlash(rel)]++
+ d.logger.Info("gc: artifact removed", "path", target, "bytes", size)
+ }
+ return
+}
+
+// managedArtifactTarget resolves one managed relative subpath under absRoot to
+// an absolute path that is safe to remove, reporting false when there is
+// nothing to reclaim.
+//
+// The tree walk this replaces refused to descend through symlinks and Windows
+// junctions: the per-task codex-home links the user's real skills, Codex
+// session store and plugin cache into itself, so following one would put
+// RemoveAll inside the user's home. Addressing the path directly means every
+// component between absRoot and the leaf has to be re-checked, not just the
+// leaf. See linkedDirModes.
+//
+// Containment needs no separate check: safeRelativePath has already rejected
+// absolute paths and anything that escapes upward, and filepath.Clean leaves no
+// interior "..", so joining the components one at a time cannot leave absRoot.
+func managedArtifactTarget(absRoot, rel string) (string, bool) {
+ current := absRoot
+ for _, part := range strings.Split(rel, string(filepath.Separator)) {
+ current = filepath.Join(current, part)
+ info, err := os.Lstat(current)
+ if err != nil {
+ // Already reclaimed, never created, or unreadable — all three mean
+ // "nothing for this cycle to do".
+ return "", false
+ }
+ if info.Mode()&linkedDirModes != 0 || !info.IsDir() {
+ return "", false
+ }
+ }
+ return current, true
+}
+
+// hasManagedArtifact reports whether any managed subpath is actually present.
+// Without this the decision layer keeps returning gcActionCleanManagedArtifacts
+// for a long-lived task whose completed_at never moves again, so every cycle
+// takes an env-root reservation and logs a reclaim that removes nothing.
+func hasManagedArtifact(taskDir string) bool {
+ absRoot, err := filepath.Abs(taskDir)
+ if err != nil {
+ return false
+ }
+ for _, subpath := range execenv.ManagedReclaimableArtifactSubpaths() {
+ rel, ok := safeRelativePath(subpath)
+ if !ok {
+ continue
+ }
+ if _, ok := managedArtifactTarget(absRoot, rel); ok {
+ return true
+ }
+ }
+ return false
}
func (d *Daemon) cleanTaskArtifactsMatching(taskDir string, matcher artifactMatcher) (removed int, bytes int64, perPattern map[string]int) {
diff --git a/server/internal/daemon/gc_managed_artifact_test.go b/server/internal/daemon/gc_managed_artifact_test.go
new file mode 100644
index 0000000000..199e6f9b72
--- /dev/null
+++ b/server/internal/daemon/gc_managed_artifact_test.go
@@ -0,0 +1,496 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/multica-ai/multica/server/internal/daemon/execenv"
+)
+
+// The managed Codex cache (codex-home/.sandbox-bin, a ~285 MiB copy of the
+// Codex binary) used to be reclaimed only on the issue decision path. Every
+// other kind held it for as long as its parent record said "keep the
+// directory" — unbounded for a chat session, which stays "active" with no time
+// limit. See #6782, and #5654 for the original issue-path fix.
+//
+// sandboxBinRel is the exact managed subpath, spelled out here so a change to
+// ManagedReclaimableArtifactSubpaths has to face these tests.
+const sandboxBinRel = "codex-home/.sandbox-bin"
+
+// chatGCMux serves a chat gc-check that reports the given status.
+func chatGCMux(chatID, status string) *http.ServeMux {
+ mux := http.NewServeMux()
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/chat-sessions/%s/gc-check", chatID), func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "status": status,
+ "updated_at": time.Now().Add(-100 * 24 * time.Hour),
+ })
+ })
+ return mux
+}
+
+func assertGone(t *testing.T, taskDir, rel string) {
+ t.Helper()
+ if _, err := os.Stat(filepath.Join(taskDir, rel)); !os.IsNotExist(err) {
+ t.Fatalf("%s should have been reclaimed, stat err = %v", rel, err)
+ }
+}
+
+func assertKept(t *testing.T, taskDir string, rels ...string) {
+ t.Helper()
+ for _, rel := range rels {
+ if _, err := os.Stat(filepath.Join(taskDir, rel)); err != nil {
+ t.Fatalf("%s must be preserved: %v", rel, err)
+ }
+ }
+}
+
+// TestManagedArtifact_IdleActiveChatReclaimsSandboxBin is the #6782 regression
+// test: an active chat session idle past GCArtifactTTL gives the managed Codex
+// cache back, while everything the session owns survives.
+func TestManagedArtifact_IdleActiveChatReclaimsSandboxBin(t *testing.T) {
+ t.Parallel()
+ chatID := "aaaaaaaa-0000-0000-0000-000000000001"
+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))
+
+ meta := &execenv.GCMeta{
+ Kind: execenv.GCKindChat,
+ ChatSessionID: chatID,
+ WorkspaceID: "ws",
+ CompletedAt: time.Now().Add(-24 * time.Hour), // 2x the 12h artifact TTL
+ }
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "idle-chat", meta)
+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)
+ // Everything below must survive: session data, the audit trail, and a
+ // user-owned directory that merely shares the managed basename.
+ writeFile(t, filepath.Join(taskDir, "logs/run.log"), 32)
+ writeFile(t, filepath.Join(taskDir, "output/result.md"), 32)
+ writeFile(t, filepath.Join(taskDir, "codex-home/auth.json"), 32)
+ writeFile(t, filepath.Join(taskDir, "workdir/repo/.sandbox-bin/user-owned"), 32)
+
+ stats := &gcStats{byPattern: map[string]int{}}
+ action := d.shouldCleanTaskDir(context.Background(), taskDir)
+ if action != gcActionCleanManagedArtifacts {
+ t.Fatalf("want gcActionCleanManagedArtifacts, got %d", action)
+ }
+ d.applyGCAction(taskDir, action, stats)
+
+ assertGone(t, taskDir, sandboxBinRel)
+ assertKept(t, taskDir,
+ "logs/run.log",
+ "output/result.md",
+ "codex-home/auth.json",
+ "workdir/repo/.sandbox-bin/user-owned",
+ ".gc_meta.json",
+ )
+ if stats.artifactRemoved != 1 {
+ t.Fatalf("artifact_removed = %d, want 1", stats.artifactRemoved)
+ }
+ if got := stats.byPattern[managedArtifactPatternPrefix+sandboxBinRel]; got != 1 {
+ t.Fatalf("managed pattern count = %d, want 1", got)
+ }
+}
+
+// A chat session that completed recently keeps its cache — resuming inside the
+// TTL must not pay for a re-provision.
+func TestManagedArtifact_FreshActiveChatKeepsSandboxBin(t *testing.T) {
+ t.Parallel()
+ chatID := "aaaaaaaa-0000-0000-0000-000000000002"
+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))
+
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "fresh-chat", &execenv.GCMeta{
+ Kind: execenv.GCKindChat,
+ ChatSessionID: chatID,
+ WorkspaceID: "ws",
+ CompletedAt: time.Now().Add(-1 * time.Hour), // well inside the 12h TTL
+ })
+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)
+
+ if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {
+ t.Fatalf("want gcActionSkip inside the TTL, got %d", got)
+ }
+ assertKept(t, taskDir, sandboxBinRel+"/codex")
+}
+
+// MULTICA_GC_ARTIFACT_TTL=0 disables the managed reclaim along with the rest of
+// artifact cleanup — the documented opt-out.
+func TestManagedArtifact_ArtifactTTLZeroDisablesFallback(t *testing.T) {
+ t.Parallel()
+ chatID := "aaaaaaaa-0000-0000-0000-000000000003"
+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))
+ d.cfg.GCArtifactTTL = 0
+
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "no-ttl", &execenv.GCMeta{
+ Kind: execenv.GCKindChat,
+ ChatSessionID: chatID,
+ WorkspaceID: "ws",
+ CompletedAt: time.Now().Add(-365 * 24 * time.Hour),
+ })
+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)
+
+ if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {
+ t.Fatalf("want gcActionSkip with artifact TTL disabled, got %d", got)
+ }
+ assertKept(t, taskDir, sandboxBinRel+"/codex")
+}
+
+// Metadata with no completed_at stays with the per-kind legacy handling rather
+// than being reclaimed off an unrelated clock.
+func TestManagedArtifact_ZeroCompletedAtIsLeftAlone(t *testing.T) {
+ t.Parallel()
+ chatID := "aaaaaaaa-0000-0000-0000-000000000004"
+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))
+
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "legacy-chat", &execenv.GCMeta{
+ Kind: execenv.GCKindChat,
+ ChatSessionID: chatID,
+ WorkspaceID: "ws",
+ })
+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)
+
+ if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {
+ t.Fatalf("want gcActionSkip for zero completed_at, got %d", got)
+ }
+ assertKept(t, taskDir, sandboxBinRel+"/codex")
+}
+
+// The fallback is a one-way upgrade from skip: it must never weaken a decision
+// that already removes more.
+func TestManagedArtifact_NeverDowngradesStrongerActions(t *testing.T) {
+ t.Parallel()
+ d := newGCTestDaemon(t, http.NewServeMux())
+ meta := &execenv.GCMeta{
+ Kind: execenv.GCKindChat,
+ WorkspaceID: "ws",
+ CompletedAt: time.Now().Add(-365 * 24 * time.Hour),
+ }
+
+ for _, action := range []gcAction{gcActionClean, gcActionOrphan, gcActionCleanArtifacts, gcActionCleanManagedArtifacts} {
+ if got := d.applyManagedArtifactFallback("dir", meta, action); got != action {
+ t.Fatalf("action %d was rewritten to %d", action, got)
+ }
+ }
+}
+
+// The same hole existed for the other non-issue kinds. These reach a terminal
+// state quickly in practice, so they are bounded either way — but a run that
+// sits non-terminal should not pin the cache.
+func TestManagedArtifact_NonTerminalAutopilotAndQuickCreate(t *testing.T) {
+ t.Parallel()
+ runID := "bbbbbbbb-0000-0000-0000-000000000001"
+ taskID := "bbbbbbbb-0000-0000-0000-000000000002"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/autopilot-runs/%s/gc-check", runID), func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"status": "running"})
+ })
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/tasks/%s/gc-check", taskID), func(w http.ResponseWriter, r *http.Request) {
+ _ = json.NewEncoder(w).Encode(map[string]any{"status": "running"})
+ })
+ d := newGCTestDaemon(t, mux)
+
+ cases := []struct {
+ name string
+ meta *execenv.GCMeta
+ }{
+ {"autopilot_run", &execenv.GCMeta{Kind: execenv.GCKindAutopilotRun, AutopilotRunID: runID, WorkspaceID: "ws"}},
+ {"quick_create", &execenv.GCMeta{Kind: execenv.GCKindQuickCreate, TaskID: taskID, WorkspaceID: "ws"}},
+ }
+ for _, tc := range cases {
+ tc.meta.CompletedAt = time.Now().Add(-24 * time.Hour)
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", tc.name, tc.meta)
+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)
+
+ action := d.shouldCleanTaskDir(context.Background(), taskDir)
+ if action != gcActionCleanManagedArtifacts {
+ t.Fatalf("%s: want gcActionCleanManagedArtifacts, got %d", tc.name, action)
+ }
+ d.applyGCAction(taskDir, action, &gcStats{byPattern: map[string]int{}})
+ assertGone(t, taskDir, sandboxBinRel)
+ assertKept(t, taskDir, ".gc_meta.json")
+ }
+}
+
+// A task actively running on the directory keeps its cache — the fallback sits
+// behind the isActiveEnvRoot short-circuit.
+func TestManagedArtifact_ActiveEnvRootKeepsSandboxBin(t *testing.T) {
+ t.Parallel()
+ chatID := "aaaaaaaa-0000-0000-0000-000000000005"
+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))
+
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "running-chat", &execenv.GCMeta{
+ Kind: execenv.GCKindChat,
+ ChatSessionID: chatID,
+ WorkspaceID: "ws",
+ CompletedAt: time.Now().Add(-365 * 24 * time.Hour),
+ })
+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)
+
+ d.markActiveEnvRoot(taskDir)
+ if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {
+ t.Fatalf("want gcActionSkip for an active env root, got %d", got)
+ }
+ assertKept(t, taskDir, sandboxBinRel+"/codex")
+}
+
+// local_directory tasks keep their envRoot forever, so the managed cache is the
+// only thing the GC may ever take from them. The fallback must still apply.
+func TestManagedArtifact_LocalDirectoryChatReclaimsSandboxBin(t *testing.T) {
+ t.Parallel()
+ chatID := "aaaaaaaa-0000-0000-0000-000000000006"
+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))
+
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "local-chat", &execenv.GCMeta{
+ Kind: execenv.GCKindChat,
+ ChatSessionID: chatID,
+ WorkspaceID: "ws",
+ LocalDirectory: true,
+ CompletedAt: time.Now().Add(-24 * time.Hour),
+ })
+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)
+ writeFile(t, filepath.Join(taskDir, "logs/run.log"), 32)
+
+ action := d.shouldCleanTaskDir(context.Background(), taskDir)
+ if action != gcActionCleanManagedArtifacts {
+ t.Fatalf("want gcActionCleanManagedArtifacts, got %d", action)
+ }
+ d.applyGCAction(taskDir, action, &gcStats{byPattern: map[string]int{}})
+ assertGone(t, taskDir, sandboxBinRel)
+ assertKept(t, taskDir, "logs/run.log", ".gc_meta.json")
+}
+
+// Once the cache is gone, a long-lived active chat must stop re-deciding to
+// reclaim it. completed_at never moves again for a session that stays active,
+// so without a presence check the GC would take an env-root reservation and run
+// a removal pass every cycle, forever, for a directory with nothing to give.
+func TestManagedArtifact_SecondCycleIsANoOp(t *testing.T) {
+ t.Parallel()
+ chatID := "aaaaaaaa-0000-0000-0000-000000000007"
+ d := newGCTestDaemon(t, chatGCMux(chatID, "active"))
+
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "repeat-chat", &execenv.GCMeta{
+ Kind: execenv.GCKindChat,
+ ChatSessionID: chatID,
+ WorkspaceID: "ws",
+ CompletedAt: time.Now().Add(-24 * time.Hour),
+ })
+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)
+
+ first := d.shouldCleanTaskDir(context.Background(), taskDir)
+ if first != gcActionCleanManagedArtifacts {
+ t.Fatalf("first cycle: want gcActionCleanManagedArtifacts, got %d", first)
+ }
+ d.applyGCAction(taskDir, first, &gcStats{byPattern: map[string]int{}})
+ assertGone(t, taskDir, sandboxBinRel)
+
+ for cycle := 2; cycle <= 3; cycle++ {
+ if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {
+ t.Fatalf("cycle %d: want gcActionSkip once the cache is gone, got %d", cycle, got)
+ }
+ }
+
+ // A later Codex run re-provisions the cache; the GC must notice it again.
+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)
+ if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionCleanManagedArtifacts {
+ t.Fatalf("want reclaim after re-provision, got %d", got)
+ }
+}
+
+// The direct-path removal replaced a tree walk that refused to descend through
+// symlinks and junctions. It has to refuse at every component, not just the
+// leaf — codex-home links the user's real ~/.codex content into itself.
+func TestManagedArtifact_DirectRemovalDoesNotFollowLinks(t *testing.T) {
+ t.Parallel()
+ d := newGCTestDaemon(t, http.NewServeMux())
+
+ for _, tc := range []struct {
+ name string
+ linkPath string
+ }{
+ {name: "leaf", linkPath: sandboxBinRel},
+ {name: "parent", linkPath: "codex-home"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ taskDir := t.TempDir()
+ outside := t.TempDir()
+ keepFile := filepath.Join(outside, "keep")
+ writeFile(t, keepFile, 10)
+ // Mirror the shape that makes this dangerous: the link target is
+ // the user's real ~/.codex, which has a .sandbox-bin of its own.
+ // Traversing the link would resolve the managed path onto it.
+ userSandboxBin := filepath.Join(outside, ".sandbox-bin", "user-owned")
+ writeFile(t, userSandboxBin, 10)
+
+ linkPath := filepath.Join(taskDir, filepath.FromSlash(tc.linkPath))
+ if err := os.MkdirAll(filepath.Dir(linkPath), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(outside, linkPath); err != nil {
+ t.Skipf("symlink not supported: %v", err)
+ }
+
+ removed, bytes, _ := d.cleanManagedTaskArtifacts(taskDir)
+ if removed != 0 || bytes != 0 {
+ t.Fatalf("removed=%d bytes=%d, want 0 through a link", removed, bytes)
+ }
+ for _, keep := range []string{keepFile, userSandboxBin} {
+ if _, err := os.Stat(keep); err != nil {
+ t.Fatalf("link target was touched: %v", err)
+ }
+ }
+ })
+ }
+}
+
+// A repository directory that merely shares the managed leaf name is not the
+// managed path and must survive the direct removal.
+func TestManagedArtifact_DirectRemovalIgnoresSameNamedUserDir(t *testing.T) {
+ t.Parallel()
+ d := newGCTestDaemon(t, http.NewServeMux())
+
+ taskDir := t.TempDir()
+ writeFile(t, filepath.Join(taskDir, "workdir/repo/.sandbox-bin/user-owned"), 32)
+ writeFile(t, filepath.Join(taskDir, "codex-home/auth.json"), 32)
+
+ if removed, _, _ := d.cleanManagedTaskArtifacts(taskDir); removed != 0 {
+ t.Fatalf("removed=%d, want 0 when the managed path is absent", removed)
+ }
+ assertKept(t, taskDir, "workdir/repo/.sandbox-bin/user-owned", "codex-home/auth.json")
+}
+
+// When the batch issue check cannot answer (server error, scoped token), the
+// task data stays but the regenerable cache is still reclaimed.
+func TestManagedArtifact_UnreachableIssueStillReclaimsCache(t *testing.T) {
+ t.Parallel()
+ issueID := "cccccccc-0000-0000-0000-000000000001"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/api/daemon/workspaces/ws/issues/gc-checks", func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "boom", http.StatusInternalServerError)
+ })
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {
+ http.Error(w, "boom", http.StatusInternalServerError)
+ })
+ d := newGCTestDaemon(t, mux)
+
+ meta := &execenv.GCMeta{
+ Kind: execenv.GCKindIssue,
+ IssueID: issueID,
+ WorkspaceID: "ws",
+ CompletedAt: time.Now().Add(-24 * time.Hour),
+ }
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "unreachable-issue", meta)
+ writeFile(t, filepath.Join(taskDir, sandboxBinRel, "codex"), 4096)
+ writeFile(t, filepath.Join(taskDir, "output/result.md"), 32)
+
+ stats := &gcStats{byPattern: map[string]int{}}
+ d.gcWorkspaceIssues(context.Background(), "ws", []issueGCCandidate{{taskDir: taskDir, meta: meta}}, stats)
+
+ assertGone(t, taskDir, sandboxBinRel)
+ assertKept(t, taskDir, "output/result.md", ".gc_meta.json")
+}
+
+// The managed reclaim used to share cleanTaskArtifacts' tree walk and now
+// addresses its paths directly. The two must agree on exactly what they remove
+// — this pins that equivalence against the walk, which is still live for the
+// basename patterns, so a future managed subpath or a change to either side
+// cannot silently drift them apart.
+func TestManagedArtifact_DirectRemovalMatchesTreeWalk(t *testing.T) {
+ t.Parallel()
+
+ fixtures := map[string]func(t *testing.T, dir string){
+ "managed present": func(t *testing.T, dir string) {
+ writeFile(t, filepath.Join(dir, sandboxBinRel, "codex"), 4096)
+ writeFile(t, filepath.Join(dir, "codex-home/auth.json"), 16)
+ },
+ "managed absent": func(t *testing.T, dir string) {
+ writeFile(t, filepath.Join(dir, "codex-home/auth.json"), 16)
+ },
+ "user-owned same name only": func(t *testing.T, dir string) {
+ writeFile(t, filepath.Join(dir, "workdir/repo/.sandbox-bin/keep"), 16)
+ },
+ "both managed and user-owned": func(t *testing.T, dir string) {
+ writeFile(t, filepath.Join(dir, sandboxBinRel, "codex"), 4096)
+ writeFile(t, filepath.Join(dir, "workdir/repo/.sandbox-bin/keep"), 16)
+ },
+ "nested content and .git": func(t *testing.T, dir string) {
+ writeFile(t, filepath.Join(dir, sandboxBinRel, "a/b/c/codex"), 2048)
+ writeFile(t, filepath.Join(dir, sandboxBinRel, ".git/objects/x"), 16)
+ writeFile(t, filepath.Join(dir, "workdir/repo/.git/objects/y"), 16)
+ },
+ "codex-home is a regular file": func(t *testing.T, dir string) {
+ writeFile(t, filepath.Join(dir, "codex-home"), 16)
+ },
+ "sandbox-bin is a regular file": func(t *testing.T, dir string) {
+ writeFile(t, filepath.Join(dir, sandboxBinRel), 16)
+ },
+ "leaf symlink": func(t *testing.T, dir string) {
+ outside := t.TempDir()
+ writeFile(t, filepath.Join(outside, ".sandbox-bin/x"), 16)
+ if err := os.MkdirAll(filepath.Join(dir, "codex-home"), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(outside, filepath.Join(dir, sandboxBinRel)); err != nil {
+ t.Skipf("symlink not supported: %v", err)
+ }
+ },
+ "parent symlink": func(t *testing.T, dir string) {
+ outside := t.TempDir()
+ writeFile(t, filepath.Join(outside, ".sandbox-bin/x"), 16)
+ if err := os.Symlink(outside, filepath.Join(dir, "codex-home")); err != nil {
+ t.Skipf("symlink not supported: %v", err)
+ }
+ },
+ "empty task dir": func(t *testing.T, dir string) {},
+ }
+
+ d := newGCTestDaemon(t, http.NewServeMux())
+ walkMatcher := newArtifactMatcher(nil, execenv.ManagedReclaimableArtifactSubpaths())
+
+ for name, setup := range fixtures {
+ t.Run(name, func(t *testing.T) {
+ walked, direct := t.TempDir(), t.TempDir()
+ setup(t, walked)
+ setup(t, direct)
+
+ wRemoved, wBytes, wPattern := d.cleanTaskArtifactsMatching(walked, walkMatcher)
+ dRemoved, dBytes, dPattern := d.cleanManagedTaskArtifacts(direct)
+
+ if wRemoved != dRemoved || wBytes != dBytes || fmt.Sprint(wPattern) != fmt.Sprint(dPattern) {
+ t.Fatalf("walk=(%d,%d,%v) direct=(%d,%d,%v)", wRemoved, wBytes, wPattern, dRemoved, dBytes, dPattern)
+ }
+ if w, dd := survivingTree(t, walked), survivingTree(t, direct); fmt.Sprint(w) != fmt.Sprint(dd) {
+ t.Fatalf("survivors differ:\n walk=%v\n direct=%v", w, dd)
+ }
+ })
+ }
+}
+
+// survivingTree lists every path left under root, relative to it, without
+// following links out of the tree.
+func survivingTree(t *testing.T, root string) []string {
+ t.Helper()
+ var out []string
+ _ = filepath.WalkDir(root, func(p string, e os.DirEntry, err error) error {
+ if err != nil {
+ return nil
+ }
+ rel, relErr := filepath.Rel(root, p)
+ if relErr != nil {
+ return nil
+ }
+ out = append(out, rel)
+ if e.Type()&os.ModeSymlink != 0 {
+ return filepath.SkipDir
+ }
+ return nil
+ })
+ return out
+}
diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.go
index e9075677a0..c2e7f6b4cd 100644
--- a/server/internal/daemon/gc_test.go
+++ b/server/internal/daemon/gc_test.go
@@ -1766,6 +1766,13 @@ func TestShouldCleanTaskDir_ChatHardDeletedFreshMtime(t *testing.T) {
// criterion #2: an active chat session whose workdir is older than
// GCOrphanTTL must NOT be reclaimed. The only path to clean an active
// session's workdir is for the user to archive or hard-delete the session.
+//
+// #6782 narrowed this from "the GC does nothing" to "the GC never removes the
+// directory": a session idle past GCArtifactTTL now gives back the regenerable
+// codex-home/.sandbox-bin cache, which the next message re-provisions. The
+// acceptance criterion is unchanged — the session's own data survives — so
+// this asserts the surviving contents rather than the bare action value.
+// TestManagedArtifact_IdleActiveChatReclaimsSandboxBin covers the carve-out.
func TestShouldCleanTaskDir_ChatActiveResistsOldMtime(t *testing.T) {
t.Parallel()
chatID := "ffffffff-ffff-ffff-ffff-ffffffffff01"
@@ -1788,12 +1795,22 @@ func TestShouldCleanTaskDir_ChatActiveResistsOldMtime(t *testing.T) {
CompletedAt: time.Now().Add(-200 * 24 * time.Hour),
}
taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws", "active-chat", meta)
+ writeFile(t, filepath.Join(taskDir, "logs/run.log"), 32)
+ writeFile(t, filepath.Join(taskDir, "output/result.md"), 32)
if err := os.Chtimes(taskDir, time.Now().Add(-200*24*time.Hour), time.Now().Add(-200*24*time.Hour)); err != nil {
t.Fatalf("chtimes: %v", err)
}
- if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionSkip {
- t.Fatalf("active chat session must not be reclaimed even with stale mtime, got %d", got)
+ action := d.shouldCleanTaskDir(context.Background(), taskDir)
+ if action == gcActionClean || action == gcActionOrphan {
+ t.Fatalf("active chat session's directory must never be removed, got action %d", action)
+ }
+ d.applyGCAction(taskDir, action, &gcStats{byPattern: map[string]int{}})
+
+ for _, rel := range []string{".", "logs/run.log", "output/result.md", ".gc_meta.json"} {
+ if _, err := os.Stat(filepath.Join(taskDir, rel)); err != nil {
+ t.Fatalf("active chat session must keep %s: %v", rel, err)
+ }
}
}