diff --git a/internal/app/archied/task_actions.go b/internal/app/archied/task_actions.go index 643f77855..41a6bbb83 100644 --- a/internal/app/archied/task_actions.go +++ b/internal/app/archied/task_actions.go @@ -20,6 +20,7 @@ func (b *boot) taskActions() taskactions.Service { b.cancelTask, b.closeIssue, b.removeTaskLogs, + b.removeTaskWorktree, b.publishEvent, b.log.Warn, ) @@ -46,6 +47,13 @@ func (b *boot) removeTaskLogs(id int64) error { return b.taskLogs.Remove(id) } +func (b *boot) removeTaskWorktree(task *taskactions.Task) error { + if b.d == nil { + return nil + } + return b.d.RemoveWorktree(task.Owner, task.Repo, task.Identity, task.IssueNumber) +} + func (b *boot) publishEvent(e events.Event) { if b.bus != nil { b.bus.Publish(e) diff --git a/internal/daemon/daemon.go b/internal/daemon/daemon.go index 87bc1fd58..9b817ea7c 100644 --- a/internal/daemon/daemon.go +++ b/internal/daemon/daemon.go @@ -1474,16 +1474,16 @@ func (d *Daemon) worktreeHoldsUncapturedWork(ctx context.Context, trees *worktre if errors.Is(err, fs.ErrNotExist) { return false } - d.Log.Warn("terminal worktree kept: it could not be read", "task", task.ID, "dir", dir, "err", err) + d.Log.Warn("terminal worktree kept: it could not be read; archive the task to remove it", "task", task.ID, "dir", dir, "err", err) return true } uncommitted, err := trees.HasUncommittedChanges(ctx, dir) if err != nil { - d.Log.Warn("terminal worktree kept: uncommitted work could not be read", "task", task.ID, "dir", dir, "err", err) + d.Log.Warn("terminal worktree kept: uncommitted work could not be read; archive the task to remove it", "task", task.ID, "dir", dir, "err", err) return true } if uncommitted { - d.Log.Info("terminal worktree kept: it holds uncommitted work", "task", task.ID, "dir", dir) + d.Log.Info("terminal worktree kept: it holds uncommitted work; archive the task to remove it", "task", task.ID, "dir", dir) return true } return false @@ -2280,3 +2280,14 @@ func withTaskTimeLimit(ctx context.Context, limit time.Duration) (context.Contex } return context.WithTimeoutCause(ctx, limit, fmt.Errorf("%w (%s)", errTaskTimeLimit, limit)) } + +// RemoveWorktree deletes a task's clone from the trees of the identity that +// owns it. Archiving calls it: terminal cleanup keeps a worktree that may hold +// uncaptured work, and the operator's archive is the decision to discard it. +func (d *Daemon) RemoveWorktree(owner, repo, identity string, issue int) error { + trees := d.treesFor(&workflow.Task{Owner: owner, Repo: repo, Identity: identity}) + if trees == nil { + return nil + } + return trees.Cleanup(owner, repo, issue) +} diff --git a/internal/daemon/terminal_cleanup_test.go b/internal/daemon/terminal_cleanup_test.go index 30ff8e6f3..d1f78c4bb 100644 --- a/internal/daemon/terminal_cleanup_test.go +++ b/internal/daemon/terminal_cleanup_test.go @@ -3,6 +3,8 @@ package daemon import ( "context" "encoding/json" + "errors" + "io/fs" "log/slog" "net/http" "net/http/httptest" @@ -274,14 +276,14 @@ func TestProcessCleansWorktreeOnTerminalNoChange(t *testing.T) { wantTreeExists bool }{ { - name: "process removes worktree when worker reports merged without PR", - workerStatus: workflow.StatusMerged, + name: "process removes worktree when worker completes without a PR", + workerStatus: workflow.StatusCompleted, taskIdentity: "", wantTreeExists: false, }, { - name: "process removes identity worktree when worker reports merged without PR", - workerStatus: workflow.StatusMerged, + name: "process removes identity worktree when worker completes without a PR", + workerStatus: workflow.StatusCompleted, taskIdentity: "winter", wantTreeExists: false, }, @@ -373,21 +375,9 @@ func TestProcessCleansWorktreeOnTerminalNoChange(t *testing.T) { targetTrees := d.treesFor(task) workDir := targetTrees.Dir(task.Owner, task.Repo, task.IssueNumber) - // The route the worker's completion report takes to its status, - // computed here because t.Fatalf is not callable from the - // subscription goroutine below. - route, err := taskstatetest.Path(workflow.StatusRunning, tt.workerStatus) - if err != nil { - t.Fatalf("no legal route to %s: %v", tt.workerStatus, err) - } - sub, err := mustCoreConn(t, busClient).Subscribe(agentnats.SubjectForTask(task.ID), func(msg *natsio.Msg) { // Transition task in store as archie-agent would do over the gRPC State Store - at := workflow.StatusRunning - for _, to := range route { - _ = s.Transition(ctx, task.ID, at, to, "worker completion") - at = to - } + _ = s.Transition(ctx, task.ID, workflow.StatusRunning, tt.workerStatus, "worker completion") resp, _ := json.Marshal(taskrun.Response{ Status: tt.workerStatus, }) @@ -408,3 +398,27 @@ func TestProcessCleansWorktreeOnTerminalNoChange(t *testing.T) { }) } } + +// TestRemoveWorktreeReapsTheOwningIdentitysClone is the operator's reap path +// for a worktree terminal cleanup kept: archiving removes the clone under the +// trees of the identity that owns the task, and only that clone. +func TestRemoveWorktreeReapsTheOwningIdentitysClone(t *testing.T) { + root := &worktree.Manager{WorkDir: t.TempDir()} + winter := &worktree.Manager{WorkDir: t.TempDir()} + d := &Daemon{Trees: root, Identities: []*IdentityRunner{{Name: "winter", Trees: winter}}} + for _, m := range []*worktree.Manager{root, winter} { + if err := os.MkdirAll(m.Dir("acme", "widget", 7), 0o755); err != nil { + t.Fatal(err) + } + } + + if err := d.RemoveWorktree("acme", "widget", "winter", 7); err != nil { + t.Fatalf("RemoveWorktree: %v", err) + } + if _, err := os.Stat(winter.Dir("acme", "widget", 7)); !errors.Is(err, fs.ErrNotExist) { + t.Errorf("identity worktree still on disk: %v", err) + } + if _, err := os.Stat(root.Dir("acme", "widget", 7)); err != nil { + t.Errorf("root worktree removed: %v", err) + } +} diff --git a/internal/domain/taskactions/service.go b/internal/domain/taskactions/service.go index cb4875d3a..90cc401f3 100644 --- a/internal/domain/taskactions/service.go +++ b/internal/domain/taskactions/service.go @@ -140,8 +140,11 @@ type Service struct { CancelTask func(int64) bool CloseIssue func(context.Context, string, string, int, string) error RemoveLogs func(int64) error - Publish func(events.Event) - Warn func(string, ...any) + // RemoveWorktree discards the task's clone on archive, the reap path for a + // worktree terminal cleanup kept because it may hold uncaptured work. + RemoveWorktree func(*Task) error + Publish func(events.Event) + Warn func(string, ...any) } // Apply scopes chat requests to an identity. A nil scope denotes a caller @@ -315,6 +318,11 @@ func (s Service) applyArchive(ctx context.Context, task *Task, actor Actor, o ou s.warn("task log cleanup failed", "task", task.ID, "err", cleanupErr) } } + if s.RemoveWorktree != nil { + if cleanupErr := s.RemoveWorktree(task); cleanupErr != nil { + s.warn("task worktree cleanup failed", "task", task.ID, "err", cleanupErr) + } + } return o, nil } diff --git a/internal/infrastructure/taskactions/service.go b/internal/infrastructure/taskactions/service.go index e9e387456..8b9e07cf6 100644 --- a/internal/infrastructure/taskactions/service.go +++ b/internal/infrastructure/taskactions/service.go @@ -17,16 +17,18 @@ func NewService( cancel func(int64) bool, closeIssue func(context.Context, string, string, int, string) error, removeLogs func(int64) error, + removeWorktree func(*taskactions.Task) error, publish func(events.Event), warn func(string, ...any), ) taskactions.Service { return taskactions.Service{ - Store: store, - MaxRetries: maxRetries, - CancelTask: cancel, - CloseIssue: closeIssue, - RemoveLogs: removeLogs, - Publish: publish, - Warn: warn, + Store: store, + MaxRetries: maxRetries, + CancelTask: cancel, + CloseIssue: closeIssue, + RemoveLogs: removeLogs, + RemoveWorktree: removeWorktree, + Publish: publish, + Warn: warn, } } diff --git a/internal/webui/api_tasks_actions_test.go b/internal/webui/api_tasks_actions_test.go index 457bed96d..81a13eb12 100644 --- a/internal/webui/api_tasks_actions_test.go +++ b/internal/webui/api_tasks_actions_test.go @@ -80,6 +80,7 @@ func (d *daemonActions) ApplyChatTaskAction( d.cancelTask(), d.closeIssue(), d.removeLogs(), + nil, d.publish(), d.srv.logf, )