Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7094 fix(pi): drop a resume whose recorded cwd is gone (#8097)
Bohan Jiang33222ff52f9d
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex eab5f7cb6c..b3aa8a12d2 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -1,6 +1,7 @@package daemonimport (+ "bufio""context""encoding/json""errors"@@ -6165,10 +6166,10 @@ func sameExistingDir(a, b string) bool {return os.SameFile(ai, bi)}-func gateResumeToReachableSession(task *Task, taskCtx *execenv.TaskContextForEnv, provider, envWorkDir string, sessionHomeReachable bool, taskLog *slog.Logger) bool {+func gateResumeToReachableSession(task *Task, taskCtx *execenv.TaskContextForEnv, provider, envWorkDir string, sessionHomeReachable, refusesMissingSessionCwd bool, taskLog *slog.Logger) bool {var reachable boolif providerUsesPiSessionFile(provider) {- reachable = piSessionFilePresent(task.PriorSessionID)+ reachable = piSessionResumable(task.PriorSessionID, refusesMissingSessionCwd)} else {// Compare the directories, not the spelling. Reuse runs in the canonical// path it validated and locked, which need not be character-identical to@@ -6205,6 +6206,66 @@ func providerUsesPiSessionFile(provider string) bool {return ok && desc.ProtocolFamily == "pi"}+// piSessionResumable reports whether the backend can actually START from this+// session. The transcript file always has to be there; whether its recorded+// working directory also has to be there depends on the runtime, which is what+// refusesMissingCwd carries (providerRefusesMissingSessionCwd).+//+// Checking only the file is what produced GH #8082: after the prior task's+// worktree was reclaimed the file survived, the gate reported the session+// reachable, and Pi exited 1 in under 200ms with no tool call and no output —+// permanently, because the failed run records the same session id again and the+// next claim serves the same stale pointer. That is the exact failure shape the+// gate above exists to prevent; #7760 removed the protection for the Pi family+// without replacing it with the key Pi actually validates.+func piSessionResumable(sessionID string, refusesMissingCwd bool) bool {+ if !piSessionFilePresent(sessionID) {+ return false+ }+ return !refusesMissingCwd || piSessionCwdPresent(sessionID)+}++// providerRefusesMissingSessionCwd reports whether a runtime refuses to start+// when the working directory recorded in the transcript no longer exists.+//+// This is deliberately NOT the same question as providerUsesPiSessionFile.+// That one asks where the session lives — an independently addressed JSONL path+// rather than a cwd-keyed store — and it is true for the whole Pi protocol+// family. This one asks what the runtime does with the cwd it finds inside that+// file, and the family does not agree:+//+// - pi re-anchors a resumed run to the recorded cwd and hard-refuses when it+// is gone (GH #8082).+// - omp opens the transcript from an explicit --session path and falls back to+// the launch cwd instead; verified on v17.2.12, where the same transcript+// whose recorded cwd had been deleted resumed with exit 0 and ran in the+// launch directory.+//+// So the check must not be applied family-wide: doing that drops omp sessions+// omp would have resumed cleanly, which is exactly the continuity loss #7760+// set out to fix.+//+// builtinRuntime is why the provider name alone cannot answer this. A custom+// runtime profile keeps its protocol family as the provider, so+// `protocol_family: pi` with `command_name: <anything>` also arrives here as+// "pi" while being an unrelated implementation — the same trap agent.Config's+// BuiltinRuntime field documents. Only the provider's own discovered binary is+// the CLI whose refusal was actually verified, so a custom command answers+// false and keeps its session.+//+// False is the safe default in both directions — unknown Pi-family runtime,+// and custom command. A runtime that refuses in the words the backend matches+// (piResumeRefusedMarker) is still recovered by Result.ResumeRejected: one+// wasted run and a fresh session, not the permanent loop this issue reported.+// That backstop is a single phrase match and does not generalise to a refusal+// worded differently — but it does cover the case this default is most likely+// to be wrong about, a Pi-family runtime behaving like Pi. Guessing the other+// way has no backstop at all: it silently discards history that was never in+// danger, with nothing downstream to notice.+func providerRefusesMissingSessionCwd(provider string, builtinRuntime bool) bool {+ return builtinRuntime && provider == "pi"+}+// piSessionFilePresent proves there is persisted history to resume. It does// not claim the transcript is idle: the Pi backend takes an exclusive lock for// the complete child-process lifetime and reports a busy resume as rejected so@@ -6217,6 +6278,76 @@ func piSessionFilePresent(sessionID string) bool {return err == nil && info.Mode().IsRegular() && info.Size() > 0}+// piSessionCwdPresent mirrors Pi's own startup check, deliberately condition+// for condition, so the two cannot disagree about what "resumable" means a+// second time. Pi refuses to start if and only if the transcript carries a+// session header whose `cwd` is non-empty and does not exist on disk; with no+// header, or an empty cwd, it falls back to the launch directory and starts+// normally. Anything this predicate cannot read is therefore NOT evidence of a+// refusal, and returns true: a false negative here silently discards healthy+// conversation history, which is the regression #7760 set out to fix.+//+// Existence is the whole test — not "is a directory". Pi uses existsSync, which+// is true for a plain file too, so demanding a directory would drop sessions Pi+// would have accepted and re-open the same divergence from the other side.+//+// Note this says nothing about WHICH directory the resumed run will use. Pi+// adopts the recorded cwd, so a session whose recorded cwd still exists but is+// not this task's workdir resumes into the older directory. That is a separate+// defect with a separate fix; this predicate deliberately keeps the existing+// behaviour there rather than widening a crash fix into a semantic change.+func piSessionCwdPresent(sessionID string) bool {+ cwd, ok := piSessionRecordedCwd(sessionID)+ if !ok || cwd == "" {+ return true+ }+ _, err := os.Stat(cwd)+ return err == nil+}++// piSessionHeaderScanLines bounds how far into a transcript we look for the+// session header. Pi writes it as the first line at session creation, so the+// answer is always line 1 in practice; the bound only stops a pathological or+// hand-edited file from turning a cheap predicate into a full read of a+// multi-megabyte transcript.+const piSessionHeaderScanLines = 64++// piSessionMaxHeaderLine caps a single scanned line. A transcript's later lines+// carry whole assistant turns and can be far larger than bufio's 64KB default;+// without this the scan would stop early with an error on a perfectly healthy+// file.+const piSessionMaxHeaderLine = 1 << 20++// piSessionRecordedCwd returns the cwd recorded in the transcript's session+// header. The bool reports whether a header was found at all — callers must+// distinguish "no header" (Pi starts fine) from "header with an empty cwd"+// (also fine), and neither from a real recorded directory.+func piSessionRecordedCwd(path string) (string, bool) {+ f, err := os.Open(path)+ if err != nil {+ return "", false+ }+ defer func() { _ = f.Close() }()++ scanner := bufio.NewScanner(f)+ scanner.Buffer(make([]byte, 0, 64*1024), piSessionMaxHeaderLine)+ for i := 0; i < piSessionHeaderScanLines && scanner.Scan(); i++ {+ var entry struct {+ Type string `json:"type"`+ Cwd string `json:"cwd"`+ }+ // A malformed line is skipped rather than failing the scan: Pi itself+ // tolerates unparseable entries when loading a transcript.+ if err := json.Unmarshal(scanner.Bytes(), &entry); err != nil {+ continue+ }+ if entry.Type == "session" {+ return entry.Cwd, true+ }+ }+ return "", false+}+// sessionHomeReachable reports whether a session recorded by a prior task on// this conversation can still be found from THIS run's environment, for// providers that key their sessions somewhere other than the cwd.@@ -7849,7 +7980,16 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot icancelPrepare()_ = d.client.ReportProgress(ctx, task.ID, fmt.Sprintf("Launching %s", provider), 1, 2)- resumeReachable := gateResumeToReachableSession(&task, &taskCtx, provider, env.WorkDir, sessionHomeReachable(provider, env, envReused), taskLog)+ // usesCustomProfileCommand is the same provenance the backend receives as+ // agent.Config.BuiltinRuntime: it separates the provider's own discovered+ // binary from an arbitrary command speaking its protocol. Reused here so+ // the gate and the backend cannot disagree about which one is running.+ resumeReachable := gateResumeToReachableSession(+ &task, &taskCtx, provider, env.WorkDir,+ sessionHomeReachable(provider, env, envReused),+ providerRefusesMissingSessionCwd(provider, !usesCustomProfileCommand),+ taskLog,+ )// A reused workdir is necessary but not sufficient for a Codex resume: the// prior thread's rollout must actually be present in this task's CODEX_HOME// sessions (MUL-4424 isolates them). Drop the resume before the brief isdiff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex d1dee34c3b..32fdeac4df 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -2000,7 +2000,7 @@ func TestGateResumeToReachableSession(t *testing.T) {task := Task{PriorSessionID: tt.sessionID, PriorWorkDir: priorDir}taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: tt.sessionID != ""}- reachable := gateResumeToReachableSession(&task, &taskCtx, "claude", envDir, !tt.sessionHomeUnreachable, slog.Default())+ reachable := gateResumeToReachableSession(&task, &taskCtx, "claude", envDir, !tt.sessionHomeUnreachable, false, slog.Default())if reachable != tt.wantReused {t.Fatalf("reachable = %v, want %v", reachable, tt.wantReused)@@ -2045,7 +2045,7 @@ func TestGatePiResumeToSessionFile(t *testing.T) {task := Task{PriorSessionID: sessionFile, PriorWorkDir: priorDir}taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: true}- reachable := gateResumeToReachableSession(&task, &taskCtx, provider, envDir, true, slog.Default())+ reachable := gateResumeToReachableSession(&task, &taskCtx, provider, envDir, true, providerRefusesMissingSessionCwd(provider, true), slog.Default())if !reachable {t.Fatal("Pi-family session file should remain reachable across workdirs")@@ -2105,7 +2105,7 @@ func TestGatePiResumeDropsUnusableSessionFile(t *testing.T) {task := Task{PriorSessionID: sessionPath, PriorWorkDir: workDir}taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: true}- reachable := gateResumeToReachableSession(&task, &taskCtx, "pi", workDir, true, slog.Default())+ reachable := gateResumeToReachableSession(&task, &taskCtx, "pi", workDir, true, providerRefusesMissingSessionCwd("pi", true), slog.Default())if reachable {t.Fatalf("%s Pi session was treated as reachable", test.name)@@ -2123,6 +2123,262 @@ func TestGatePiResumeDropsUnusableSessionFile(t *testing.T) {}}+// TestGatePiResumeChecksRecordedCwd covers GH #8082: the session file existing+// is not sufficient, because Pi re-anchors a resumed run to the cwd recorded in+// the transcript header and refuses to start when that directory is gone.+//+// The predicate mirrors Pi's own check condition for condition, so the cases+// where Pi starts FINE matter as much as the one where it refuses — reading any+// of them as unresumable would discard healthy history, which is the regression+// #7760 set out to fix in the first place.+//+// The same reasoning is why the two runtimes carry separate expectations. The+// refusal is Pi's behaviour, not the protocol family's: omp opens the+// transcript from the explicit --session path and falls back to the launch cwd,+// so applying Pi's constraint to it would drop sessions it resumes cleanly.+func TestGatePiResumeChecksRecordedCwd(t *testing.T) {+ t.Parallel()++ header := func(cwd string) string {+ return fmt.Sprintf(`{"type":"session","version":3,"id":"01a0","timestamp":"2026-09-06T00:00:00.000Z","cwd":%q}`, cwd)+ }++ for _, test := range []struct {+ name string+ // body builds the transcript. liveDir exists; deadDir does not.+ body func(liveDir, deadDir, aFile string) string+ // Expectations are keyed by whether the RUNTIME is one we may drop a+ // session for, not by its name. Only pi's own binary is: it hard-+ // refuses on a missing recorded cwd. omp is verified to fall back to+ // the launch cwd instead, and a custom command's behaviour is simply+ // unknown — neither is the CLI the refusal was verified against, so+ // dropping their session risks pure continuity loss.+ wantRefusing bool+ wantTolerant bool+ }{+ {+ // The reported failure: worktree reclaimed, transcript survives.+ name: "recorded cwd no longer exists",+ body: func(_, deadDir, _ string) string {+ // Pi writes the header twice on a real session; keep the+ // fixture faithful to what is actually on disk.+ return header(deadDir) + "\n" + header(deadDir) + "\n"+ },+ wantRefusing: false,+ wantTolerant: true,+ },+ {+ name: "recorded cwd still exists",+ body: func(liveDir, _, _ string) string {+ return header(liveDir) + "\n"+ },+ wantRefusing: true,+ wantTolerant: true,+ },+ {+ // No header: Pi falls back to the launch directory and starts.+ name: "no session header",+ body: func(_, _, _ string) string {+ return `{"type":"model_change","id":"a"}` + "\n"+ },+ wantRefusing: true,+ wantTolerant: true,+ },+ {+ // Empty cwd: Pi's own guard short-circuits on falsy and starts.+ name: "header records an empty cwd",+ body: func(_, _, _ string) string {+ return header("") + "\n"+ },+ wantRefusing: true,+ wantTolerant: true,+ },+ {+ // Pi uses existsSync, which is true for a plain file. Demanding a+ // directory here would drop a session Pi would have accepted.+ name: "recorded cwd is a file",+ body: func(_, _, aFile string) string {+ return header(aFile) + "\n"+ },+ wantRefusing: true,+ wantTolerant: true,+ },+ {+ // Unparseable leading lines must not hide the header behind them.+ name: "malformed line precedes the header",+ body: func(_, deadDir, _ string) string {+ return "not json\n" + header(deadDir) + "\n"+ },+ wantRefusing: false,+ wantTolerant: true,+ },+ {+ // Past the bounded scan we cannot read the header, and "could not+ // read" is not evidence of a refusal — keep the session and let the+ // backend's ResumeRejected signal recover if Pi does refuse.+ name: "header sits beyond the scan bound",+ body: func(_, deadDir, _ string) string {+ var b strings.Builder+ for i := 0; i < piSessionHeaderScanLines+1; i++ {+ b.WriteString(`{"type":"model_change","id":"a"}` + "\n")+ }+ b.WriteString(header(deadDir) + "\n")+ return b.String()+ },+ wantRefusing: true,+ wantTolerant: true,+ },+ } {+ // refusesMissingCwd is stated as a literal rather than read back from+ // providerRefusesMissingSessionCwd, so this matrix cannot be satisfied+ // by the predicate agreeing with itself. The predicate's own answers+ // are pinned in TestProviderRefusesMissingSessionCwd.+ for _, runtime := range []struct {+ name string+ provider string+ refusesMissingCwd bool+ }{+ {name: "pi", provider: "pi", refusesMissingCwd: true},+ {name: "omp", provider: "omp", refusesMissingCwd: false},+ // A custom runtime profile registers its protocol family as the+ // provider, so an arbitrary command configured as `protocol_family:+ // pi` also arrives here as "pi". It is not the binary whose refusal+ // was verified, so it must keep its session.+ {name: "custom-pi-family-profile", provider: "pi", refusesMissingCwd: false},+ } {+ wantReachable := test.wantTolerant+ if runtime.refusesMissingCwd {+ wantReachable = test.wantRefusing+ }+ provider := runtime.provider+ t.Run(test.name+"/"+runtime.name, func(t *testing.T) {+ t.Parallel()++ base := t.TempDir()+ workDir := filepath.Join(base, "workdir")+ liveDir := filepath.Join(base, "live-workdir")+ for _, dir := range []string{workDir, liveDir} {+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatalf("create %s: %v", dir, err)+ }+ }+ deadDir := filepath.Join(base, "reclaimed-workdir")+ aFile := filepath.Join(base, "not-a-directory")+ if err := os.WriteFile(aFile, []byte("x"), 0o644); err != nil {+ t.Fatalf("create file: %v", err)+ }++ sessionPath := filepath.Join(base, "session.jsonl")+ if err := os.WriteFile(sessionPath, []byte(test.body(liveDir, deadDir, aFile)), 0o644); err != nil {+ t.Fatalf("create session: %v", err)+ }++ task := Task{PriorSessionID: sessionPath, PriorWorkDir: liveDir}+ taskCtx := execenv.TaskContextForEnv{PriorSessionResumed: true}++ reachable := gateResumeToReachableSession(&task, &taskCtx, provider, workDir, true, runtime.refusesMissingCwd, slog.Default())++ if reachable != wantReachable {+ t.Fatalf("reachable = %v, want %v", reachable, wantReachable)+ }+ if wantReachable {+ if task.PriorSessionID != sessionPath {+ t.Fatalf("PriorSessionID = %q, want %q", task.PriorSessionID, sessionPath)+ }+ if taskCtx.PriorSessionResumeUnavailable {+ t.Fatal("a resumable session was reported unavailable")+ }+ return+ }+ if task.PriorSessionID != "" {+ t.Fatalf("PriorSessionID = %q, want empty", task.PriorSessionID)+ }+ if taskCtx.PriorSessionResumed {+ t.Fatal("PriorSessionResumed stayed true for an unusable session")+ }+ // The user asked to continue this conversation; a silent+ // restart is what MUL-4424 forbids.+ if !taskCtx.PriorSessionResumeUnavailable {+ t.Fatal("dropped session was not disclosed as unavailable")+ }+ })+ }+ }+}++// TestProviderRefusesMissingSessionCwd pins which runtimes are allowed to have+// their prior session dropped for a missing recorded cwd.+//+// The provider name alone cannot answer this. A custom runtime profile keeps+// its protocol family as the provider, so `protocol_family: pi` with any+// command arrives as "pi" while being an unrelated implementation — the trap+// agent.Config.BuiltinRuntime documents. Only the provider's own discovered+// binary is the CLI whose refusal was verified.+//+// Everything else answers false, and that asymmetry is deliberate: a runtime+// that really does refuse is still recovered by the backend's ResumeRejected+// signal at the cost of one run, whereas a wrong true silently discards+// history that was never in danger and has no backstop at all.+func TestProviderRefusesMissingSessionCwd(t *testing.T) {+ t.Parallel()++ for _, test := range []struct {+ name string+ provider string+ builtin bool+ want bool+ }{+ {name: "pi's own binary refuses", provider: "pi", builtin: true, want: true},+ {name: "custom command speaking pi protocol", provider: "pi", builtin: false, want: false},+ {name: "omp's own binary tolerates", provider: "omp", builtin: true, want: false},+ {name: "custom command speaking omp protocol", provider: "omp", builtin: false, want: false},+ {name: "unrelated provider", provider: "claude", builtin: true, want: false},+ } {+ t.Run(test.name, func(t *testing.T) {+ t.Parallel()++ if got := providerRefusesMissingSessionCwd(test.provider, test.builtin); got != test.want {+ t.Fatalf("providerRefusesMissingSessionCwd(%q, builtin=%v) = %v, want %v",+ test.provider, test.builtin, got, test.want)+ }+ })+ }+}++// TestShouldRetryPiRefusedResume closes the GH #8082 loop end to end: it pins+// that the backend's new signal is what turns a refused Pi resume into a fresh+// retry, and that without it the same failure is unrecoverable.+//+// The negative case is the bug as shipped. Every other branch of the gate+// misses this failure — the error text carries no empty-message locator and no+// auth phrase, and Pi is (correctly) not in ResumeRejectionUndetectable — so+// the run failed as a plain process_failure, kept its session id, and the next+// claim served the same stale pointer forever.+func TestShouldRetryPiRefusedResume(t *testing.T) {+ t.Parallel()++ // Exactly what the daemon saw in the report: no output, no tool call, and+ // an error carrying only the process exit code.+ result := agent.Result{+ Status: "failed",+ Error: "pi exited with error: exit status 1",+ }+ const priorSession = "/home/u/.multica/pi-sessions/20260904T174429.978964000.jsonl"++ if shouldRetryWithFreshSession(result, priorSession, 0, "pi") {+ t.Fatal("a bare exit-1 must not trigger a fresh retry by exclusion")+ }++ result.ResumeRejected = true+ if !shouldRetryWithFreshSession(result, priorSession, 0, "pi") {+ t.Fatal("a refused Pi resume did not trigger the fresh-session retry")+ }+ // A run that already used a tool is never replayed, poisoned or not.+ if shouldRetryWithFreshSession(result, priorSession, 1, "pi") {+ t.Fatal("a run that used tools was retried")+ }+}+func TestSessionHomeReachable(t *testing.T) {t.Parallel()diff --git a/server/pkg/agent/pi.go b/server/pkg/agent/pi.goindex 049c10c700..716970519a 100644--- a/server/pkg/agent/pi.go+++ b/server/pkg/agent/pi.go@@ -1,6 +1,7 @@package agentimport (+ "bytes""context""encoding/json""fmt"@@ -268,7 +269,11 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptions}var closeStdinOnce sync.OncecloseStdin := func() { closeStdinOnce.Do(func() { _ = stdin.Close() }) }- cmd.Stderr = newLogWriter(b.cfg.Logger, "["+label+":stderr] ")+ // Watch stderr as well as log it. When Pi refuses a resume it exits before+ // emitting a single JSON event, so stderr is the only place the reason+ // exists and Result.ResumeRejected has nothing else to be built from.+ stderrWatch := newPiStderrWatcher(newLogWriter(b.cfg.Logger, "["+label+":stderr] "))+ cmd.Stderr = stderrWatchif err := startOwnedProcessTree(cmd, b.cfg.Logger); err != nil {closeStdin()@@ -484,6 +489,11 @@ func (b *piBackend) Execute(ctx context.Context, prompt string, opts ExecOptionsDurationMs: duration.Milliseconds(),SessionID: sessionPath,Usage: usage,+ // Only a run that asked to resume can have had a resume refused.+ // On a cold run the phrase cannot appear anyway, but stating the+ // precondition keeps this honest against Result.ResumeRejected's+ // contract rather than relying on Pi never saying it.+ ResumeRejected: opts.ResumeSessionID != "" && stderrWatch.resumeRefused(),}}()@@ -503,6 +513,64 @@ func piSessionBusyResult(label, sessionPath string) *Session {return &Session{Messages: msgCh, Result: resCh}}+// piResumeRefusedMarker is Pi's message when a resumed transcript names a+// working directory that no longer exists. Pi re-anchors a resumed run to the+// cwd recorded in the session header; when that directory is gone it prints+// this to stderr and exits 1 immediately, before any JSON event, any tool call+// and any output (GH #8082).+//+// The daemon's resume gate already declines to hand Pi such a session, so in+// normal operation this never fires. It is the second layer, and its reach is+// exactly this one refusal arriving on a run the gate let through: the+// directory disappearing between the gate's check and Pi's, a header the+// gate's bounded scan did not reach or could not parse, or a Pi-family runtime+// the gate does not model as refusing. It is a single phrase match, so it does+// NOT generalise to some other refusal Pi might grow later.+//+// Without it such a run fails as a generic non-retryable process_failure and+// the same stale pointer is served again on the next claim — the permanent+// loop #8082 reported.+const piResumeRefusedMarker = "Stored session working directory does not exist"++// piStderrTailLimit bounds the retained stderr tail. The marker arrives in a+// single write at startup, so this only has to be large enough that a partial+// flush cannot split it apart.+const piStderrTailLimit = 8 << 10++// piStderrWatcher tees Pi's stderr to the debug log while retaining a bounded+// tail to test for a resume refusal. Writes arrive from the child process+// goroutine and resumeRefused is read from the result goroutine after Wait, so+// the buffer is mutex-guarded rather than relying on that ordering.+type piStderrWatcher struct {+ log io.Writer++ mu sync.Mutex+ tail []byte+}++func newPiStderrWatcher(log io.Writer) *piStderrWatcher {+ return &piStderrWatcher{log: log}+}++func (w *piStderrWatcher) Write(p []byte) (int, error) {+ w.mu.Lock()+ w.tail = append(w.tail, p...)+ if len(w.tail) > piStderrTailLimit {+ w.tail = w.tail[len(w.tail)-piStderrTailLimit:]+ }+ w.mu.Unlock()+ // Never fail the child's stderr write on a logging problem: a short write+ // here makes Pi's own writer error out mid-run.+ _, _ = w.log.Write(p)+ return len(p), nil+}++func (w *piStderrWatcher) resumeRefused() bool {+ w.mu.Lock()+ defer w.mu.Unlock()+ return bytes.Contains(w.tail, []byte(piResumeRefusedMarker))+}+// ── Pi event types ──// piStreamEvent is the union of fields we consume from Pi's JSON eventdiff --git a/server/pkg/agent/pi_resume_refused_unix_test.go b/server/pkg/agent/pi_resume_refused_unix_test.gonew file mode 100644index 0000000000..92020d02cd--- /dev/null+++ b/server/pkg/agent/pi_resume_refused_unix_test.go@@ -0,0 +1,136 @@+//go:build unix++package agent++import (+ "fmt"+ "io"+ "log/slog"+ "os"+ "path/filepath"+ "testing"+ "time"+)++// TestPiExecuteReportsRefusedResume pins the backend half of the GH #8082 fix.+//+// When a resumed transcript names a working directory that no longer exists,+// Pi prints its refusal to stderr and exits 1 before emitting a single JSON+// event. Without a positive Result.ResumeRejected the daemon sees only+// "exit status 1", classifies a non-retryable process_failure, records the same+// session id again, and the next claim serves the same stale pointer — the+// permanent crash loop the issue reported. This test drives the real backend+// against a fake `pi` that reproduces that exact exit.+func TestPiExecuteReportsRefusedResume(t *testing.T) {+ t.Parallel()++ for _, test := range []struct {+ name string+ resume bool+ wantResumeRejects bool+ }{+ {name: "resumed run", resume: true, wantResumeRejects: true},+ // A cold run cannot have had a resume refused, whatever the CLI says.+ {name: "cold run", resume: false, wantResumeRejects: false},+ } {+ t.Run(test.name, func(t *testing.T) {+ t.Parallel()++ base := t.TempDir()+ sessionPath := filepath.Join(base, "session.jsonl")+ if err := os.WriteFile(sessionPath, []byte(`{"type":"session","cwd":"/gone"}`+"\n"), 0o644); err != nil {+ t.Fatalf("create session: %v", err)+ }++ // Mirrors Pi's own output: the refusal on stderr, nothing on+ // stdout, exit 1.+ script := fmt.Sprintf(+ "#!/bin/sh\ncat >/dev/null\necho %q >&2\nexit 1\n",+ piResumeRefusedMarker+": /gone",+ )+ fakePath := filepath.Join(base, "pi")+ writeTestExecutable(t, fakePath, []byte(script))++ backend, err := New("pi", Config{ExecutablePath: fakePath, Logger: slog.Default()})+ if err != nil {+ t.Fatalf("New(pi): %v", err)+ }++ opts := ExecOptions{Timeout: 30 * time.Second, Cwd: base}+ if test.resume {+ opts.ResumeSessionID = sessionPath+ }+ session, err := backend.Execute(t.Context(), "hello", opts)+ if err != nil {+ t.Fatalf("Execute: %v", err)+ }+ for range session.Messages {+ }+ result := <-session.Result++ if result.Status != "failed" {+ t.Fatalf("status = %q, want failed", result.Status)+ }+ if result.ResumeRejected != test.wantResumeRejects {+ t.Fatalf("ResumeRejected = %v, want %v (error=%q)",+ result.ResumeRejected, test.wantResumeRejects, result.Error)+ }+ // The transient flag means "another run holds the transcript" and+ // must stay off: unlike a busy lock, this session never becomes+ // usable again, so it has to be retired rather than retried onto.+ if result.ResumeRejectedTransient {+ t.Fatal("ResumeRejectedTransient set for a permanent refusal")+ }+ })+ }+}++// TestPiStderrWatcherSpansWrites guards the one way the marker could be missed:+// stderr arriving in fragments. A substring test over a single Write would pass+// the test above and still fail in production on a split flush.+func TestPiStderrWatcherSpansWrites(t *testing.T) {+ t.Parallel()++ w := newPiStderrWatcher(io.Discard)+ if w.resumeRefused() {+ t.Fatal("empty stderr reported a refusal")+ }+ marker := piResumeRefusedMarker+ split := len(marker) / 2+ if _, err := w.Write([]byte(marker[:split])); err != nil {+ t.Fatalf("write: %v", err)+ }+ if w.resumeRefused() {+ t.Fatal("half the marker reported a refusal")+ }+ if _, err := w.Write([]byte(marker[split:] + ": /gone\n")); err != nil {+ t.Fatalf("write: %v", err)+ }+ if !w.resumeRefused() {+ t.Fatal("marker split across writes was not detected")+ }+}++// TestPiStderrWatcherBoundsTail keeps a chatty run from retaining unbounded+// stderr, while still detecting a marker that arrives after the noise.+func TestPiStderrWatcherBoundsTail(t *testing.T) {+ t.Parallel()++ w := newPiStderrWatcher(io.Discard)+ noise := make([]byte, piStderrTailLimit*3)+ for i := range noise {+ noise[i] = 'x'+ }+ if _, err := w.Write(noise); err != nil {+ t.Fatalf("write: %v", err)+ }+ if got := len(w.tail); got > piStderrTailLimit {+ t.Fatalf("retained %d bytes, want <= %d", got, piStderrTailLimit)+ }+ if _, err := w.Write([]byte(piResumeRefusedMarker + ": /gone\n")); err != nil {+ t.Fatalf("write: %v", err)+ }+ if !w.resumeRefused() {+ t.Fatal("marker after bounded noise was not detected")+ }+}