Skip to content

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

Go

MUL-7034: fix(server): keep the parent workdir when an automatic retry must start fresh (#8291)

Bohan Jiang676245af632d
diff --git a/server/cmd/server/rerun_session_test.go b/server/cmd/server/rerun_session_test.go
index 7af6642910..4f0ac34186 100644
--- a/server/cmd/server/rerun_session_test.go
+++ b/server/cmd/server/rerun_session_test.go
@@ -584,8 +584,10 @@ func TestCreateRetryTaskFreshensCodexSemanticInactivity(t *testing.T) {
if child.SessionID.Valid {
t.Fatalf("expected retry child to drop poisoned session_id, got %q", child.SessionID.String)
}
- if child.WorkDir.Valid {
- t.Fatalf("expected retry child to drop poisoned work_dir, got %q", child.WorkDir.String)
+ // A poisoned conversation does not poison the workdir (MUL-7034): the
+ // child keeps the parent's work_dir for the claim to hand back.
+ if !child.WorkDir.Valid || child.WorkDir.String != "/tmp/codex-stuck" {
+ t.Fatalf("expected retry child to inherit parent work_dir /tmp/codex-stuck, got %+v", child.WorkDir)
}
if !child.ForceFreshSession {
t.Fatal("expected retry child to force a fresh session")
diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.go
index 9d2093a610..50252d28b9 100644
--- a/server/internal/daemon/client.go
+++ b/server/internal/daemon/client.go
@@ -210,6 +210,7 @@ func daemonCommonCapabilities() []string {
protocol.DaemonCapabilitySourceContextQuickCreateV1,
protocol.DaemonCapabilityRPCV1,
protocol.DaemonCapabilityPlatformSkillV1,
+ protocol.DaemonCapabilityReusedWorkdirNoticeV1,
}
}
diff --git a/server/internal/daemon/client_test.go b/server/internal/daemon/client_test.go
index a78607e10f..68b810d2aa 100644
--- a/server/internal/daemon/client_test.go
+++ b/server/internal/daemon/client_test.go
@@ -51,6 +51,10 @@ func TestClient_IdentityHeaders_PostJSON(t *testing.T) {
// and a stale signpost, neither of which any other test would
// notice.
protocol.DaemonCapabilityPlatformSkillV1,
+ // Gates whether an automatic retry is handed its parent's workdir
+ // (MUL-7034). Dropping it silently sends those retries back to a
+ // fresh directory, losing the continuity nothing else would flag.
+ protocol.DaemonCapabilityReusedWorkdirNoticeV1,
} {
if !capabilities[want] {
t.Errorf("X-Client-Capabilities missing %q: %v", want, capabilities)
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index c0cc418fdb..eb4c230e48 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -8027,6 +8027,13 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
if env.LocalWorktree != nil && len(env.LocalWorktree.ReplayConflicts) > 0 {
promptOptions = append(promptOptions, WithWorktreeReplayConflicts(env.LocalWorktree.ReplayConflicts))
}
+ // A fresh session in a reused workdir starts among files it has no memory
+ // of producing (MUL-7034). envReused is what this daemon actually did, not
+ // what the server offered: a GC'd directory falls back to Prepare and is
+ // not warned about.
+ if envReused && task.PriorSessionID == "" {
+ promptOptions = append(promptOptions, WithReusedWorkdir())
+ }
prompt := BuildPrompt(task, provider, promptOptions...)
// Pass task-scoped auth credentials and context so the spawned agent CLI
@@ -8398,6 +8405,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i
execOpts.SystemPrompt = runtimeBrief
}
}
+ // The first attempt was resuming, so it was not warned about the reused
+ // workdir; this one is in the same directory without that memory.
+ if envReused {
+ promptOptions = append(promptOptions, WithReusedWorkdir())
+ }
freshPrompt := BuildPrompt(task, provider, promptOptions...)
retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, freshPrompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)
diff --git a/server/internal/daemon/leader_workdir_reuse_test.go b/server/internal/daemon/leader_workdir_reuse_test.go
index 26ee54021c..8ed6a8817c 100644
--- a/server/internal/daemon/leader_workdir_reuse_test.go
+++ b/server/internal/daemon/leader_workdir_reuse_test.go
@@ -136,6 +136,177 @@ func TestShouldReusePriorWorkdirChatAcceptsMatchingConversation(t *testing.T) {
}
}
+// TestShouldReusePriorWorkdirDeclinesRemovedDirectory covers an automatic retry
+// whose parent's workdir was GC'd between the failure and the claim (MUL-7034):
+// the server still offers the recorded path, and the daemon must decline it so
+// the run prepares a fresh environment instead.
+func TestShouldReusePriorWorkdirDeclinesRemovedDirectory(t *testing.T) {
+ t.Parallel()
+
+ root := t.TempDir()
+ workDir := filepath.Join(root, "ws-leader", "12345678", "workdir")
+ writeLeaderTaskMarker(t, workDir, "agent-leader", "issue-leader")
+ writeLeaderManagedEnvProvenance(t, workDir, "ws-leader", "issue-leader", "agent-leader")
+
+ task := leaderReuseTestTask("task-retry")
+ task.IsLeaderTask = false
+ task.PriorWorkDir = workDir
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); !ok {
+ t.Fatalf("setup: fully-provenanced workdir %q was not reusable", workDir)
+ }
+
+ if err := os.RemoveAll(filepath.Dir(workDir)); err != nil {
+ t.Fatalf("remove env root: %v", err)
+ }
+ if _, ok := shouldReusePriorWorkdir(task, nil, root); ok {
+ t.Fatal("reused a prior workdir that no longer exists")
+ }
+}
+
+// TestRunTaskWarnsFreshSessionInReusedWorkdir drives real runTask calls to pin
+// where the reused-workdir warning lands (MUL-7034). A run that reuses an
+// earlier run's directory without resuming its session is warned in the prompt
+// the backend receives, and the warning stays out of the brief written into the
+// workdir, which must be byte-stable across runs (MUL-5377). A run that resumes
+// the session remembers the work and is not warned; a run whose offered
+// directory is gone gets a fresh one and nothing to be warned about.
+func TestRunTaskWarnsFreshSessionInReusedWorkdir(t *testing.T) {
+ t.Parallel()
+
+ d, _, promptsFile, cleanup := newPromptCapturingReuseTestDaemon(t)
+ defer cleanup()
+
+ const warning = "Files from an earlier run"
+ run := func(task Task) (TaskResult, string) {
+ t.Helper()
+ task.IsLeaderTask = false
+ result, err := d.runTask(context.Background(), task, "claude", 0, d.logger)
+ if err != nil {
+ t.Fatalf("runTask %s: %v", task.ID, err)
+ }
+ prompts, err := os.ReadFile(promptsFile)
+ if err != nil {
+ t.Fatalf("read prompts: %v", err)
+ }
+ lines := strings.Split(strings.TrimRight(string(prompts), "\n"), "\n")
+ return result, lines[len(lines)-1]
+ }
+
+ firstResult, firstPrompt := run(leaderReuseTestTask("task-first"))
+ if strings.Contains(firstPrompt, warning) {
+ t.Fatalf("a fresh environment was warned about an earlier run: %s", firstPrompt)
+ }
+
+ // What the server hands an automatic retry after a conversation-poisoning
+ // failure: the parent's workdir, no session.
+ retry := leaderReuseTestTask("task-retry")
+ retry.PriorWorkDir = firstResult.WorkDir
+ retry.PriorSessionResumeUnavailable = true
+ retryResult, retryPrompt := run(retry)
+ if !sameDir(t, retryResult.WorkDir, firstResult.WorkDir) {
+ t.Fatalf("retry WorkDir = %q, want the reused %q", retryResult.WorkDir, firstResult.WorkDir)
+ }
+ if !strings.Contains(retryPrompt, warning) {
+ t.Fatalf("fresh session in a reused workdir was not warned; prompt: %s", retryPrompt)
+ }
+ brief, err := os.ReadFile(filepath.Join(retryResult.WorkDir, "CLAUDE.md"))
+ if err != nil {
+ t.Fatalf("read brief: %v", err)
+ }
+ if strings.Contains(string(brief), warning) {
+ t.Fatal("reused-workdir warning leaked into the byte-stable brief")
+ }
+
+ followUp := leaderReuseTestTask("task-follow-up")
+ followUp.PriorWorkDir = retryResult.WorkDir
+ followUp.PriorSessionID = retryResult.SessionID
+ followUpResult, followUpPrompt := run(followUp)
+ if !sameDir(t, followUpResult.WorkDir, retryResult.WorkDir) {
+ t.Fatalf("follow-up WorkDir = %q, want the reused %q", followUpResult.WorkDir, retryResult.WorkDir)
+ }
+ if strings.Contains(followUpPrompt, warning) {
+ t.Fatalf("a resumed session was warned about work it remembers: %s", followUpPrompt)
+ }
+
+ if err := os.RemoveAll(firstResult.EnvRoot); err != nil {
+ t.Fatalf("remove env root: %v", err)
+ }
+ afterGC := leaderReuseTestTask("task-after-gc")
+ afterGC.PriorWorkDir = firstResult.WorkDir
+ afterGCResult, afterGCPrompt := run(afterGC)
+ if afterGCResult.WorkDir == firstResult.WorkDir {
+ t.Fatalf("run reused a workdir that no longer exists: %q", afterGCResult.WorkDir)
+ }
+ if strings.Contains(afterGCPrompt, warning) {
+ t.Fatalf("a fresh environment was warned about an earlier run: %s", afterGCPrompt)
+ }
+}
+
+// TestRunTaskWarnsFreshRetryAfterRejectedResume covers the in-turn path to the
+// same state: a run that reused a workdir to resume its session, had the resume
+// rejected, and retried with a fresh session in that directory. The resuming
+// attempt remembers the work and is not warned; the fresh retry is (MUL-7034).
+func TestRunTaskWarnsFreshRetryAfterRejectedResume(t *testing.T) {
+ t.Parallel()
+
+ d, _, promptsFile, cleanup := newPromptCapturingReuseTestDaemon(t)
+ defer cleanup()
+
+ first := leaderReuseTestTask("task-first")
+ first.IsLeaderTask = false
+ firstResult, err := d.runTask(context.Background(), first, "claude", 0, d.logger)
+ if err != nil {
+ t.Fatalf("first runTask: %v", err)
+ }
+
+ // From here on the provider refuses every --resume the way Claude does
+ // when the transcript is gone, and accepts a fresh session.
+ rejectingScript := `#!/bin/sh
+IFS= read -r prompt
+printf '%s\n' "$prompt" >> "` + promptsFile + `"
+for arg in "$@"; do
+ if [ "$arg" = "--resume" ]; then
+ echo "No conversation found with session ID: session-leader-reuse" >&2
+ printf '%s\n' '{"type":"result","subtype":"error_during_execution","is_error":true,"result":"No conversation found"}'
+ exit 1
+ fi
+done
+printf '%s\n' '{"type":"system","session_id":"session-fresh"}'
+printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"session-fresh","result":"done"}'
+`
+ if err := os.WriteFile(d.cfg.Agents["claude"].Path, []byte(rejectingScript), 0o755); err != nil {
+ t.Fatalf("rewrite fake agent: %v", err)
+ }
+
+ second := leaderReuseTestTask("task-second")
+ second.IsLeaderTask = false
+ second.PriorWorkDir = firstResult.WorkDir
+ second.PriorSessionID = firstResult.SessionID
+ secondResult, err := d.runTask(context.Background(), second, "claude", 0, d.logger)
+ if err != nil {
+ t.Fatalf("second runTask: %v", err)
+ }
+ if secondResult.SessionID != "session-fresh" {
+ t.Fatalf("second run did not end on the fresh session: %+v", secondResult)
+ }
+
+ prompts, err := os.ReadFile(promptsFile)
+ if err != nil {
+ t.Fatalf("read prompts: %v", err)
+ }
+ lines := strings.Split(strings.TrimRight(string(prompts), "\n"), "\n")
+ if len(lines) != 3 {
+ t.Fatalf("got %d invocations, want first run + rejected resume + fresh retry:\n%s", len(lines), prompts)
+ }
+ const warning = "Files from an earlier run"
+ if strings.Contains(lines[1], warning) {
+ t.Fatalf("the resuming attempt was warned about work it remembers: %s", lines[1])
+ }
+ if !strings.Contains(lines[2], warning) {
+ t.Fatalf("fresh retry in the reused workdir was not warned: %s", lines[2])
+ }
+}
+
// TestShouldReusePriorWorkdirSquadLeaderAcceptsManagedProvenance is the unit
// positive: managed shape + matching Prepare-time provenance + matching marker.
func TestShouldReusePriorWorkdirSquadLeaderAcceptsManagedProvenance(t *testing.T) {
@@ -286,14 +457,25 @@ func TestShouldReusePriorWorkdirSquadLeaderRejectsSymlinkEscape(t *testing.T) {
func newLeaderReuseTestDaemon(t *testing.T) (*Daemon, string, func()) {
t.Helper()
+ d, argsFile, _, cleanup := newPromptCapturingReuseTestDaemon(t)
+ return d, argsFile, cleanup
+}
+
+// newPromptCapturingReuseTestDaemon is newLeaderReuseTestDaemon that also
+// returns a file holding each invocation's prompt, one stream-json frame per
+// line in invocation order.
+func newPromptCapturingReuseTestDaemon(t *testing.T) (*Daemon, string, string, func()) {
+ t.Helper()
testDir := t.TempDir()
fakeBin := filepath.Join(testDir, "claude")
argsFile := filepath.Join(testDir, "claude-args.txt")
+ promptsFile := filepath.Join(testDir, "claude-prompts.txt")
script := `#!/bin/sh
printf '%s\n' "$@" >> "` + argsFile + `"
printf '%s\n' '--invocation-end--' >> "` + argsFile + `"
-IFS= read -r _
+IFS= read -r prompt
+printf '%s\n' "$prompt" >> "` + promptsFile + `"
printf '%s\n' '{"type":"system","session_id":"session-leader-reuse"}'
printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id":"session-leader-reuse","result":"done"}'
`
@@ -321,7 +503,7 @@ printf '%s\n' '{"type":"result","subtype":"success","is_error":false,"session_id
},
},
}
- return d, argsFile, srv.Close
+ return d, argsFile, promptsFile, srv.Close
}
func writeLeaderTaskMarker(t *testing.T, workDir, agentID, issueID string) {
diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.go
index 0dcc64fe74..9d61f8d2c9 100644
--- a/server/internal/daemon/prompt.go
+++ b/server/internal/daemon/prompt.go
@@ -67,6 +67,7 @@ func perTurnContextBlocks(task Task, opts promptOpts) string {
if task.PriorSessionResumeUnavailable {
b.WriteString(sessionContinuityNoticeFor(task))
}
+ b.WriteString(buildReusedWorkdirBlock(opts.reusedWorkdir))
b.WriteString(execenv.BuildTaskInitiatorBlock(task.InitiatorType, task.InitiatorName, task.InitiatorEmail))
b.WriteString(execenv.BuildConnectedAppsBlock(task.ConnectedApps))
return b.String()
@@ -78,6 +79,7 @@ func perTurnContextBlocks(task Task, opts promptOpts) string {
type promptOpts struct {
sharedLocalDirectory bool
worktreeReplayConflicts []string
+ reusedWorkdir bool
}
// PromptOption tunes per-turn prompt copy with run-scoped context.
@@ -103,6 +105,14 @@ func WithWorktreeReplayConflicts(files []string) PromptOption {
return func(o *promptOpts) { o.worktreeReplayConflicts = files }
}
+// WithReusedWorkdir marks a turn that runs a fresh provider session inside a
+// workdir an earlier run left behind: an automatic or manual retry after a
+// failure that poisoned the conversation, or a resume the daemon had to drop.
+// The files are there; the memory of producing them is not (MUL-7034).
+func WithReusedWorkdir() PromptOption {
+ return func(o *promptOpts) { o.reusedWorkdir = true }
+}
+
// buildSharedLocalDirectoryBlock warns an unlocked turn that its working
// directory is shared live. Deliberately guidance and not a prohibition: the
// mutex never covered the user's own editor either, so refusing writes here
@@ -120,6 +130,25 @@ func buildSharedLocalDirectoryBlock(shared bool) string {
return b.String()
}
+// buildReusedWorkdirBlock tells a fresh session that its working directory
+// already holds an earlier run's files. Nothing else says so: the brief points
+// at `multica repo checkout` for fetching code, and on an existing checkout
+// that command runs `git reset --hard` and `git clean -fd` before branching
+// from the default branch, so following the brief would delete the
+// uncommitted work the reuse exists to keep. Per-turn, not in the brief: it is
+// true of this run only, and the brief must stay byte-stable across runs
+// (MUL-5377).
+func buildReusedWorkdirBlock(reused bool) string {
+ if !reused {
+ return ""
+ }
+ var b strings.Builder
+ b.WriteString("## Files from an earlier run\n\n")
+ b.WriteString("Your working directory was kept from an earlier run, but this run does not continue that run's conversation, so you have no memory of what it did here. Repository checkouts in it may hold that work, including uncommitted changes.\n\n")
+ b.WriteString("Look before you fetch anything: list the working directory, and in each existing checkout run `git status` and `git log` to see what was changed. Continue from that work where it serves this task. Do not run `multica repo checkout` for a repository that is already checked out here unless you have confirmed nothing in it needs keeping — on an existing checkout it discards uncommitted changes, untracked files included, and starts a new branch from the default branch.\n\n")
+ return b.String()
+}
+
// maxConflictListBytes bounds the RENDERED file list, in bytes of the escaped
// output rather than in entries: a git path can be as long as the filesystem
// allows, so a per-entry count bounds nothing. 4 KiB is roughly a thousand
diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.go
index 84dbee31df..b601a1099d 100644
--- a/server/internal/daemon/prompt_test.go
+++ b/server/internal/daemon/prompt_test.go
@@ -2071,3 +2071,43 @@ func TestWorktreeReplayConflictBlock(t *testing.T) {
}
})
}
+
+// TestReusedWorkdirBlock covers the warning a fresh session gets when it lands
+// in an earlier run's workdir (MUL-7034): it must say the files are there and
+// that `multica repo checkout` would reset an existing checkout, and it is
+// appended per turn after the prompt body, never ahead of it. That it reaches
+// the backend's prompt and not the brief is pinned end to end by
+// TestRunTaskWarnsFreshSessionInReusedWorkdir.
+func TestReusedWorkdirBlock(t *testing.T) {
+ t.Parallel()
+
+ issue := Task{IssueID: "issue-1", IssueIdentifier: "MUL-7034"}
+ chat := Task{ChatSessionID: "chat-1", ChatMessage: "keep going"}
+
+ if out := BuildPrompt(issue, "codex"); strings.Contains(out, "Files from an earlier run") {
+ t.Fatalf("reused-workdir warning rendered without the option:\n%s", out)
+ }
+ for name, task := range map[string]Task{"issue": issue, "chat": chat} {
+ t.Run(name, func(t *testing.T) {
+ out := BuildPrompt(task, "codex", WithReusedWorkdir())
+ block := buildReusedWorkdirBlock(true)
+ if !strings.HasSuffix(out, block) {
+ t.Fatalf("warning was not appended after the %s prompt body:\n%s", name, out)
+ }
+ if !strings.HasPrefix(out, buildPromptBody(task, "codex")) {
+ t.Fatalf("warning displaced the %s prompt body:\n%s", name, out)
+ }
+ for _, want := range []string{
+ "## Files from an earlier run",
+ "no memory of what it did here",
+ "`git status`",
+ "Do not run `multica repo checkout` for a repository that is already checked out here",
+ "discards uncommitted changes",
+ } {
+ if !strings.Contains(block, want) {
+ t.Fatalf("warning missing %q:\n%s", want, block)
+ }
+ }
+ })
+ }
+}
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index f2c4c6c5c7..78a971edb2 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -421,9 +421,11 @@ type AgentTaskResponse struct {
PriorWorkDir string `json:"prior_work_dir,omitempty"` // work_dir from a previous task on same issue
// PriorSessionResumeUnavailable is set when a more recent Codex session was
// withheld because its rollout was missing (MUL-5305); PriorSessionID (if
- // any) is then an older fallback. The daemon surfaces the continuity gap in
- // the brief even when that older session resumes cleanly. omitempty keeps it
- // off the wire for the common (no-gap) case and for old daemons.
+ // any) is then an older fallback, and the daemon surfaces the continuity gap
+ // in the brief even when that older session resumes cleanly. It is also set
+ // when an automatic retry continues in its parent's workdir under a fresh
+ // session (MUL-7034). omitempty keeps it off the wire for the common
+ // (no-gap) case and for old daemons.
PriorSessionResumeUnavailable bool `json:"prior_session_resume_unavailable,omitempty"`
WorkDir string `json:"work_dir,omitempty"` // local working directory pinned for this task; populated once the daemon reports it
// RelativeWorkDir is a privacy-safe display form of WorkDir intended for
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 482da80503..b1cf5c4c26 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2148,6 +2148,28 @@ func rerunSourceMatchesTaskScope(task, source db.AgentTaskQueue) bool {
return false
}
+// applyFreshSessionRetryWorkdir resolves the prior pointers for an automatic
+// retry that must start a fresh session. CreateRetryTask forces one only when
+// the parent's failure poisoned the conversation (currently
+// codex_semantic_inactivity), and still copies the parent's work_dir onto the
+// child: a poisoned conversation says nothing about the files it left behind,
+// the same contract the manual-retry branch applies (MUL-4869, MUL-7034).
+//
+// The workdir is offered only to a daemon that warns the fresh session about
+// the files it will find (DaemonCapabilityReusedWorkdirNoticeV1). Unwarned, the
+// session follows the brief and re-runs `multica repo checkout`, which resets
+// an existing checkout and deletes the work being kept, so an older daemon gets
+// a fresh directory as before. The daemon validates the directory before
+// reusing it and falls back to a fresh Prepare when it is gone. Either way the
+// failed attempt's working memory does not come back, so the continuity gap is
+// disclosed.
+func applyFreshSessionRetryWorkdir(task db.AgentTaskQueue, resp *AgentTaskResponse, daemonWarnsOfReusedWorkdir bool) {
+ if daemonWarnsOfReusedWorkdir && task.WorkDir.Valid {
+ resp.PriorWorkDir = task.WorkDir.String
+ }
+ resp.PriorSessionResumeUnavailable = true
+}
+
func claimResponseAgentIdentityMatches(resp AgentTaskResponse) bool {
return resp.AgentID != "" && resp.Agent != nil && resp.Agent.ID == resp.AgentID
}
@@ -2782,6 +2804,11 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}); err == nil && missing {
resp.PriorSessionResumeUnavailable = true
}
+ } else if task.RetryOfTaskID.Valid {
+ // Automatic retry that must start a fresh session: continue in the
+ // parent's workdir, never its session. A force_fresh task with no
+ // retry lineage still resumes nothing.
+ applyFreshSessionRetryWorkdir(*task, &resp, requestHasClientCapability(r, protocol.DaemonCapabilityReusedWorkdirNoticeV1))
}
}
@@ -2956,6 +2983,11 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
if err == nil && missing {
resp.PriorSessionResumeUnavailable = true
}
+ } else if task.RetryOfTaskID.Valid {
+ // Same as the issue branch. The retry lineage is what separates this
+ // from a user-requested fresh start (the Lark fresh-session command),
+ // which still inherits nothing.
+ applyFreshSessionRetryWorkdir(*task, &resp, requestHasClientCapability(r, protocol.DaemonCapabilityReusedWorkdirNoticeV1))
}
parts := make([]string, 0, len(unanswered))
diff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.go
index 0f84337d78..085ac46c8a 100644
--- a/server/internal/handler/daemon_test.go
+++ b/server/internal/handler/daemon_test.go
@@ -2730,10 +2730,20 @@ type claimRuntimeGuardTask struct {
func claimTaskForRuntimeGuard(t *testing.T, runtimeID, daemonID string) *claimRuntimeGuardTask {
t.Helper()
+ return claimTaskForRuntimeGuardWithCapabilities(t, runtimeID, daemonID, "")
+}
+
+// claimTaskForRuntimeGuardWithCapabilities claims as a daemon advertising the
+// given X-Client-Capabilities value ("" for a daemon that advertises none).
+func claimTaskForRuntimeGuardWithCapabilities(t *testing.T, runtimeID, daemonID, capabilities string) *claimRuntimeGuardTask {
+ t.Helper()
w := httptest.NewRecorder()
req := newDaemonTokenRequest("POST", "/api/daemon/runtimes/"+runtimeID+"/claim", nil,
testWorkspaceID, daemonID)
+ if capabilities != "" {
+ req.Header.Set("X-Client-Capabilities", capabilities)
+ }
rctx := chi.NewRouteContext()
rctx.URLParams.Add("runtimeId", runtimeID)
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))
@@ -3182,6 +3192,141 @@ func TestClaimTask_ManualRetryReusesWorkdir(t *testing.T) {
})
}
+// createAutoRetryForTest runs the production retry insert against a failed
+// parent, so a claim test exercises the row CreateRetryTask actually writes.
+func createAutoRetryForTest(t *testing.T, ctx context.Context, parentID string) {
+ t.Helper()
+ child, err := testHandler.Queries.CreateRetryTask(ctx, db.CreateRetryTaskParams{ID: parseUUID(parentID)})
+ if err != nil {
+ t.Fatalf("setup: CreateRetryTask: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, child.ID)
+ })
+}
+
+// TestClaimTask_AutoRetryFreshSessionReusesParentWorkdir is the MUL-7034
+// claim-layer contract for an automatic retry of a conversation-poisoning
+// failure: a fresh session, the parent's workdir, and a disclosed continuity
+// gap. The retry row comes from the real CreateRetryTask so the query and the
+// claim are pinned together; the workdir reaches the daemon only when both
+// carry it (GH #7998). The workdir is offered only to a daemon that warns the
+// fresh session about the files it will find there; an older daemon keeps
+// getting a fresh directory, because unwarned its agent would re-run
+// `multica repo checkout` and reset the very checkout being kept. Contrast a
+// force_fresh task with no retry lineage, which resumes nothing
+// (TestClaimTask_IssuePriorSessionRuntimeGuard).
+func TestClaimTask_AutoRetryFreshSessionReusesParentWorkdir(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ for _, tc := range []struct {
+ name string
+ capabilities string
+ wantWorkDir string
+ }{
+ {
+ name: "daemon_warns_of_reused_workdir",
+ capabilities: protocol.DaemonCapabilityReusedWorkdirNoticeV1,
+ wantWorkDir: "/tmp/codex-stuck-workdir",
+ },
+ {
+ name: "older_daemon_gets_fresh_directory",
+ capabilities: protocol.DaemonCapabilityCoalescedCommentsV1,
+ wantWorkDir: "",
+ },
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ ctx := context.Background()
+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)
+ issueID := dbfx.Issue(t, "auto-retry fresh-session fixture", testutil.Cols{"status": "in_progress"})
+
+ // An earlier healthy turn is what the (agent, issue) resume lookup
+ // returns, since it skips the poisoned parent. Getting its session or
+ // workdir back would mean the retry fell through to that lookup.
+ dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "issue_id": issueID,
+ "status": "completed",
+ "started_at": testutil.Raw("now() - interval '30 minutes'"),
+ "completed_at": testutil.Raw("now() - interval '25 minutes'"),
+ "session_id": "earlier-healthy-session",
+ "work_dir": "/tmp/earlier-healthy-workdir",
+ })
+ parentID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "issue_id": issueID,
+ "status": "failed",
+ "failure_reason": "codex_semantic_inactivity",
+ "started_at": testutil.Raw("now() - interval '20 minutes'"),
+ "completed_at": testutil.Raw("now() - interval '1 minute'"),
+ "session_id": "codex-stuck-session",
+ "work_dir": "/tmp/codex-stuck-workdir",
+ "attempt": 1,
+ "max_attempts": 2,
+ })
+ createAutoRetryForTest(t, ctx, parentID)
+
+ task := claimTaskForRuntimeGuardWithCapabilities(t, runtimeID, daemonID, tc.capabilities)
+ if task.PriorWorkDir != tc.wantWorkDir {
+ t.Fatalf("PriorWorkDir = %q, want %q", task.PriorWorkDir, tc.wantWorkDir)
+ }
+ if task.PriorSessionID != "" {
+ t.Fatalf("PriorSessionID = %q, want empty (the poisoned session must not resume)", task.PriorSessionID)
+ }
+ if !task.PriorSessionResumeUnavailable {
+ t.Fatal("auto-retry must disclose that the failed attempt's context did not come back")
+ }
+ })
+ }
+}
+
+// TestClaimTask_ChatAutoRetryFreshSessionReusesParentWorkdir is the chat half
+// of the same contract. The chat_session pointer names a different session and
+// workdir, so the assertions prove the retry continues its parent rather than
+// the conversation-wide pointer. Contrast a force_fresh chat task with no retry
+// lineage, which inherits nothing
+// (TestClaimTask_ChatForceFreshSessionSkipsPriorSession).
+func TestClaimTask_ChatAutoRetryFreshSessionReusesParentWorkdir(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)
+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{
+ "title": "auto-retry fresh chat",
+ "session_id": "chat-pointer-session",
+ "work_dir": "/tmp/chat-pointer-workdir",
+ "runtime_id": runtimeID,
+ })
+ parentID := dbfx.Task(t, agentID, testutil.Cols{
+ "runtime_id": runtimeID,
+ "chat_session_id": chatSessionID,
+ "status": "failed",
+ "failure_reason": "codex_semantic_inactivity",
+ "started_at": testutil.Raw("now() - interval '20 minutes'"),
+ "completed_at": testutil.Raw("now() - interval '1 minute'"),
+ "session_id": "codex-stuck-chat-session",
+ "work_dir": "/tmp/codex-stuck-chat-workdir",
+ "attempt": 1,
+ "max_attempts": 2,
+ })
+ createAutoRetryForTest(t, ctx, parentID)
+
+ task := claimTaskForRuntimeGuardWithCapabilities(t, runtimeID, daemonID, protocol.DaemonCapabilityReusedWorkdirNoticeV1)
+ if task.PriorWorkDir != "/tmp/codex-stuck-chat-workdir" {
+ t.Fatalf("PriorWorkDir = %q, want the failed parent's /tmp/codex-stuck-chat-workdir", task.PriorWorkDir)
+ }
+ if task.PriorSessionID != "" {
+ t.Fatalf("PriorSessionID = %q, want empty (the poisoned session must not resume)", task.PriorSessionID)
+ }
+ if !task.PriorSessionResumeUnavailable {
+ t.Fatal("chat auto-retry must disclose that the failed attempt's context did not come back")
+ }
+}
+
func TestClaimTask_ChatPriorSessionRuntimeGuard(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index 36e7f998f3..18674c42a4 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -2826,7 +2826,7 @@ SELECT
CASE WHEN p.chat_session_id IS NOT NULL THEN GREATEST(p.priority, 3) ELSE p.priority END,
p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.session_id END,
- CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,
+ p.work_dir,
p.attempt + 1, COALESCE($3::int, p.max_attempts), p.id,
p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',
p.is_leader_task,
@@ -2883,8 +2883,11 @@ type CreateRetryTaskParams struct {
// agent's resume context (session_id/work_dir) so the child can continue
// the conversation when the backend supports it. Resume-unsafe failures are
// retried as fresh sessions so the child does not inherit a stuck agent
-// conversation. Keep the CASE WHEN predicates in sync with
-// resumeUnsafeFailureReason and the resume lookup blacklists. attempt is
+// conversation, but work_dir is still carried forward: a poisoned
+// conversation says nothing about the files it left behind, and the claim
+// handler offers that workdir to the fresh session (MUL-7034). Keep the CASE
+// WHEN predicates in sync with resumeUnsafeFailureReason and the resume lookup
+// blacklists. attempt is
// incremented; max_attempts, trigger_comment_id, coalesced_comment_ids,
// is_leader_task, and squad_id are inherited so the retried task receives the
// parent's complete planned comment batch and keeps the same squad-role
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 9a52a9e39c..8d0c0e6307 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -465,8 +465,11 @@ WHERE id = $1 AND issue_id IS NULL
-- agent's resume context (session_id/work_dir) so the child can continue
-- the conversation when the backend supports it. Resume-unsafe failures are
-- retried as fresh sessions so the child does not inherit a stuck agent
--- conversation. Keep the CASE WHEN predicates in sync with
--- resumeUnsafeFailureReason and the resume lookup blacklists. attempt is
+-- conversation, but work_dir is still carried forward: a poisoned
+-- conversation says nothing about the files it left behind, and the claim
+-- handler offers that workdir to the fresh session (MUL-7034). Keep the CASE
+-- WHEN predicates in sync with resumeUnsafeFailureReason and the resume lookup
+-- blacklists. attempt is
-- incremented; max_attempts, trigger_comment_id, coalesced_comment_ids,
-- is_leader_task, and squad_id are inherited so the retried task receives the
-- parent's complete planned comment batch and keeps the same squad-role
@@ -531,7 +534,7 @@ SELECT
CASE WHEN p.chat_session_id IS NOT NULL THEN GREATEST(p.priority, 3) ELSE p.priority END,
p.trigger_comment_id, p.coalesced_comment_ids, p.trigger_summary, p.context,
CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.session_id END,
- CASE WHEN p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity' THEN NULL ELSE p.work_dir END,
+ p.work_dir,
p.attempt + 1, COALESCE(sqlc.narg(max_attempts)::int, p.max_attempts), p.id,
p.failure_reason IS NOT DISTINCT FROM 'codex_semantic_inactivity',
p.is_leader_task,
diff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.go
index fdafeb8c58..143286d36e 100644
--- a/server/pkg/protocol/messages.go
+++ b/server/pkg/protocol/messages.go
@@ -49,6 +49,19 @@ const (
// nothing extra, so the stub retires itself as daemons update.
DaemonCapabilityPlatformSkillV1 = "platform-skill-v1"
+ // DaemonCapabilityReusedWorkdirNoticeV1 advertises that the daemon warns a
+ // fresh provider session when it lands in a workdir an earlier run left
+ // behind (MUL-7034).
+ //
+ // The server hands an automatic retry that must start a fresh session its
+ // parent's workdir only when this is present. That session has no memory of
+ // the work in the directory, and the brief tells it to fetch repositories
+ // with `multica repo checkout`, which resets an existing checkout and deletes
+ // uncommitted changes. Without the warning, reusing the directory would
+ // destroy the work it was meant to keep, so an older daemon keeps getting a
+ // fresh directory and the parent's stays untouched on disk.
+ DaemonCapabilityReusedWorkdirNoticeV1 = "reused-workdir-notice-v1"
+
// AppCapabilityChatDraftRestoreV1 is advertised (X-Client-Capabilities) by
// app clients that understand the durable draft-restore recovery path:
// chat:cancel_finalized as an invalidation hint plus the draft-restores