Skip to content

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

Go

MUL-6945 & MUL-6944: fix(daemon): preserve Git content during artifact GC (#7893)

[S]640788c05953
diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.go
index 135bfa3b7a..19efc2fc9c 100644
--- a/server/internal/daemon/gc.go
+++ b/server/internal/daemon/gc.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"fmt"
+ "log/slog"
"net/http"
"os"
"os/exec"
@@ -226,7 +227,7 @@ func (d *Daemon) gcWorkspace(ctx context.Context, wsDir string, stats *gcStats)
}
}
action := d.shouldCleanTaskDir(ctx, taskDir)
- cleanedHere += d.applyGCAction(taskDir, action, stats)
+ cleanedHere += d.applyGCAction(ctx, taskDir, action, stats)
}
workspaceIDs := make([]string, 0, len(issueCandidatesByWorkspace))
for workspaceID := range issueCandidatesByWorkspace {
@@ -306,13 +307,13 @@ func (d *Daemon) gcWorkspaceIssues(ctx context.Context, workspaceID string, cand
// 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)
+ cleaned += d.applyGCAction(ctx, 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)
+ cleaned += d.applyGCAction(ctx, candidate.taskDir, action, stats)
}
return cleaned
}
@@ -320,7 +321,7 @@ func (d *Daemon) gcWorkspaceIssues(ctx context.Context, workspaceID string, cand
// applyGCAction performs one decision and updates cycle stats. Each mutation
// atomically reserves the env root because a task can start while the server
// reconciliation request is in flight.
-func (d *Daemon) applyGCAction(taskDir string, action gcAction, stats *gcStats) int {
+func (d *Daemon) applyGCAction(ctx context.Context, taskDir string, action gcAction, stats *gcStats) int {
if action != gcActionSkip {
if _, err := d.gcTaskDirOwner(taskDir); err != nil {
d.logger.Warn("gc: refusing to mutate unowned task directory", "dir", taskDir, "error", err)
@@ -361,7 +362,7 @@ func (d *Daemon) applyGCAction(taskDir string, action gcAction, stats *gcStats)
stats.bytesReclaimed += bytes
return 1
case gcActionCleanArtifacts:
- removed, bytes, perPattern := d.cleanTaskArtifacts(taskDir, d.cfg.GCArtifactPatterns)
+ removed, bytes, perPattern := d.cleanTaskArtifacts(ctx, taskDir, d.cfg.GCArtifactPatterns)
recordArtifactCleanup(stats, removed, bytes, perPattern)
stats.skipped++ // task dir itself preserved
case gcActionCleanManagedArtifacts:
@@ -939,13 +940,20 @@ const linkedDirModes = os.ModeSymlink | os.ModeIrregular
// - patterns are basename-only; entries with a path separator are dropped.
// - .git subtrees are never descended into, so the agent's git history stays
// intact even if a pattern would otherwise match.
+// - a basename-matched directory containing Git-tracked files is retained. Artifact
+// names are conventions, not proof that the repository treats the content
+// as regenerable; deleting tracked output mutates the agent's checkout.
+// - a basename-matched directory that is or contains a Git checkout is retained, even
+// when its containing repository does not track the nested checkout.
+// Exact daemon-managed cache paths keep their explicit regenerable contract,
+// consistent with cleanManagedTaskArtifacts.
// - linked directories are skipped entirely — neither the link nor its
// target is touched, so a malicious or stale link can't redirect the GC
// outside the workdir. See linkedDirModes for what counts as a link.
// - 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) cleanTaskArtifacts(ctx context.Context, taskDir string, patterns []string) (removed int, bytes int64, perPattern map[string]int) {
+ return d.cleanTaskArtifactsMatching(ctx, taskDir, newArtifactMatcher(patterns, execenv.ManagedReclaimableArtifactSubpaths()))
}
// cleanManagedTaskArtifacts removes the exact daemon-managed artifact subpaths
@@ -1041,7 +1049,7 @@ func hasManagedArtifact(taskDir string) bool {
return false
}
-func (d *Daemon) cleanTaskArtifactsMatching(taskDir string, matcher artifactMatcher) (removed int, bytes int64, perPattern map[string]int) {
+func (d *Daemon) cleanTaskArtifactsMatching(ctx context.Context, taskDir string, matcher artifactMatcher) (removed int, bytes int64, perPattern map[string]int) {
perPattern = map[string]int{}
if taskDir == "" || (len(matcher.basenames) == 0 && len(matcher.exactPaths) == 0) {
return
@@ -1053,6 +1061,9 @@ func (d *Daemon) cleanTaskArtifactsMatching(taskDir string, matcher artifactMatc
}
walkErr := filepath.WalkDir(absRoot, func(path string, entry os.DirEntry, err error) error {
+ if ctx.Err() != nil {
+ return context.Cause(ctx)
+ }
if err != nil {
return nil // best-effort — keep walking
}
@@ -1080,7 +1091,33 @@ func (d *Daemon) cleanTaskArtifactsMatching(taskDir string, matcher artifactMatc
if !ok {
return nil
}
- size := dirSize(path)
+ rel, relErr := filepath.Rel(absRoot, path)
+ if relErr != nil {
+ return relErr
+ }
+ if _, managed := matcher.exactPaths[rel]; !managed {
+ preserve, preserveErr := artifactDirectoryNeedsPreservation(ctx, absRoot, path)
+ if preserveErr != nil {
+ // Fail closed. A malformed or temporarily unreadable checkout is not
+ // evidence that a matched directory is safe to remove.
+ d.logger.Warn("gc: artifact retained because git tracking could not be determined", "path", path, "error", preserveErr)
+ return filepath.SkipDir
+ }
+ if preserve {
+ if d.logger.Enabled(ctx, slog.LevelDebug) {
+ retainedBytes, _ := dirSizeContext(ctx, path)
+ d.logger.DebugContext(ctx, "gc: artifact directory retained to preserve git content", "path", path, "pattern", pattern, "retained_bytes", retainedBytes)
+ }
+ return filepath.SkipDir
+ }
+ }
+ size, sizeErr := dirSizeContext(ctx, path)
+ if sizeErr != nil {
+ return sizeErr
+ }
+ if ctx.Err() != nil {
+ return context.Cause(ctx)
+ }
if rmErr := os.RemoveAll(path); rmErr != nil {
d.logger.Warn("gc: artifact remove failed", "path", path, "error", rmErr)
return filepath.SkipDir
@@ -1098,6 +1135,111 @@ func (d *Daemon) cleanTaskArtifactsMatching(taskDir string, matcher artifactMatc
return
}
+// artifactDirectoryNeedsPreservation protects both tracked content and Git
+// checkout boundaries. The index, not git status, decides whether content is
+// tracked: a clean checkout containing a committed .next directory must stay.
+// A nested checkout's files need not appear in the outer repository's index,
+// so its metadata must also be checked before deleting the entire subtree.
+func artifactDirectoryNeedsPreservation(ctx context.Context, taskRoot, artifactPath string) (bool, error) {
+ if ctx.Err() != nil {
+ return false, context.Cause(ctx)
+ }
+ absRoot, err := filepath.Abs(taskRoot)
+ if err != nil {
+ return false, err
+ }
+ absArtifact, err := filepath.Abs(artifactPath)
+ if err != nil {
+ return false, err
+ }
+ if !isPathWithin(absRoot, absArtifact) {
+ return false, fmt.Errorf("artifact path escapes task root")
+ }
+
+ repoRoot, err := containingGitCheckout(absRoot, absArtifact)
+ if err != nil {
+ return false, err
+ }
+ if repoRoot == absArtifact {
+ return true, nil // the removal target is itself an entire checkout
+ }
+ if repoRoot != "" {
+ rel, err := filepath.Rel(repoRoot, absArtifact)
+ if err != nil {
+ return false, fmt.Errorf("resolve artifact path relative to git checkout: %w", err)
+ }
+ if !isPathWithin(repoRoot, absArtifact) {
+ return false, fmt.Errorf("artifact path is not below git checkout")
+ }
+ // -- ends option parsing, not pathspec magic. These are filesystem
+ // paths, so names such as :(top)fixture must be interpreted literally.
+ // NUL output also makes whitespace-only tracked names unambiguous.
+ out, err := runGitGCCommandContext(ctx, repoRoot, "--literal-pathspecs", "ls-files", "-z", "--", filepath.ToSlash(rel))
+ if err != nil {
+ return false, fmt.Errorf("list tracked files below %s: %w", rel, err)
+ }
+ if out != "" {
+ return true, nil
+ }
+ }
+
+ found := false
+ err = filepath.WalkDir(absArtifact, func(path string, entry os.DirEntry, err error) error {
+ if ctx.Err() != nil {
+ return context.Cause(ctx)
+ }
+ if err != nil {
+ return err // an unreadable subtree cannot be proven safe to delete
+ }
+ if entry.Name() == ".git" {
+ found = true // includes linked worktrees and damaged metadata
+ return filepath.SkipAll
+ }
+ if entry.IsDir() {
+ info, err := os.Lstat(path)
+ if err != nil {
+ return err
+ }
+ if info.Mode()&linkedDirModes != 0 {
+ return filepath.SkipDir
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return false, fmt.Errorf("inspect artifact subtree for git checkouts: %w", err)
+ }
+ return found, nil
+}
+
+// containingGitCheckout returns the nearest ancestor carrying Git worktree
+// metadata without walking above taskRoot. Linked worktrees use a .git file;
+// ordinary clones use a .git directory, so either shape is authoritative.
+func containingGitCheckout(taskRoot, start string) (string, error) {
+ current := filepath.Clean(start)
+ for isPathWithin(taskRoot, current) {
+ if _, err := os.Lstat(filepath.Join(current, ".git")); err == nil {
+ return current, nil
+ } else if !os.IsNotExist(err) {
+ return "", fmt.Errorf("inspect git metadata: %w", err)
+ }
+ if current == taskRoot {
+ break
+ }
+ parent := filepath.Dir(current)
+ if parent == current {
+ break
+ }
+ current = parent
+ }
+ return "", nil
+}
+
+func isPathWithin(root, path string) bool {
+ rel, err := filepath.Rel(root, path)
+ return err == nil && rel != ".." && !strings.HasPrefix(rel, ".."+string(filepath.Separator)) && !filepath.IsAbs(rel)
+}
+
// dirSize returns the total size of all regular files under root, in bytes.
// Linked content is not counted: os.RemoveAll would drop the link and leave
// the target, so counting it would overstate what a removal reclaims.
diff --git a/server/internal/daemon/gc_artifact_tracking_test.go b/server/internal/daemon/gc_artifact_tracking_test.go
new file mode 100644
index 0000000000..02e62e90a6
--- /dev/null
+++ b/server/internal/daemon/gc_artifact_tracking_test.go
@@ -0,0 +1,157 @@
+package daemon
+
+import (
+ "bytes"
+ "context"
+ "log/slog"
+ "net/http"
+ "os"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+)
+
+func TestCleanTaskArtifacts_PreservesCheckoutBoundaries(t *testing.T) {
+ t.Parallel()
+
+ for _, layout := range []string{"clone", "linked worktree"} {
+ for _, location := range []struct {
+ name string
+ repo string
+ outer bool
+ }{
+ {name: "matched root", repo: "workdir/target"},
+ {name: "nested checkout", repo: "workdir/node_modules/dependency"},
+ {name: "nested checkout inside another repo", repo: "workdir/outer/node_modules/dependency", outer: true},
+ } {
+ t.Run(layout+"/"+location.name, func(t *testing.T) {
+ d := newGCTestDaemon(t, http.NewServeMux())
+ root := t.TempDir()
+ repo := filepath.Join(root, filepath.FromSlash(location.repo))
+ if location.outer {
+ outer := filepath.Join(root, "workdir", "outer")
+ if err := os.MkdirAll(outer, 0o755); err != nil {
+ t.Fatal(err)
+ }
+ runGitForGC(t, outer, "init")
+ }
+ source := repo
+ if layout == "linked worktree" {
+ source = t.TempDir()
+ }
+ file := filepath.Join(source, "src", "main.go")
+ if err := os.MkdirAll(filepath.Dir(file), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(file, []byte("tracked source"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ runGitForGC(t, source, "init")
+ runGitForGC(t, source, "add", "src/main.go")
+ runGitForGC(t, source, "-c", "commit.gpgsign=false", "commit", "-m", "tracked source")
+ if layout == "linked worktree" {
+ runGitForGC(t, source, "worktree", "add", "--detach", repo)
+ }
+ writeFile(t, filepath.Join(root, "workdir", ".turbo", "cache"), 8)
+
+ removed, bytes, perPattern := d.cleanTaskArtifacts(context.Background(), root, []string{"target", "node_modules", ".turbo"})
+ if removed != 1 || bytes != 8 || perPattern[".turbo"] != 1 {
+ t.Fatalf("removed=%d bytes=%d patterns=%v, want only the unrelated cache removed", removed, bytes, perPattern)
+ }
+ if got, err := os.ReadFile(filepath.Join(repo, "src", "main.go")); err != nil || string(got) != "tracked source" {
+ t.Fatalf("checkout source was removed: data=%q err=%v", got, err)
+ }
+ if _, err := os.Lstat(filepath.Join(repo, ".git")); err != nil {
+ t.Fatalf("checkout metadata was removed: %v", err)
+ }
+ })
+ }
+ }
+}
+
+func TestCleanTaskArtifacts_UsesLiteralTrackedPaths(t *testing.T) {
+ t.Parallel()
+
+ for _, prefix := range []string{":(top)fixture", ":(exclude)fixture", "dist[1]", "star*fixture"} {
+ t.Run(prefix, func(t *testing.T) {
+ if runtime.GOOS == "windows" && strings.ContainsAny(prefix, ":*") {
+ t.Skip("the fixture name is not valid on Windows")
+ }
+ d := newGCTestDaemon(t, http.NewServeMux())
+ root := t.TempDir()
+ repo := filepath.Join(root, "workdir", "repo")
+ rel := filepath.Join(prefix, ".next", "server", "page.js")
+ tracked := filepath.Join(repo, rel)
+ if err := os.MkdirAll(filepath.Dir(tracked), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(tracked, []byte("tracked output"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ runGitForGC(t, repo, "init")
+ runGitForGC(t, repo, "--literal-pathspecs", "add", "--", filepath.ToSlash(rel))
+ writeFile(t, filepath.Join(repo, "node_modules", "cache"), 8)
+
+ removed, bytes, perPattern := d.cleanTaskArtifacts(context.Background(), root, []string{".next", "node_modules"})
+ if removed != 1 || bytes != 8 || perPattern["node_modules"] != 1 {
+ t.Fatalf("removed=%d bytes=%d patterns=%v, want only untracked node_modules removed", removed, bytes, perPattern)
+ }
+ if got, err := os.ReadFile(tracked); err != nil || string(got) != "tracked output" {
+ t.Fatalf("literal tracked path was removed: data=%q err=%v", got, err)
+ }
+ })
+ }
+}
+
+func TestCleanTaskArtifacts_PreservesInvalidGitMetadata(t *testing.T) {
+ t.Parallel()
+
+ d := newGCTestDaemon(t, http.NewServeMux())
+ root := t.TempDir()
+ repo := filepath.Join(root, "workdir", "repo")
+ writeFile(t, filepath.Join(repo, ".next", "cache"), 8)
+ if err := os.WriteFile(filepath.Join(repo, ".git"), []byte("gitdir: missing"), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ if removed, _, _ := d.cleanTaskArtifacts(context.Background(), root, []string{".next"}); removed != 0 {
+ t.Fatalf("removed=%d, want fail-closed retention", removed)
+ }
+}
+
+func TestCleanTaskArtifacts_CancellationPreservesArtifacts(t *testing.T) {
+ t.Parallel()
+
+ d := newGCTestDaemon(t, http.NewServeMux())
+ root := t.TempDir()
+ artifact := filepath.Join(root, "workdir", "node_modules", "cache")
+ writeFile(t, artifact, 8)
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if removed, _, _ := d.cleanTaskArtifacts(ctx, root, []string{"node_modules"}); removed != 0 {
+ t.Fatalf("removed=%d after cancellation, want 0", removed)
+ }
+ if _, err := os.Stat(artifact); err != nil {
+ t.Fatalf("cancelled cleanup removed artifact: %v", err)
+ }
+}
+
+func TestCleanTaskArtifacts_DebugLogsRetainedBytes(t *testing.T) {
+ t.Parallel()
+
+ d := newGCTestDaemon(t, http.NewServeMux())
+ var logs bytes.Buffer
+ d.logger = slog.New(slog.NewJSONHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug}))
+ root := t.TempDir()
+ repo := filepath.Join(root, "workdir", "repo")
+ writeFile(t, filepath.Join(repo, ".next", "tracked"), 8)
+ writeFile(t, filepath.Join(repo, ".next", "cache"), 16)
+ runGitForGC(t, repo, "init")
+ runGitForGC(t, repo, "add", ".next/tracked")
+ if removed, _, _ := d.cleanTaskArtifacts(context.Background(), root, []string{".next"}); removed != 0 {
+ t.Fatalf("removed=%d, want tracked directory retained", removed)
+ }
+ if log := logs.String(); !strings.Contains(log, `"level":"DEBUG"`) || !strings.Contains(log, `"retained_bytes":24`) {
+ t.Fatalf("missing debug retention byte count: %s", log)
+ }
+}
diff --git a/server/internal/daemon/gc_junction_windows_test.go b/server/internal/daemon/gc_junction_windows_test.go
index 6b70d4ec15..866f1f0e90 100644
--- a/server/internal/daemon/gc_junction_windows_test.go
+++ b/server/internal/daemon/gc_junction_windows_test.go
@@ -3,6 +3,7 @@
package daemon
import (
+ "context"
"net/http"
"os"
"os/exec"
@@ -58,7 +59,7 @@ func TestCleanTaskArtifacts_DoesNotFollowDirectoryJunction(t *testing.T) {
// user's ~/.codex/skills/<name>.
createJunction(t, userSkill, filepath.Join(taskDir, "codex-home", "skills", "alpha"))
- removed, _, _ := d.cleanTaskArtifacts(taskDir, []string{"node_modules"})
+ removed, _, _ := d.cleanTaskArtifacts(context.Background(), taskDir, []string{"node_modules"})
if removed != 0 {
t.Errorf("removed %d artifacts through a junction, want 0", removed)
}
diff --git a/server/internal/daemon/gc_managed_artifact_test.go b/server/internal/daemon/gc_managed_artifact_test.go
index b35cf1021a..a878063cd2 100644
--- a/server/internal/daemon/gc_managed_artifact_test.go
+++ b/server/internal/daemon/gc_managed_artifact_test.go
@@ -80,7 +80,7 @@ func TestManagedArtifact_IdleActiveChatReclaimsSandboxBin(t *testing.T) {
if action != gcActionCleanManagedArtifacts {
t.Fatalf("want gcActionCleanManagedArtifacts, got %d", action)
}
- d.applyGCAction(taskDir, action, stats)
+ d.applyGCAction(context.Background(), taskDir, action, stats)
assertGone(t, taskDir, sandboxBinRel)
assertKept(t, taskDir,
@@ -212,7 +212,7 @@ func TestManagedArtifact_NonTerminalAutopilotAndQuickCreate(t *testing.T) {
if action != gcActionCleanManagedArtifacts {
t.Fatalf("%s: want gcActionCleanManagedArtifacts, got %d", tc.name, action)
}
- d.applyGCAction(taskDir, action, &gcStats{byPattern: map[string]int{}})
+ d.applyGCAction(context.Background(), taskDir, action, &gcStats{byPattern: map[string]int{}})
assertGone(t, taskDir, sandboxBinRel)
assertKept(t, taskDir, ".gc_meta.json")
}
@@ -261,7 +261,7 @@ func TestManagedArtifact_LocalDirectoryChatReclaimsSandboxBin(t *testing.T) {
if action != gcActionCleanManagedArtifacts {
t.Fatalf("want gcActionCleanManagedArtifacts, got %d", action)
}
- d.applyGCAction(taskDir, action, &gcStats{byPattern: map[string]int{}})
+ d.applyGCAction(context.Background(), taskDir, action, &gcStats{byPattern: map[string]int{}})
assertGone(t, taskDir, sandboxBinRel)
assertKept(t, taskDir, "logs/run.log", ".gc_meta.json")
}
@@ -287,7 +287,7 @@ func TestManagedArtifact_SecondCycleIsANoOp(t *testing.T) {
if first != gcActionCleanManagedArtifacts {
t.Fatalf("first cycle: want gcActionCleanManagedArtifacts, got %d", first)
}
- d.applyGCAction(taskDir, first, &gcStats{byPattern: map[string]int{}})
+ d.applyGCAction(context.Background(), taskDir, first, &gcStats{byPattern: map[string]int{}})
assertGone(t, taskDir, sandboxBinRel)
for cycle := 2; cycle <= 3; cycle++ {
@@ -460,7 +460,7 @@ func TestManagedArtifact_DirectRemovalMatchesTreeWalk(t *testing.T) {
setup(t, walked)
setup(t, direct)
- wRemoved, wBytes, wPattern := d.cleanTaskArtifactsMatching(walked, walkMatcher)
+ wRemoved, wBytes, wPattern := d.cleanTaskArtifactsMatching(context.Background(), walked, walkMatcher)
dRemoved, dBytes, dPattern := d.cleanManagedTaskArtifacts(direct)
if wRemoved != dRemoved || wBytes != dBytes || fmt.Sprint(wPattern) != fmt.Sprint(dPattern) {
diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.go
index 8e90b38c0a..ab2b1cec39 100644
--- a/server/internal/daemon/gc_test.go
+++ b/server/internal/daemon/gc_test.go
@@ -597,7 +597,7 @@ func TestApplyGCAction_RefusesEveryMutationWithoutOwner(t *testing.T) {
}
stats := &gcStats{byPattern: map[string]int{}}
- if removed := d.applyGCAction(taskDir, tc.action, stats); removed != 0 {
+ if removed := d.applyGCAction(context.Background(), taskDir, tc.action, stats); removed != 0 {
t.Fatalf("applyGCAction reported %d removals on an unowned directory", removed)
}
if stats.cleaned != 0 || stats.orphaned != 0 || stats.artifactDirs != 0 || stats.bytesReclaimed != 0 {
@@ -1489,8 +1489,10 @@ func TestCleanTaskArtifacts_RemovesOnlyMatchedDirs(t *testing.T) {
mustMkdir("workdir/repo/src")
mustWrite("workdir/repo/src/index.ts", "console.log('hi')")
- mustMkdir("workdir/repo/.git/objects")
- mustWrite("workdir/repo/.git/objects/pack", "binary")
+ if out, err := exec.Command("git", "-C", filepath.Join(taskDir, "workdir/repo"), "init").CombinedOutput(); err != nil {
+ t.Fatalf("git init: %v: %s", err, out)
+ }
+ mustWrite("workdir/repo/.git/objects/pack/test.pack", "binary")
mustMkdir("workdir/repo/node_modules/lodash")
mustWrite("workdir/repo/node_modules/lodash/index.js", "module.exports = {}")
mustMkdir("workdir/repo/.next/cache")
@@ -1503,7 +1505,7 @@ func TestCleanTaskArtifacts_RemovesOnlyMatchedDirs(t *testing.T) {
mustMkdir("output")
mustWrite("output/result.txt", "done")
- removed, bytes, perPattern := d.cleanTaskArtifacts(taskDir, []string{"node_modules", ".next", ".turbo"})
+ removed, bytes, perPattern := d.cleanTaskArtifacts(context.Background(), taskDir, []string{"node_modules", ".next", ".turbo"})
if removed != 3 {
t.Fatalf("expected 3 artifact dirs removed, got %d", removed)
@@ -1518,7 +1520,7 @@ func TestCleanTaskArtifacts_RemovesOnlyMatchedDirs(t *testing.T) {
// Verify protected paths are intact.
for _, rel := range []string{
"workdir/repo/src/index.ts",
- "workdir/repo/.git/objects/pack",
+ "workdir/repo/.git/objects/pack/test.pack",
"workdir/repo/dist/main.js",
"output/result.txt",
".gc_meta.json",
@@ -1540,6 +1542,45 @@ func TestCleanTaskArtifacts_RemovesOnlyMatchedDirs(t *testing.T) {
}
}
+func TestCleanTaskArtifacts_PreservesTrackedArtifactDirectory(t *testing.T) {
+ t.Parallel()
+
+ d := newGCTestDaemon(t, http.NewServeMux())
+ taskDir := t.TempDir()
+ repoDir := filepath.Join(taskDir, "workdir", "repo")
+ tracked := filepath.Join(repoDir, ".next", "server", "page.js")
+ untracked := filepath.Join(repoDir, "node_modules", "dependency", "index.js")
+ for path, content := range map[string]string{
+ tracked: "committed build output",
+ untracked: "regenerable dependency",
+ } {
+ if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(content), 0o644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if out, err := exec.Command("git", "-C", repoDir, "init").CombinedOutput(); err != nil {
+ t.Fatalf("git init: %v: %s", err, out)
+ }
+ if out, err := exec.Command("git", "-C", repoDir, "add", ".next/server/page.js").CombinedOutput(); err != nil {
+ t.Fatalf("git add tracked artifact: %v: %s", err, out)
+ }
+
+ removed, _, perPattern := d.cleanTaskArtifacts(context.Background(), taskDir, []string{"node_modules", ".next"})
+
+ if removed != 1 || perPattern["node_modules"] != 1 || perPattern[".next"] != 0 {
+ t.Fatalf("removed=%d perPattern=%v, want only untracked node_modules removed", removed, perPattern)
+ }
+ if got, err := os.ReadFile(tracked); err != nil || string(got) != "committed build output" {
+ t.Fatalf("tracked artifact was mutated: data=%q err=%v", got, err)
+ }
+ if _, err := os.Stat(filepath.Dir(filepath.Dir(untracked))); !os.IsNotExist(err) {
+ t.Fatalf("untracked artifact directory survived: %v", err)
+ }
+}
+
func TestCleanTaskArtifacts_RejectsPatternsWithSeparators(t *testing.T) {
t.Parallel()
@@ -1549,7 +1590,7 @@ func TestCleanTaskArtifacts_RejectsPatternsWithSeparators(t *testing.T) {
t.Fatal(err)
}
- removed, _, _ := d.cleanTaskArtifacts(taskDir, []string{"workdir/node_modules", "../etc"})
+ removed, _, _ := d.cleanTaskArtifacts(context.Background(), taskDir, []string{"workdir/node_modules", "../etc"})
if removed != 0 {
t.Fatalf("expected 0 removals from separator-bearing patterns, got %d", removed)
}
@@ -1577,7 +1618,7 @@ func TestCleanTaskArtifacts_DoesNotFollowSymlinks(t *testing.T) {
t.Skipf("symlink not supported: %v", err)
}
- removed, _, _ := d.cleanTaskArtifacts(taskDir, []string{"node_modules"})
+ removed, _, _ := d.cleanTaskArtifacts(context.Background(), taskDir, []string{"node_modules"})
if removed != 0 {
t.Fatalf("expected 0 removals (symlinked node_modules), got %d", removed)
}
@@ -1597,7 +1638,7 @@ func TestCleanTaskArtifacts_ManagedPathIsExactAndDeduplicated(t *testing.T) {
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)
+ removed, bytes, perPattern := d.cleanTaskArtifacts(context.Background(), taskDir, nil)
if removed != 1 || bytes != 300 {
t.Fatalf("removed=%d bytes=%d, want 1/300", removed, bytes)
}
@@ -1616,7 +1657,7 @@ func TestCleanTaskArtifacts_ManagedPathIsExactAndDeduplicated(t *testing.T) {
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"})
+ removed, bytes, perPattern := d.cleanTaskArtifacts(context.Background(), taskDir, []string{".sandbox-bin"})
if removed != 2 || bytes != 700 {
t.Fatalf("removed=%d bytes=%d, want 2/700 without double counting", removed, bytes)
}
@@ -1651,7 +1692,7 @@ func TestCleanTaskArtifacts_ManagedPathDoesNotFollowSymlinks(t *testing.T) {
t.Skipf("symlink not supported: %v", err)
}
- removed, _, _ := d.cleanTaskArtifacts(taskDir, nil)
+ removed, _, _ := d.cleanTaskArtifacts(context.Background(), taskDir, nil)
if removed != 0 {
t.Fatalf("removed=%d, want 0 for symlinked managed path", removed)
}
@@ -2523,7 +2564,7 @@ func TestShouldCleanTaskDir_ChatActiveResistsOldMtime(t *testing.T) {
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{}})
+ d.applyGCAction(context.Background(), 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 {