Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6870 fix(daemon): require proven task ownership before GC mutation (#7798)
mrlonely2e297451001e
diff --git a/server/internal/daemon/execenv/root_identity.go b/server/internal/daemon/execenv/root_identity.goindex 6e71cf4906..f4ef23be5f 100644--- a/server/internal/daemon/execenv/root_identity.go+++ b/server/internal/daemon/execenv/root_identity.go@@ -167,6 +167,40 @@ func validTaskRootSegment(segment, id string, workspace bool) bool {return strings.HasSuffix(segment, "-"+key)}+// ValidateEnvRootOwnerPath proves that envRoot is the two-level task root+// named by owner under workspacesRoot. GC callers use this before every+// mutation: configuration may point WorkspacesRoot at an arbitrary user-owned+// tree, and a directory's age or missing metadata is not proof that the daemon+// created it.+func ValidateEnvRootOwnerPath(workspacesRoot, envRoot string, owner EnvRootOwner) error {+ if strings.TrimSpace(workspacesRoot) == "" || strings.TrimSpace(envRoot) == "" {+ return errors.New("execenv: workspaces root and env root are required")+ }+ if owner.WorkspaceID == "" || owner.TaskID == "" {+ return errors.New("execenv: env root owner must name both workspace and task")+ }++ relative, err := filepath.Rel(workspacesRoot, envRoot)+ if err != nil {+ return fmt.Errorf("execenv: make env root relative: %w", err)+ }+ relative = filepath.Clean(relative)+ if relative == "." || filepath.IsAbs(relative) {+ return fmt.Errorf("execenv: env root %s is not a task directory below %s", envRoot, workspacesRoot)+ }+ parts := strings.Split(relative, string(filepath.Separator))+ if len(parts) != 2 || parts[0] == "" || parts[1] == "" || parts[0] == ".." || parts[1] == ".." {+ return fmt.Errorf("execenv: env root %s is not exactly two levels below %s", envRoot, workspacesRoot)+ }+ if !validTaskRootSegment(parts[0], owner.WorkspaceID, true) {+ return fmt.Errorf("execenv: workspace directory %q does not match owner %s", parts[0], owner.WorkspaceID)+ }+ if !validTaskRootSegment(parts[1], owner.TaskID, false) {+ return fmt.Errorf("execenv: task directory %q does not match owner %s", parts[1], owner.TaskID)+ }+ return nil+}+// RemoveRootDirRecord removes the stable index after GC has reclaimed a// terminal task root. It verifies that the record still points at envRoot so a// stale cleanup can never remove another task's identity.diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex 5f19a61604..d7c05e88ca 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -3,6 +3,7 @@ package daemonimport ("context""errors"+ "fmt""net/http""os""os/exec"@@ -320,21 +321,41 @@ func (d *Daemon) gcWorkspaceIssues(ctx context.Context, workspaceID string, cand// reconciliation request is in flight.func (d *Daemon) applyGCAction(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)+ stats.skipped+++ return 0+ }release, ok := d.reserveEnvRootForGC(taskDir)if !ok {stats.skipped++return 0}defer release()+ // Re-read provenance after taking the exclusion lock so a concurrent+ // reset cannot change ownership between validation and mutation.+ if _, err := d.gcTaskDirOwner(taskDir); err != nil {+ d.logger.Warn("gc: refusing to mutate task directory after ownership changed", "dir", taskDir, "error", err)+ stats.skipped+++ return 0+ }}switch action {case gcActionClean:- bytes := d.cleanTaskDir(taskDir)+ bytes, removed := d.cleanTaskDir(taskDir)+ if !removed {+ stats.skipped+++ return 0+ }stats.cleaned++stats.bytesReclaimed += bytesreturn 1case gcActionOrphan:- bytes := d.cleanTaskDir(taskDir)+ bytes, removed := d.cleanTaskDir(taskDir)+ if !removed {+ stats.skipped+++ return 0+ }stats.orphaned++stats.bytesReclaimed += bytesreturn 1@@ -393,6 +414,10 @@ func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcActiometa, err := execenv.ReadGCMeta(taskDir)if err != nil {+ if _, ownerErr := d.gcTaskDirOwner(taskDir); ownerErr != nil {+ d.logger.Warn("gc: skipping directory without valid task ownership", "dir", taskDir, "error", ownerErr)+ return gcActionSkip+ }return d.orphanByMTime(taskDir, "no meta")}@@ -814,23 +839,60 @@ func isAgentTaskTerminal(status string) bool {}}-// cleanTaskDir removes a task directory, logs the reclaimed bytes, and returns-// that count for the cycle summary. A failed removal reports zero reclaimed.-func (d *Daemon) cleanTaskDir(taskDir string) int64 {- bytes := dirSize(taskDir)- owner, ownerErr := execenv.ReadEnvRootOwner(taskDir)+// gcTaskDirOwner returns authoritative provenance only when both the marker+// and its position under WorkspacesRoot agree. Missing GC metadata is not+// ownership proof: partially prepared roots have .task_owner, while arbitrary+// user directories do not.+func (d *Daemon) gcTaskDirOwner(taskDir string) (*execenv.EnvRootOwner, error) {+ owner, err := execenv.ReadEnvRootOwner(taskDir)+ if err != nil {+ return nil, fmt.Errorf("read task owner: %w", err)+ }+ if owner == nil {+ return nil, errors.New("task owner is missing")+ }+ validated := *owner+ if validated.WorkspaceID == "" && validated.TaskID != "" {+ // Legacy owner markers contain only the task ID. Completion metadata can+ // supply the missing workspace identity without weakening the hard+ // requirement that a Prepare-time owner marker exists.+ meta, metaErr := execenv.ReadGCMeta(taskDir)+ if metaErr != nil || strings.TrimSpace(meta.WorkspaceID) == "" {+ return nil, errors.New("legacy task owner has no workspace identity or valid GC metadata")+ }+ validated.WorkspaceID = strings.TrimSpace(meta.WorkspaceID)+ }+ if err := execenv.ValidateEnvRootOwnerPath(d.cfg.WorkspacesRoot, taskDir, validated); err != nil {+ return nil, err+ }+ return &validated, nil+}++// cleanTaskDir removes a proven daemon-owned task directory, logs the+// reclaimed bytes, and returns that count for the cycle summary. A failed or+// refused removal reports removed=false.+func (d *Daemon) cleanTaskDir(taskDir string) (bytes int64, removed bool) {+ // Measure first, prove ownership second. dirSize walks the entire tree,+ // which on a large task directory takes long enough for the validated+ // directory to be replaced underneath us — checking before that walk would+ // hand RemoveAll a path last proven ours tens of seconds earlier. This is+ // the defense-in-depth check, so it sits immediately before the removal.+ bytes = dirSize(taskDir)+ owner, ownerErr := d.gcTaskDirOwner(taskDir)+ if ownerErr != nil {+ d.logger.Warn("gc: refusing to remove unowned task directory", "dir", taskDir, "error", ownerErr)+ return 0, false+ }if err := os.RemoveAll(taskDir); err != nil {d.logger.Warn("gc: remove task dir failed", "dir", taskDir, "error", err)- return 0+ return 0, false} else {d.logger.Info("gc: removed", "dir", taskDir, "bytes_reclaimed", bytes)}- if ownerErr == nil && owner != nil {- if err := execenv.RemoveRootDirRecord(d.cfg.WorkspacesRoot, taskDir, *owner); err != nil {- d.logger.Warn("gc: remove stable task root record failed", "dir", taskDir, "error", err)- }+ if err := execenv.RemoveRootDirRecord(d.cfg.WorkspacesRoot, taskDir, *owner); err != nil {+ d.logger.Warn("gc: remove stable task root record failed", "dir", taskDir, "error", err)}- return bytes+ return bytes, true}// linkedDirModes are the mode bits that mark a directory entry as a link todiff --git a/server/internal/daemon/gc_managed_artifact_test.go b/server/internal/daemon/gc_managed_artifact_test.goindex 199e6f9b72..b35cf1021a 100644--- a/server/internal/daemon/gc_managed_artifact_test.go+++ b/server/internal/daemon/gc_managed_artifact_test.go@@ -200,7 +200,7 @@ func TestManagedArtifact_NonTerminalAutopilotAndQuickCreate(t *testing.T) {name stringmeta *execenv.GCMeta}{- {"autopilot_run", &execenv.GCMeta{Kind: execenv.GCKindAutopilotRun, AutopilotRunID: runID, WorkspaceID: "ws"}},+ {"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 {diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.goindex df0ecf5659..4f13f7062d 100644--- a/server/internal/daemon/gc_test.go+++ b/server/internal/daemon/gc_test.go@@ -49,6 +49,20 @@ func createTaskDir(t *testing.T, root, wsID, dirName string, meta *execenv.GCMetif err := os.MkdirAll(taskDir, 0o755); err != nil {t.Fatal(err)}+ // Production task directories end in the task key rather than the full+ // task ID. Keep human-readable fixture names while making the owner marker+ // obey the same path/identity contract enforced by GC.+ taskID := dirName+ if i := strings.LastIndex(dirName, "-"); i >= 0 && i+1 < len(dirName) {+ taskID = dirName[i+1:]+ }+ owner, err := json.Marshal(execenv.EnvRootOwner{WorkspaceID: wsID, TaskID: taskID})+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(taskDir, ".task_owner"), owner, 0o644); err != nil {+ t.Fatal(err)+ }if meta != nil {data, _ := json.Marshal(meta)if err := os.WriteFile(filepath.Join(taskDir, ".gc_meta.json"), data, 0o644); err != nil {@@ -512,7 +526,7 @@ func TestCleanTaskDir_RemovesDirectory(t *testing.T) {t.Fatal("task dir should exist before cleanup")}- if bytes := d.cleanTaskDir(taskDir); bytes < 64 {+ if bytes, removed := d.cleanTaskDir(taskDir); !removed || bytes < 64 {t.Fatalf("reclaimed bytes = %d, want at least payload size", bytes)}@@ -521,6 +535,142 @@ func TestCleanTaskDir_RemovesDirectory(t *testing.T) {}}+func TestRunGC_SharedRootPreservesForeignDirectories(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ d.cfg.GCOrphanTTL = 0+ projectDir := filepath.Join(d.cfg.WorkspacesRoot, "analyze-serenity-event-study-20260827")+ dataDir := filepath.Join(projectDir, "data")+ database := filepath.Join(dataDir, "research.sqlite")+ if err := os.MkdirAll(dataDir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(database, []byte("do not delete"), 0o644); err != nil {+ t.Fatal(err)+ }++ d.runGC(context.Background())++ if got, err := os.ReadFile(database); err != nil || string(got) != "do not delete" {+ t.Fatalf("GC mutated non-Multica data under a shared root: data=%q err=%v", got, err)+ }+}++// The incident regression above only proves the no-meta orphan path returns+// early. applyGCAction is the single gate every mutating action passes+// through, so pin all four: an unowned directory must survive full cleanup,+// orphan removal, pattern artifact cleanup and managed artifact cleanup alike.+func TestApplyGCAction_RefusesEveryMutationWithoutOwner(t *testing.T) {+ t.Parallel()++ for _, tc := range []struct {+ name string+ action gcAction+ }{+ {"clean", gcActionClean},+ {"orphan", gcActionOrphan},+ {"artifacts", gcActionCleanArtifacts},+ {"managed artifacts", gcActionCleanManagedArtifacts},+ } {+ t.Run(tc.name, func(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ taskDir := filepath.Join(d.cfg.WorkspacesRoot, "source-repository", "data")+ // Give both artifact actions something they would delete if the+ // ownership gate were absent, so a passing test means refusal+ // rather than an empty fixture.+ artifactDir := filepath.Join(taskDir, d.cfg.GCArtifactPatterns[0])+ managedDir := filepath.Join(taskDir, execenv.ManagedReclaimableArtifactSubpaths()[0])+ for _, dir := range []string{artifactDir, managedDir} {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(dir, "payload"), []byte("keep"), 0o644); err != nil {+ t.Fatal(err)+ }+ }+ database := filepath.Join(taskDir, "research.sqlite")+ if err := os.WriteFile(database, []byte("do not delete"), 0o644); err != nil {+ t.Fatal(err)+ }++ stats := &gcStats{byPattern: map[string]int{}}+ if removed := d.applyGCAction(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 {+ t.Fatalf("unowned mutation was counted: cleaned=%d orphaned=%d artifactDirs=%d bytes=%d",+ stats.cleaned, stats.orphaned, stats.artifactDirs, stats.bytesReclaimed)+ }+ for _, path := range []string{database, filepath.Join(artifactDir, "payload"), filepath.Join(managedDir, "payload")} {+ if _, err := os.Stat(path); err != nil {+ t.Fatalf("unowned content was mutated: %s: %v", path, err)+ }+ }+ })+ }+}++func TestCleanTaskDir_RefusesOwnerPathMismatch(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ taskDir := filepath.Join(d.cfg.WorkspacesRoot, "source-repository", "data")+ if err := os.MkdirAll(taskDir, 0o755); err != nil {+ t.Fatal(err)+ }+ owner, err := json.Marshal(execenv.EnvRootOwner{WorkspaceID: "workspace-id", TaskID: "task-id"})+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(taskDir, ".task_owner"), owner, 0o644); err != nil {+ t.Fatal(err)+ }+ survivor := filepath.Join(taskDir, "research.sqlite")+ if err := os.WriteFile(survivor, []byte("keep"), 0o644); err != nil {+ t.Fatal(err)+ }++ if bytes, removed := d.cleanTaskDir(taskDir); removed || bytes != 0 {+ t.Fatalf("cleanTaskDir removed owner/path mismatch: removed=%v bytes=%d", removed, bytes)+ }+ if _, err := os.Stat(survivor); err != nil {+ t.Fatalf("owner/path mismatch data was not preserved: %v", err)+ }+}++func TestCleanTaskDir_AcceptsLegacyOwnerWithGCWorkspaceIdentity(t *testing.T) {+ t.Parallel()++ d := newGCTestDaemon(t, http.NewServeMux())+ taskDir := filepath.Join(d.cfg.WorkspacesRoot, "ws1", "task1")+ if err := os.MkdirAll(taskDir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(taskDir, ".task_owner"), []byte("task1"), 0o644); err != nil {+ t.Fatal(err)+ }+ meta, err := json.Marshal(execenv.GCMeta{Kind: execenv.GCKindIssue, WorkspaceID: "ws1"})+ if err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(taskDir, ".gc_meta.json"), meta, 0o644); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(filepath.Join(taskDir, "payload"), []byte("owned"), 0o644); err != nil {+ t.Fatal(err)+ }++ if _, removed := d.cleanTaskDir(taskDir); !removed {+ t.Fatal("legacy task owner with matching GC workspace identity was not removed")+ }+ if _, err := os.Stat(taskDir); !os.IsNotExist(err) {+ t.Fatalf("legacy owned task directory still exists: %v", err)+ }+}+func TestCleanTaskDir_RemovesStableRootRecord(t *testing.T) {t.Parallel()@@ -539,7 +689,7 @@ func TestCleanTaskDir_RemovesStableRootRecord(t *testing.T) {}original := env.RootDird := &Daemon{cfg: Config{WorkspacesRoot: root}, logger: slog.Default()}- if bytes := d.cleanTaskDir(original); bytes <= 0 {+ if bytes, removed := d.cleanTaskDir(original); !removed || bytes <= 0 {t.Fatalf("reclaimed bytes = %d, want owner metadata bytes", bytes)}