fix(daemon): keep a terminal worktree that holds uncommitted work

The cleanup added for no-change runs removed a `completed` task's
worktree whenever it had no PR. agent.run also ends its workflow
`StatusCompleted`, and it works in a real clone whose uncommitted edits
are the deliverable, so the status alone was enough to delete the work:
no commit, no push, no other copy of those edits anywhere.

Cleanup now reads the worktree first and skips a dirty one. A worktree
whose status cannot be read is kept too -- a wrong keep costs disk, a
wrong delete costs the work -- while one that is not on disk has nothing
to keep. The lifecycle fixtures prepare a real clone now, which is the
only shape the daemon ever cleans up, and the cancelled-context test
still cancels only the cleanup call.
This commit is contained in:
sam committed 2026-09-26 04:01:08 +10:00
1 parent f7bfd78d5f
commit 4e9b30d712
3 files changed
+94 -12

No files matched your search

+40 -5
View File
@@ -1329,6 +1329,15 @@ func (d *Daemon) prepareWorkspace(ctx context.Context, task *workflow.Task, tree
return dir, true
}
// cleanupTerminalTaskWorktree removes a task's worktree once its forge side is
// settled, unless the worktree still holds work no commit captured.
//
// The cleanliness guard is what keeps agent.run's deliverable: that step ends
// the workflow StatusCompleted and works in a real clone whose edits it never
// commits, so a status-only rule deletes the work. Nothing else holds it -- not
// the branch, not the store. A worktree whose cleanliness cannot be read is
// kept for the same reason: a wrong keep costs disk, a wrong delete costs the
// work.
func (d *Daemon) cleanupTerminalTaskWorktree(ctx context.Context, task *workflow.Task, trees *worktree.Manager) {
if d.Store == nil || trees == nil || task == nil || !task.HasRepository() {
return
@@ -1348,17 +1357,43 @@ func (d *Daemon) cleanupTerminalTaskWorktree(ctx context.Context, task *workflow
// later run needs: the PR merged, the PR was rejected, an operator refused
// the work, or the run finished without opening a PR at all (a no-change
// build, a triage that needed no code -- StatusCompleted). The PRNumber
// guard keeps the worktree when a PR exists for the reconciler.
// guard keeps the worktree when a PR exists for the reconciler; the
// cleanliness guard keeps it when it holds uncaptured work.
switch latest.Status {
case workflow.StatusMerged, workflow.StatusRejected, workflow.StatusClosedWontDo, workflow.StatusCompleted:
if latest.PRNumber == 0 {
if err := trees.Cleanup(task.Owner, task.Repo, task.IssueNumber); err != nil {
d.Log.Warn("terminal worktree cleanup failed", "task", task.ID, "err", err)
}
if latest.PRNumber != 0 {
return
}
if d.worktreeHoldsUncapturedWork(cleanupCtx, trees, task) {
return
}
if err := trees.Cleanup(task.Owner, task.Repo, task.IssueNumber); err != nil {
d.Log.Warn("terminal worktree cleanup failed", "task", task.ID, "err", err)
}
}
}
// worktreeHoldsUncapturedWork reports whether a terminal task's worktree has
// to survive cleanup because it may hold work no commit captured. A worktree
// that is not on disk at all has nothing to keep, so a task whose clone was
// already removed still cleans up whatever leftovers share its path.
func (d *Daemon) worktreeHoldsUncapturedWork(ctx context.Context, trees *worktree.Manager, task *workflow.Task) bool {
dir := trees.Dir(task.Owner, task.Repo, task.IssueNumber)
if _, err := os.Stat(dir); err != nil {
return false
}
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)
return true
}
if uncommitted {
d.Log.Info("terminal worktree kept: it holds uncommitted work", "task", task.ID, "dir", dir)
return true
}
return false
}
// openTaskLog opens task's log sink for the lifetime of one process() call
// and returns the function to close it. That lifetime covers preparation,
// the full-task container handoff, and teardown. A failure to open is not
+8 -3
View File
@@ -197,6 +197,8 @@ func TestCancelledTaskTransitionsToParked(t *testing.T) {
}
func TestCleanupTerminalTaskWorktreeWithCancelledContext(t *testing.T) {
host := newLocalRemote(t, "acme", "widget")
tests := []struct {
name string
taskStatus string
@@ -243,7 +245,7 @@ func TestCleanupTerminalTaskWorktreeWithCancelledContext(t *testing.T) {
st := pgstore.Open(t)
t.Cleanup(func() { _ = st.Close() })
trees := &worktree.Manager{WorkDir: t.TempDir()}
trees := newTestTrees(t, host)
log := slog.New(slog.DiscardHandler)
d := &Daemon{
Store: st,
@@ -270,8 +272,11 @@ func TestCleanupTerminalTaskWorktreeWithCancelledContext(t *testing.T) {
}
workDir := trees.Dir(task.Owner, task.Repo, task.IssueNumber)
if err := os.MkdirAll(workDir, 0o755); err != nil {
t.Fatalf("create workDir: %v", err)
// A prepared clone: the cancelled context is the thing under test,
// so the worktree itself is readied with a live one.
if _, _, err := trees.Prepare(context.Background(), task.Owner, task.Repo, "main",
task.IssueNumber, task.Title, task.Body, task.Labels); err != nil {
t.Fatalf("prepare worktree: %v", err)
}
d.cleanupTerminalTaskWorktree(ctx, task, trees)
+46 -4
View File
@@ -100,12 +100,28 @@ func newLocalRemote(t *testing.T, owner, repo string) string {
return host
}
// newTestTrees returns a worktree manager whose clones come from the local
// bare remote at host, so a fixture can prepare the clone the daemon would.
func newTestTrees(t *testing.T, host string) *worktree.Manager {
t.Helper()
return &worktree.Manager{
WorkDir: t.TempDir(),
Token: "unused",
BotUser: "archie-bot",
BotEmail: "archie-bot@example.com",
BaseURL: "file://" + host,
}
}
func TestCleanupTerminalTaskWorktreeLifecycle(t *testing.T) {
host := newLocalRemote(t, "acme", "widget")
tests := []struct {
name string
taskIdentity string
setupStatus string
prNumber int
uncommitted bool
wantTreeExists bool
}{
{
@@ -136,6 +152,25 @@ func TestCleanupTerminalTaskWorktreeLifecycle(t *testing.T) {
prNumber: 0,
wantTreeExists: false,
},
{
// agent.run ends a task completed with its deliverable still
// uncommitted in the clone. Deleting that worktree deletes the
// work: nothing else anywhere holds those edits.
name: "completed task keeps a worktree that holds uncommitted work",
taskIdentity: "",
setupStatus: workflow.StatusCompleted,
prNumber: 0,
uncommitted: true,
wantTreeExists: true,
},
{
name: "merged task keeps a worktree that holds uncommitted work",
taskIdentity: "",
setupStatus: workflow.StatusMerged,
prNumber: 0,
uncommitted: true,
wantTreeExists: true,
},
{
name: "parked task preserves worktree for post-mortem",
taskIdentity: "",
@@ -165,8 +200,8 @@ func TestCleanupTerminalTaskWorktreeLifecycle(t *testing.T) {
st := pgstore.Open(t)
t.Cleanup(func() { _ = st.Close() })
rootTrees := &worktree.Manager{WorkDir: t.TempDir()}
winterTrees := &worktree.Manager{WorkDir: t.TempDir()}
rootTrees := newTestTrees(t, host)
winterTrees := newTestTrees(t, host)
log := slog.New(slog.DiscardHandler)
d := &Daemon{
@@ -210,8 +245,15 @@ func TestCleanupTerminalTaskWorktreeLifecycle(t *testing.T) {
targetTrees := d.treesFor(claimed)
workDir := targetTrees.Dir(claimed.Owner, claimed.Repo, claimed.IssueNumber)
if err := os.MkdirAll(workDir, 0o755); err != nil {
t.Fatalf("create workDir: %v", err)
// A prepared clone, the only shape the daemon ever cleans up.
if _, _, err := targetTrees.Prepare(ctx, claimed.Owner, claimed.Repo, "main",
claimed.IssueNumber, claimed.Title, claimed.Body, claimed.Labels); err != nil {
t.Fatalf("prepare worktree: %v", err)
}
if tt.uncommitted {
if err := os.WriteFile(filepath.Join(workDir, "deliverable.md"), []byte("uncommitted work\n"), 0o600); err != nil {
t.Fatalf("write uncommitted work: %v", err)
}
}
d.cleanupTerminalTaskWorktree(ctx, claimed, targetTrees)