Skip to content

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

Go

MUL-4999: reclaim managed Codex sandbox task caches

Multica Eve152d82e42e4c
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.md
index 2a305c0993..c634a79916 100644
--- a/CLI_AND_DAEMON.md
+++ b/CLI_AND_DAEMON.md
@@ -192,9 +192,9 @@ 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 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.
+- **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.
-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`.
+Configured patterns are basename-only — entries containing `/` or `\` are silently dropped — and `.git` subtrees are never descended into. The managed Codex cache is matched by its exact relative path, so a repository's own `.sandbox-bin` is not removed unless an operator explicitly adds that basename to `MULTICA_GC_ARTIFACT_PATTERNS`. 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, including the managed Codex cache, set `MULTICA_GC_ARTIFACT_TTL=0`.
Agent-specific overrides:
diff --git a/server/internal/daemon/artifact_matcher.go b/server/internal/daemon/artifact_matcher.go
new file mode 100644
index 0000000000..2bb61920ae
--- /dev/null
+++ b/server/internal/daemon/artifact_matcher.go
@@ -0,0 +1,84 @@
+package daemon
+
+import (
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+)
+
+const managedArtifactPatternPrefix = "managed:"
+
+// artifactMatcher combines operator-configured basename matches with exact
+// daemon-managed paths. Exact paths take precedence so a broad basename such
+// as .sandbox-bin cannot double-count a managed directory.
+type artifactMatcher struct {
+ basenames map[string]struct{}
+ exactPaths map[string]string
+ exactLeafNames map[string]struct{}
+}
+
+func newArtifactMatcher(patterns, managedSubpaths []string) artifactMatcher {
+ m := artifactMatcher{
+ basenames: buildPatternSet(patterns),
+ exactPaths: make(map[string]string, len(managedSubpaths)),
+ exactLeafNames: make(map[string]struct{}, len(managedSubpaths)),
+ }
+ for _, subpath := range managedSubpaths {
+ cleaned, ok := safeRelativePath(subpath)
+ if !ok {
+ continue
+ }
+ display := filepath.ToSlash(cleaned)
+ m.exactPaths[cleaned] = managedArtifactPatternPrefix + display
+ m.exactLeafNames[filepath.Base(cleaned)] = struct{}{}
+ }
+ return m
+}
+
+func (m artifactMatcher) matchDirectory(absRoot, path string, entry os.DirEntry) (string, bool) {
+ _, exactCandidate := m.exactLeafNames[entry.Name()]
+ _, basenameMatch := m.basenames[entry.Name()]
+ if !exactCandidate && !basenameMatch {
+ return "", false
+ }
+
+ // Rel and containment validation are only needed for a directory whose
+ // leaf could actually match. Most workdir entries avoid this path entirely.
+ rel, err := filepath.Rel(absRoot, path)
+ if err != nil {
+ return "", false
+ }
+ rel, ok := safeRelativePath(rel)
+ if !ok {
+ return "", false
+ }
+ if label, ok := m.exactPaths[rel]; ok {
+ return label, true
+ }
+ if basenameMatch {
+ return entry.Name(), true
+ }
+ return "", false
+}
+
+func (m artifactMatcher) managedSubpaths() []string {
+ out := make([]string, 0, len(m.exactPaths))
+ for rel := range m.exactPaths {
+ out = append(out, filepath.ToSlash(rel))
+ }
+ sort.Strings(out)
+ return out
+}
+
+func safeRelativePath(path string) (string, bool) {
+ path = strings.TrimSpace(path)
+ if path == "" || filepath.IsAbs(path) || filepath.VolumeName(path) != "" {
+ return "", false
+ }
+ cleaned := filepath.Clean(path)
+ if cleaned == "." || cleaned == ".." || strings.HasPrefix(cleaned, ".."+string(filepath.Separator)) {
+ return "", false
+ }
+ return cleaned, true
+}
diff --git a/server/internal/daemon/diskusage.go b/server/internal/daemon/diskusage.go
index f29a49f37f..2c83ca889d 100644
--- a/server/internal/daemon/diskusage.go
+++ b/server/internal/daemon/diskusage.go
@@ -43,16 +43,17 @@ type WorkspaceDiskUsage struct {
// fields always reflect the entire scan, never the post-`--top` truncated
// view — consumers that need the displayed subtotals can sum the slice.
type DiskUsageReport struct {
- WorkspacesRoot string `json:"workspaces_root"`
- GeneratedAt time.Time `json:"generated_at"`
- ArtifactPatterns []string `json:"artifact_patterns"`
- Tasks []TaskDiskUsage `json:"tasks"`
- Workspaces []WorkspaceDiskUsage `json:"workspaces"`
- TotalTaskCount int `json:"total_task_count"`
- TotalWorkspaceCount int `json:"total_workspace_count"`
- TotalSizeBytes int64 `json:"total_size_bytes"`
- TotalArtifactSizeBytes int64 `json:"total_artifact_size_bytes"`
- TotalArtifactRatio float64 `json:"total_artifact_ratio"`
+ WorkspacesRoot string `json:"workspaces_root"`
+ GeneratedAt time.Time `json:"generated_at"`
+ ArtifactPatterns []string `json:"artifact_patterns"`
+ ManagedArtifactSubpaths []string `json:"managed_artifact_subpaths"`
+ Tasks []TaskDiskUsage `json:"tasks"`
+ Workspaces []WorkspaceDiskUsage `json:"workspaces"`
+ TotalTaskCount int `json:"total_task_count"`
+ TotalWorkspaceCount int `json:"total_workspace_count"`
+ TotalSizeBytes int64 `json:"total_size_bytes"`
+ TotalArtifactSizeBytes int64 `json:"total_artifact_size_bytes"`
+ TotalArtifactRatio float64 `json:"total_artifact_ratio"`
}
// DiskUsageRoot pairs a workspaces root with the profile it was derived from
@@ -75,14 +76,15 @@ type RootDiskUsage struct {
// (never the post-`--top` truncated view) so the combined footprint stays
// accurate even when each root's table is trimmed for display.
type AggregateDiskUsageReport struct {
- GeneratedAt time.Time `json:"generated_at"`
- ArtifactPatterns []string `json:"artifact_patterns"`
- Roots []RootDiskUsage `json:"roots"`
- TotalTaskCount int `json:"total_task_count"`
- TotalWorkspaceCount int `json:"total_workspace_count"`
- TotalSizeBytes int64 `json:"total_size_bytes"`
- TotalArtifactSizeBytes int64 `json:"total_artifact_size_bytes"`
- TotalArtifactRatio float64 `json:"total_artifact_ratio"`
+ GeneratedAt time.Time `json:"generated_at"`
+ ArtifactPatterns []string `json:"artifact_patterns"`
+ ManagedArtifactSubpaths []string `json:"managed_artifact_subpaths"`
+ Roots []RootDiskUsage `json:"roots"`
+ TotalTaskCount int `json:"total_task_count"`
+ TotalWorkspaceCount int `json:"total_workspace_count"`
+ TotalSizeBytes int64 `json:"total_size_bytes"`
+ TotalArtifactSizeBytes int64 `json:"total_artifact_size_bytes"`
+ TotalArtifactRatio float64 `json:"total_artifact_ratio"`
}
// ScanDiskUsageRoots scans every root in order and returns the combined report.
@@ -92,7 +94,9 @@ type AggregateDiskUsageReport struct {
// permission error on the root directory itself) aborts the whole scan.
func ScanDiskUsageRoots(roots []DiskUsageRoot, artifactPatterns []string) (AggregateDiskUsageReport, error) {
agg := AggregateDiskUsageReport{GeneratedAt: time.Now().UTC()}
- agg.ArtifactPatterns = sortedKeys(buildPatternSet(artifactPatterns))
+ matcher := newArtifactMatcher(artifactPatterns, execenv.ManagedReclaimableArtifactSubpaths())
+ agg.ArtifactPatterns = sortedKeys(matcher.basenames)
+ agg.ManagedArtifactSubpaths = matcher.managedSubpaths()
for _, r := range roots {
report, err := ScanDiskUsage(r.Root, artifactPatterns)
@@ -118,8 +122,9 @@ const DiskUsageKindUnknown = "unknown"
// walk is read-only and follows the same safety contract as the GC artifact
// cleaner: it never enters .git, never follows symlinks, and counts only
// regular files. artifactPatterns is filtered through the basename-only check
-// used by cleanTaskArtifacts so the reported "artifact" footprint matches the
-// bytes the GC would actually reclaim. Missing roots return an empty report
+// used by cleanTaskArtifacts, and exact daemon-managed artifact paths are
+// included, so the reported "artifact" footprint matches the bytes the GC
+// would actually reclaim. Missing roots return an empty report
// (not an error) — a daemon that's never run yet has no directory to walk.
func ScanDiskUsage(workspacesRoot string, artifactPatterns []string) (DiskUsageReport, error) {
report := DiskUsageReport{
@@ -131,8 +136,9 @@ func ScanDiskUsage(workspacesRoot string, artifactPatterns []string) (DiskUsageR
return report, fmt.Errorf("disk-usage: workspaces root is required")
}
- patternSet := buildPatternSet(artifactPatterns)
- report.ArtifactPatterns = sortedKeys(patternSet)
+ matcher := newArtifactMatcher(artifactPatterns, execenv.ManagedReclaimableArtifactSubpaths())
+ report.ArtifactPatterns = sortedKeys(matcher.basenames)
+ report.ManagedArtifactSubpaths = matcher.managedSubpaths()
wsEntries, err := os.ReadDir(workspacesRoot)
if err != nil {
@@ -162,7 +168,7 @@ func ScanDiskUsage(workspacesRoot string, artifactPatterns []string) (DiskUsageR
continue
}
taskDir := filepath.Join(wsDir, t.Name())
- usage := buildTaskUsage(taskDir, wsID, t.Name(), patternSet)
+ usage := buildTaskUsage(taskDir, wsID, t.Name(), matcher)
report.Tasks = append(report.Tasks, usage)
report.TotalSizeBytes += usage.SizeBytes
@@ -236,7 +242,7 @@ func sortedKeys(set map[string]struct{}) []string {
return out
}
-func buildTaskUsage(taskDir, wsID, taskShort string, patternSet map[string]struct{}) TaskDiskUsage {
+func buildTaskUsage(taskDir, wsID, taskShort string, matcher artifactMatcher) TaskDiskUsage {
usage := TaskDiskUsage{
WorkspaceID: wsID,
WorkspaceShort: ShortID(wsID),
@@ -245,31 +251,36 @@ func buildTaskUsage(taskDir, wsID, taskShort string, patternSet map[string]struc
Kind: DiskUsageKindUnknown,
}
+ metaPresent := false
if meta, err := execenv.ReadGCMeta(taskDir); err == nil && meta != nil {
+ metaPresent = true
usage.Kind = string(meta.Kind)
if !meta.CompletedAt.IsZero() {
usage.AgeSeconds = int64(time.Since(meta.CompletedAt).Seconds())
+ } else if age, ok := gcMetaFileAge(taskDir); ok {
+ usage.AgeSeconds = int64(age.Seconds())
}
}
- // Fall back to mtime when meta is missing or didn't carry a completed_at.
- // Matches the orphanByMTime path the GC loop takes for the same case.
- if usage.AgeSeconds <= 0 {
+ // With no readable metadata, use taskDir mtime just like orphanByMTime.
+ // Legacy readable metadata without completed_at uses its own file mtime,
+ // matching gcDecisionIssueResult's managed-only fallback.
+ if usage.AgeSeconds <= 0 && !metaPresent {
if info, err := os.Stat(taskDir); err == nil {
usage.AgeSeconds = int64(time.Since(info.ModTime()).Seconds())
}
}
- usage.SizeBytes, usage.ArtifactSizeBytes = taskSize(taskDir, patternSet)
+ usage.SizeBytes, usage.ArtifactSizeBytes = taskSize(taskDir, matcher)
return usage
}
// taskSize walks taskDir and returns (totalBytes, artifactBytes). Both honor
// the GC safety contract: never descends into .git, never follows symlinks,
-// counts only regular files. A directory whose basename matches patternSet
-// is treated as an artifact subtree — its size is added to both totals and
-// the walk does not descend further so the size matches what os.RemoveAll
-// would reclaim if the GC ran cleanTaskArtifacts on it.
-func taskSize(taskDir string, patternSet map[string]struct{}) (totalBytes int64, artifactBytes int64) {
+// counts only regular files. A directory matched by matcher is treated as an
+// artifact subtree — its size is added to both totals and the walk does not
+// descend further so the size matches what os.RemoveAll would reclaim if the
+// GC ran cleanTaskArtifacts on it.
+func taskSize(taskDir string, matcher artifactMatcher) (totalBytes int64, artifactBytes int64) {
if taskDir == "" {
return
}
@@ -296,11 +307,7 @@ func taskSize(taskDir string, patternSet map[string]struct{}) (totalBytes int64,
if entry.Name() == ".git" {
return filepath.SkipDir
}
- if _, ok := patternSet[entry.Name()]; ok {
- rel, relErr := filepath.Rel(absRoot, path)
- if relErr != nil || rel == "" || rel == "." || strings.HasPrefix(rel, "..") {
- return filepath.SkipDir
- }
+ if _, ok := matcher.matchDirectory(absRoot, path, entry); ok {
size := dirSize(path)
totalBytes += size
artifactBytes += size
diff --git a/server/internal/daemon/diskusage_test.go b/server/internal/daemon/diskusage_test.go
index 5f2d45f56a..749b2defd0 100644
--- a/server/internal/daemon/diskusage_test.go
+++ b/server/internal/daemon/diskusage_test.go
@@ -193,6 +193,7 @@ func TestScanDiskUsage_AggregatesAndCategorizes(t *testing.T) {
`"workspace_id"`,
`"task_short"`,
`"artifact_ratio"`,
+ `"managed_artifact_subpaths"`,
`"total_task_count"`,
`"total_workspace_count"`,
`"total_artifact_ratio"`,
@@ -203,6 +204,66 @@ func TestScanDiskUsage_AggregatesAndCategorizes(t *testing.T) {
}
}
+func TestScanDiskUsage_ManagedCodexSandboxIsExactAndDeduplicated(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ wsID := "mmmmmmmm-mmmm-mmmm-mmmm-mmmmmmmmmmmm"
+ taskDir := filepath.Join(root, wsID, "tttttttt")
+ writeFile(t, filepath.Join(taskDir, "codex-home/.sandbox-bin/codex.exe"), 300)
+ writeFile(t, filepath.Join(taskDir, "workdir/repo/.sandbox-bin/cache"), 400)
+
+ report, err := ScanDiskUsage(root, nil)
+ if err != nil {
+ t.Fatalf("ScanDiskUsage managed-only: %v", err)
+ }
+ if got := report.Tasks[0].SizeBytes; got != 700 {
+ t.Fatalf("size_bytes=%d, want 700", got)
+ }
+ if got := report.Tasks[0].ArtifactSizeBytes; got != 300 {
+ t.Fatalf("artifact_size_bytes=%d, want exact managed 300", got)
+ }
+ if got := strings.Join(report.ManagedArtifactSubpaths, ","); got != "codex-home/.sandbox-bin" {
+ t.Fatalf("managed artifact paths=%q, want codex-home/.sandbox-bin", got)
+ }
+
+ report, err = ScanDiskUsage(root, []string{".sandbox-bin"})
+ if err != nil {
+ t.Fatalf("ScanDiskUsage broad basename: %v", err)
+ }
+ if got := report.Tasks[0].ArtifactSizeBytes; got != 700 {
+ t.Fatalf("artifact_size_bytes=%d, want 700 without double counting", got)
+ }
+}
+
+func TestScanDiskUsage_LegacyMetaAgeUsesMetaFileMTime(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ wsID := "llllllll-llll-llll-llll-llllllllllll"
+ taskDir := filepath.Join(root, wsID, "tttttttt")
+ writeFile(t, filepath.Join(taskDir, "workdir/main.go"), 10)
+ mustWriteMeta(t, taskDir, execenv.GCMeta{
+ Kind: execenv.GCKindIssue, IssueID: "issue-legacy", WorkspaceID: wsID,
+ })
+ oldRoot := time.Now().Add(-30 * 24 * time.Hour)
+ if err := os.Chtimes(taskDir, oldRoot, oldRoot); err != nil {
+ t.Fatal(err)
+ }
+ recentMeta := time.Now().Add(-2 * time.Hour)
+ if err := os.Chtimes(filepath.Join(taskDir, ".gc_meta.json"), recentMeta, recentMeta); err != nil {
+ t.Fatal(err)
+ }
+
+ report, err := ScanDiskUsage(root, nil)
+ if err != nil {
+ t.Fatalf("ScanDiskUsage: %v", err)
+ }
+ if got := report.Tasks[0].AgeSeconds; got < int64(time.Hour.Seconds()) || got > int64((3*time.Hour).Seconds()) {
+ t.Fatalf("age_seconds=%d, want metadata age near 2h instead of stale task root age", got)
+ }
+}
+
// TestScanDiskUsage_EmptyWorkspaceArtifactRatio guards the total=0 edge:
// a workspace whose tasks have no measurable bytes (or no files at all) must
// still report ArtifactRatio=0, never NaN. The CLI table renders this column,
@@ -386,6 +447,9 @@ func TestScanDiskUsageRoots_SumsAcrossRoots(t *testing.T) {
if agg.TotalWorkspaceCount != 2 {
t.Fatalf("TotalWorkspaceCount = %d, want 2", agg.TotalWorkspaceCount)
}
+ if got := strings.Join(agg.ManagedArtifactSubpaths, ","); got != "codex-home/.sandbox-bin" {
+ t.Fatalf("managed artifact paths=%q, want codex-home/.sandbox-bin", got)
+ }
}
func mustWriteMeta(t *testing.T, taskDir string, meta execenv.GCMeta) {
diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.go
index 5bab43d24b..0fd7edba2f 100644
--- a/server/internal/daemon/execenv/execenv.go
+++ b/server/internal/daemon/execenv/execenv.go
@@ -334,7 +334,7 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {
// For Codex, set up a per-task CODEX_HOME seeded from ~/.codex/ with skills.
if params.Provider == "codex" {
- codexHome := filepath.Join(envRoot, "codex-home")
+ codexHome := filepath.Join(envRoot, codexHomeDirName)
// Under the Linux workspace-write sandbox the real HOME is read-only;
// give the task a writable HOME and grant write access to it in the
// Codex config so npm/Prisma can write their caches (MUL-4856).
@@ -546,7 +546,7 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {
// lives alongside the workdir. Re-run prepareCodexHomeWithOpts to ensure
// config (especially sandbox/network access) is up to date.
if params.Provider == "codex" {
- codexHome := filepath.Join(env.RootDir, "codex-home")
+ codexHome := filepath.Join(env.RootDir, codexHomeDirName)
// Refresh the per-task writable HOME (re-seed credential symlinks in
// case the user's real home changed) and recompute the sandbox
// writable_roots on reuse, mirroring the fresh Prepare path (MUL-4856).
diff --git a/server/internal/daemon/execenv/reclaimable.go b/server/internal/daemon/execenv/reclaimable.go
new file mode 100644
index 0000000000..c478d061f6
--- /dev/null
+++ b/server/internal/daemon/execenv/reclaimable.go
@@ -0,0 +1,16 @@
+package execenv
+
+import "path/filepath"
+
+const (
+ codexHomeDirName = "codex-home"
+ codexSandboxBinDirName = ".sandbox-bin"
+)
+
+// ManagedReclaimableArtifactSubpaths returns daemon-owned, regenerable
+// directories inside a task env root. Callers must match these as exact
+// relative paths rather than basenames: a repository may legitimately contain
+// a directory with the same leaf name.
+func ManagedReclaimableArtifactSubpaths() []string {
+ return []string{filepath.Join(codexHomeDirName, codexSandboxBinDirName)}
+}
diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.go
index 1073ecec4e..6010b3c8c6 100644
--- a/server/internal/daemon/gc.go
+++ b/server/internal/daemon/gc.go
@@ -26,6 +26,7 @@ func (d *Daemon) gcLoop(ctx context.Context) {
"orphan_ttl", d.cfg.GCOrphanTTL,
"artifact_ttl", d.cfg.GCArtifactTTL,
"artifact_patterns", d.cfg.GCArtifactPatterns,
+ "managed_artifact_subpaths", execenv.ManagedReclaimableArtifactSubpaths(),
)
// Run once at startup after a short delay (let the daemon finish initializing).
@@ -56,7 +57,7 @@ type gcStats struct {
artifactRemoved int // count of removed artifact subdirs
storesReclaimed int // per-issue Codex session stores reclaimed past their TTL
bytesReclaimed int64 // total bytes freed in this cycle
- byPattern map[string]int // basename -> reclaim count, for visibility
+ byPattern map[string]int // configured basename or managed path label -> reclaim count
}
// runGC performs a single GC scan across all workspace directories.
@@ -206,7 +207,7 @@ func (d *Daemon) gcWorkspaceIssues(ctx context.Context, workspaceID string, cand
continue
}
action := d.gcDecisionIssueResult(candidate.taskDir, candidate.meta, result)
- action = applyLocalDirectoryGCOverride(candidate.meta, action)
+ action = d.applyLocalDirectoryGCOverride(candidate.meta, action)
cleaned += d.applyGCAction(candidate.taskDir, action, stats)
}
return cleaned
@@ -239,14 +240,11 @@ func (d *Daemon) applyGCAction(taskDir string, action gcAction, stats *gcStats)
return 1
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
- }
- }
+ recordArtifactCleanup(stats, removed, bytes, perPattern)
+ stats.skipped++ // task dir itself preserved
+ case gcActionCleanManagedArtifacts:
+ removed, bytes, perPattern := d.cleanManagedTaskArtifacts(taskDir)
+ recordArtifactCleanup(stats, removed, bytes, perPattern)
stats.skipped++ // task dir itself preserved
default:
stats.skipped++
@@ -254,13 +252,29 @@ func (d *Daemon) applyGCAction(taskDir string, action gcAction, stats *gcStats)
return 0
}
+func recordArtifactCleanup(stats *gcStats, removed int, bytes int64, perPattern map[string]int) {
+ if removed == 0 {
+ return
+ }
+ stats.artifactDirs++
+ stats.artifactRemoved += removed
+ stats.bytesReclaimed += bytes
+ if stats.byPattern == nil {
+ stats.byPattern = map[string]int{}
+ }
+ for pattern, count := range perPattern {
+ stats.byPattern[pattern] += count
+ }
+}
+
type gcAction int
const (
- 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
+ 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
+ gcActionCleanManagedArtifacts // preserve the task and drop exact daemon-managed artifacts only
)
// shouldCleanTaskDir decides whether a task directory should be removed.
@@ -282,34 +296,37 @@ func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcActio
}
action := d.shouldCleanTaskDirForKind(ctx, taskDir, meta)
- return applyLocalDirectoryGCOverride(meta, action)
+ return d.applyLocalDirectoryGCOverride(meta, action)
}
-func applyLocalDirectoryGCOverride(meta *execenv.GCMeta, action gcAction) gcAction {
+func (d *Daemon) applyLocalDirectoryGCOverride(meta *execenv.GCMeta, action gcAction) gcAction {
if !meta.LocalDirectory {
return action
}
// local_directory tasks keep their envRoot indefinitely so the user
// can inspect output/ and logs/ for forensic context. The WorkDir is
- // the user's own path and lives outside taskDir, so the envRoot
- // itself is just the daemon's logbook for the run — never large, and
- // safe to keep.
+ // the user's own path and lives outside taskDir. The envRoot contains
+ // the daemon's durable logbook plus regenerable tool caches, so keep the
+ // former while allowing narrowly scoped cleanup of the latter.
//
// gcActionClean → demote to artifact-pattern cleanup so envRoot
// (and especially the logbook) survives.
- // gcActionOrphan → skip outright; we don't ever wipe a
- // local_directory envRoot via the mtime path,
- // since the parent issue / chat record going
- // away should not collateral-delete the user's
- // own audit trail.
+ // gcActionOrphan → exact managed-artifact cleanup only; we don't ever
+ // wipe a local_directory envRoot via the mtime path,
+ // since the parent issue / chat record going away
+ // should not collateral-delete the user's audit trail.
//
- // gcActionCleanArtifacts and gcActionSkip already obey the
+ // Artifact cleanup remains disabled when GCArtifactTTL is explicitly zero.
+ // gcActionCleanArtifacts, gcActionCleanManagedArtifacts, and gcActionSkip obey the
// "no full envRoot RemoveAll" rule.
+ if d.cfg.GCArtifactTTL <= 0 {
+ return gcActionSkip
+ }
switch action {
case gcActionClean:
return gcActionCleanArtifacts
case gcActionOrphan:
- return gcActionSkip
+ return gcActionCleanManagedArtifacts
default:
return action
}
@@ -401,8 +418,7 @@ func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, res
return gcActionClean
}
- if d.cfg.GCArtifactTTL > 0 && len(d.cfg.GCArtifactPatterns) > 0 &&
- !meta.CompletedAt.IsZero() && time.Since(meta.CompletedAt) > d.cfg.GCArtifactTTL {
+ 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),
"kind", "issue",
@@ -413,9 +429,35 @@ func (d *Daemon) gcDecisionIssueResult(taskDir string, meta *execenv.GCMeta, res
return gcActionCleanArtifacts
}
+ // Old metadata may not have completed_at. Keep that case conservative:
+ // after the metadata file itself has been idle for the longer orphan TTL,
+ // reclaim only the exact daemon-managed cache. WriteGCMeta replaces this
+ // file after every completed task, so a recent reuse refreshes the signal
+ // even when activity below taskDir leaves the root directory mtime stale.
+ if d.cfg.GCArtifactTTL > 0 && meta.CompletedAt.IsZero() {
+ if age, ok := gcMetaFileAge(taskDir); ok && age > d.cfg.GCOrphanTTL {
+ d.logger.Info("gc: legacy task eligible for managed artifact cleanup",
+ "dir", filepath.Base(taskDir),
+ "kind", "issue",
+ "issue", meta.IssueID,
+ "status", result.Status,
+ "age", age.Round(time.Hour),
+ )
+ return gcActionCleanManagedArtifacts
+ }
+ }
+
return gcActionSkip
}
+func gcMetaFileAge(taskDir string) (time.Duration, bool) {
+ info, err := os.Stat(filepath.Join(taskDir, ".gc_meta.json"))
+ if err != nil {
+ return 0, false
+ }
+ return time.Since(info.ModTime()), true
+}
+
func (d *Daemon) gcDecisionChat(ctx context.Context, taskDir string, meta *execenv.GCMeta) gcAction {
if strings.TrimSpace(meta.ChatSessionID) == "" {
return d.orphanByMTime(taskDir, "empty chat session id")
@@ -577,7 +619,8 @@ func (d *Daemon) cleanTaskDir(taskDir string) {
}
// cleanTaskArtifacts walks taskDir and deletes every directory whose basename
-// matches one of patterns. Returns (removedCount, bytesReclaimed, perPattern).
+// matches one of patterns, plus exact daemon-managed artifact paths. Returns
+// (removedCount, bytesReclaimed, perPattern).
//
// Safety contract:
// - patterns are basename-only; entries with a path separator are dropped.
@@ -589,19 +632,16 @@ func (d *Daemon) cleanTaskDir(taskDir string) {
// - 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) {
+ return d.cleanTaskArtifactsMatching(taskDir, newArtifactMatcher(patterns, execenv.ManagedReclaimableArtifactSubpaths()))
+}
+
+func (d *Daemon) cleanManagedTaskArtifacts(taskDir string) (removed int, bytes int64, perPattern map[string]int) {
+ return d.cleanTaskArtifactsMatching(taskDir, newArtifactMatcher(nil, execenv.ManagedReclaimableArtifactSubpaths()))
+}
+
+func (d *Daemon) cleanTaskArtifactsMatching(taskDir string, matcher artifactMatcher) (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 {
+ if taskDir == "" || (len(matcher.basenames) == 0 && len(matcher.exactPaths) == 0) {
return
}
@@ -634,14 +674,10 @@ func (d *Daemon) cleanTaskArtifacts(taskDir string, patterns []string) (removed
if info.Mode()&os.ModeSymlink != 0 {
return filepath.SkipDir
}
- if _, ok := patternSet[entry.Name()]; !ok {
+ pattern, ok := matcher.matchDirectory(absRoot, path, entry)
+ if !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)
@@ -649,7 +685,7 @@ func (d *Daemon) cleanTaskArtifacts(taskDir string, patterns []string) (removed
}
removed++
bytes += size
- perPattern[entry.Name()]++
+ perPattern[pattern]++
d.logger.Info("gc: artifact removed", "path", path, "bytes", size)
// Don't descend into the now-deleted subtree.
return filepath.SkipDir
diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.go
index d506a52cb8..12939b5415 100644
--- a/server/internal/daemon/gc_test.go
+++ b/server/internal/daemon/gc_test.go
@@ -440,6 +440,72 @@ func TestGCWorkspace_BatchFailureDoesNotFanOutOrClean(t *testing.T) {
}
}
+func TestGCWorkspace_ReclaimsLegacyCodexSandboxWithoutConfiguredPatterns(t *testing.T) {
+ issueID := "77777777-7777-7777-7777-777777777776"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc("/api/daemon/workspaces/ws-legacy-codex/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_progress", "updated_at": time.Now()},
+ }})
+ })
+
+ d := newGCTestDaemon(t, mux)
+ d.cfg.GCArtifactPatterns = nil
+ wsDir := filepath.Join(d.cfg.WorkspacesRoot, "ws-legacy-codex")
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws-legacy-codex", "v0.4.0-task", nil)
+ // Raw v0.4.0 metadata shape: no migration or newly introduced marker is
+ // needed for an already-existing task to become eligible after upgrade.
+ legacyMeta := fmt.Sprintf(
+ `{"kind":"issue","issue_id":%q,"workspace_id":"ws-legacy-codex","completed_at":%q,"local_directory":true}`,
+ issueID,
+ time.Now().Add(-24*time.Hour).UTC().Format(time.RFC3339Nano),
+ )
+ if err := os.WriteFile(filepath.Join(taskDir, ".gc_meta.json"), []byte(legacyMeta), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ // A tiny representative file keeps the regression fast; the reported
+ // Windows executable is about 325 MiB but has identical GC semantics.
+ writeFile(t, filepath.Join(taskDir, "codex-home/.sandbox-bin/codex.exe"), 325)
+ for _, rel := range []string{
+ "codex-home/auth.json",
+ "codex-home/config.toml",
+ "codex-home/sessions/session.jsonl",
+ "output/result.txt",
+ "logs/task.log",
+ "workdir/repo/.sandbox-bin/user-owned",
+ } {
+ writeFile(t, filepath.Join(taskDir, filepath.FromSlash(rel)), 10)
+ }
+
+ stats := &gcStats{byPattern: map[string]int{}}
+ d.gcWorkspace(context.Background(), wsDir, stats)
+
+ if _, err := os.Stat(filepath.Join(taskDir, "codex-home/.sandbox-bin")); !os.IsNotExist(err) {
+ t.Fatalf("managed Codex sandbox should be removed, stat err=%v", err)
+ }
+ for _, rel := range []string{
+ "codex-home/auth.json",
+ "codex-home/config.toml",
+ "codex-home/sessions/session.jsonl",
+ "output/result.txt",
+ "logs/task.log",
+ "workdir/repo/.sandbox-bin/user-owned",
+ ".gc_meta.json",
+ } {
+ if _, err := os.Stat(filepath.Join(taskDir, filepath.FromSlash(rel))); err != nil {
+ t.Errorf("expected %s to be preserved: %v", rel, err)
+ }
+ }
+ managedPattern := managedArtifactPatternPrefix + "codex-home/.sandbox-bin"
+ if stats.artifactDirs != 1 || stats.artifactRemoved != 1 || stats.bytesReclaimed != 325 || stats.skipped != 1 {
+ t.Fatalf("unexpected managed cleanup stats: %+v", stats)
+ }
+ if stats.byPattern[managedPattern] != 1 {
+ t.Fatalf("managed pattern stats = %+v, want %q=1", stats.byPattern, managedPattern)
+ }
+}
+
func TestShouldCleanTaskDir_OpenIssueArtifactCleanup(t *testing.T) {
t.Parallel()
issueID := "88888888-8888-8888-8888-888888888888"
@@ -491,6 +557,44 @@ func TestShouldCleanTaskDir_OpenIssueRecentTaskSkipped(t *testing.T) {
}
}
+func TestShouldCleanTaskDir_LegacyMetaUsesManagedOnlyFallback(t *testing.T) {
+ t.Parallel()
+ issueID := "88888888-8888-8888-8888-88888888888c"
+
+ 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.GCOrphanTTL = 72 * time.Hour
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "legacy-meta", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue, IssueID: issueID, WorkspaceID: "ws1",
+ })
+ old := time.Now().Add(-73 * time.Hour)
+ if err := os.Chtimes(filepath.Join(taskDir, ".gc_meta.json"), old, old); err != nil {
+ t.Fatal(err)
+ }
+
+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionCleanManagedArtifacts {
+ t.Fatalf("expected managed-only fallback for stale legacy meta, got %d", action)
+ }
+
+ recentDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "recent-legacy-meta", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue, IssueID: issueID, WorkspaceID: "ws1",
+ })
+ // Nested activity may leave taskDir's own mtime stale. A recently rewritten
+ // metadata file is the authoritative fallback and must defer cleanup.
+ if err := os.Chtimes(recentDir, old, old); err != nil {
+ t.Fatal(err)
+ }
+ if action := d.shouldCleanTaskDir(context.Background(), recentDir); action != gcActionSkip {
+ t.Fatalf("expected recent legacy meta to remain untouched, got %d", action)
+ }
+}
+
func TestShouldCleanTaskDir_ActiveEnvRootSkipsArtifactCleanup(t *testing.T) {
t.Parallel()
issueID := "88888888-8888-8888-8888-88888888888a"
@@ -618,6 +722,27 @@ func TestShouldCleanTaskDir_ArtifactTTLDisabled(t *testing.T) {
}
}
+func TestShouldCleanTaskDir_ArtifactTTLDisabledSkipsLocalOrphanManagedCleanup(t *testing.T) {
+ t.Parallel()
+ issueID := "88888888-8888-8888-8888-88888888888d"
+
+ mux := http.NewServeMux()
+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {
+ http.NotFound(w, r)
+ })
+
+ d := newGCTestDaemon(t, mux)
+ d.cfg.GCArtifactTTL = 0
+ d.cfg.GCOrphanTTL = 0
+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "disabled-local-orphan", &execenv.GCMeta{
+ Kind: execenv.GCKindIssue, IssueID: issueID, WorkspaceID: "ws1", LocalDirectory: true,
+ })
+
+ if action := d.shouldCleanTaskDir(context.Background(), taskDir); action != gcActionSkip {
+ t.Fatalf("expected artifact TTL zero to disable managed local orphan cleanup, got %d", action)
+ }
+}
+
func TestCleanTaskArtifacts_RemovesOnlyMatchedDirs(t *testing.T) {
t.Parallel()
@@ -741,6 +866,82 @@ func TestCleanTaskArtifacts_DoesNotFollowSymlinks(t *testing.T) {
}
}
+func TestCleanTaskArtifacts_ManagedPathIsExactAndDeduplicated(t *testing.T) {
+ t.Parallel()
+
+ d := newGCTestDaemon(t, http.NewServeMux())
+
+ t.Run("managed only", func(t *testing.T) {
+ taskDir := t.TempDir()
+ writeFile(t, filepath.Join(taskDir, "codex-home/.sandbox-bin/codex.exe"), 300)
+ writeFile(t, filepath.Join(taskDir, "workdir/repo/.sandbox-bin/keep"), 400)
+ writeFile(t, filepath.Join(taskDir, "codex-home/auth.json"), 10)
+
+ removed, bytes, perPattern := d.cleanTaskArtifacts(taskDir, nil)
+ if removed != 1 || bytes != 300 {
+ t.Fatalf("removed=%d bytes=%d, want 1/300", removed, bytes)
+ }
+ if perPattern[managedArtifactPatternPrefix+"codex-home/.sandbox-bin"] != 1 {
+ t.Fatalf("unexpected per-pattern stats: %+v", perPattern)
+ }
+ for _, rel := range []string{"workdir/repo/.sandbox-bin/keep", "codex-home/auth.json"} {
+ if _, err := os.Stat(filepath.Join(taskDir, filepath.FromSlash(rel))); err != nil {
+ t.Errorf("expected %s to be preserved: %v", rel, err)
+ }
+ }
+ })
+
+ t.Run("explicit broad basename", func(t *testing.T) {
+ taskDir := t.TempDir()
+ writeFile(t, filepath.Join(taskDir, "codex-home/.sandbox-bin/codex.exe"), 300)
+ writeFile(t, filepath.Join(taskDir, "workdir/repo/.sandbox-bin/cache"), 400)
+
+ removed, bytes, perPattern := d.cleanTaskArtifacts(taskDir, []string{".sandbox-bin"})
+ if removed != 2 || bytes != 700 {
+ t.Fatalf("removed=%d bytes=%d, want 2/700 without double counting", removed, bytes)
+ }
+ if perPattern[managedArtifactPatternPrefix+"codex-home/.sandbox-bin"] != 1 || perPattern[".sandbox-bin"] != 1 {
+ t.Fatalf("unexpected per-pattern stats: %+v", perPattern)
+ }
+ })
+}
+
+func TestCleanTaskArtifacts_ManagedPathDoesNotFollowSymlinks(t *testing.T) {
+ t.Parallel()
+
+ d := newGCTestDaemon(t, http.NewServeMux())
+
+ for _, tc := range []struct {
+ name string
+ linkPath string
+ }{
+ {name: "leaf", linkPath: "codex-home/.sandbox-bin"},
+ {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)
+ 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, _, _ := d.cleanTaskArtifacts(taskDir, nil)
+ if removed != 0 {
+ t.Fatalf("removed=%d, want 0 for symlinked managed path", removed)
+ }
+ if _, err := os.Stat(keepFile); err != nil {
+ t.Fatalf("symlink target was touched: %v", err)
+ }
+ })
+ }
+}
+
func TestActiveEnvRootRefcount(t *testing.T) {
t.Parallel()
@@ -1527,10 +1728,10 @@ func TestShouldCleanTaskDir_LocalDirectoryNeverClean(t *testing.T) {
}
}
-// TestShouldCleanTaskDir_LocalDirectoryNeverOrphan confirms that even when
-// the parent issue 404s (would normally fall through to mtime-based orphan
-// cleanup) a local_directory task's envRoot is preserved.
-func TestShouldCleanTaskDir_LocalDirectoryNeverOrphan(t *testing.T) {
+// TestShouldCleanTaskDir_LocalDirectoryOrphanUsesManagedOnly confirms that
+// when the parent issue 404s, a local_directory task preserves its envRoot and
+// becomes eligible only for exact daemon-managed artifact cleanup.
+func TestShouldCleanTaskDir_LocalDirectoryOrphanUsesManagedOnly(t *testing.T) {
t.Parallel()
issueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa2"
@@ -1549,8 +1750,8 @@ func TestShouldCleanTaskDir_LocalDirectoryNeverOrphan(t *testing.T) {
})
got := d.shouldCleanTaskDir(context.Background(), taskDir)
- if got == gcActionOrphan || got == gcActionClean {
- t.Fatalf("expected local_directory orphan to be skipped, got %d", got)
+ if got != gcActionCleanManagedArtifacts {
+ t.Fatalf("expected local_directory orphan to use managed-only cleanup, got %d", got)
}
}