Skip to main content

agentmux_srv_core/backend/blockcontroller/
persistent_resume.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One spawn attempt's stale-`--resume` retry decision, plus any terminal
5//! error-result line observed for it, as a single explicit state machine.
6//!
7//! This replaces three fields that used to live directly on
8//! `persistent::PersistentInner` — `pending_resume_retry`,
9//! `confirmed_stale_resume_retry`, and `pending_error_result_line` — which
10//! were mutated directly by four independently-scheduled tokio tasks
11//! (stdin writer, stdout reader, stderr reader, process-waiter) racing on
12//! a shared mutex. That shape caused the exact bug this module exists to
13//! prevent, twice: issue #2368's original report, and a live-reproduced
14//! recurrence (agent "Marks", 2026-07-30) where the stderr reader's
15//! `poison_resume` promotion landed ~500ms before the stdout reader
16//! finished draining lines, and a check of only one of the two fields
17//! missed the stash entirely.
18//!
19//! `update()` is a pure `(state, event) -> (state, effects)` function —
20//! every transition is exhaustively unit-testable without a real child
21//! process, a real tokio task, or any timing assumptions. Callers
22//! (the I/O tasks `persistent/spawn.rs` starts: `persistent/stdout_reader.rs`
23//! and `persistent/process_waiter.rs`) are responsible for actually executing
24//! the returned `ResumeEffect`s (persisting/dropping/flushing a line,
25//! firing the retry, publishing terminal status) — this module only
26//! decides, never performs I/O.
27//!
28//! Every event that could affect in-flight state carries the exact
29//! `generation` it was observed for. `update()` ignores an event whose
30//! generation doesn't match the state's currently-tracked generation, so
31//! a stale event from an already-resolved generation can never corrupt a
32//! later, unrelated generation's state — generation numbers are never
33//! reused (see `spawn_generation`'s doc comment in `persistent/mod.rs`).
34
35use super::persistent::PersistentSpawnConfig;
36
37/// One redeliverable stdin message in a [`RetryPayload`] batch: the
38/// formatted JSON plus its queue identity.
39///
40/// `seq` is the message's `QueuedMessage::seq` (issue #2365): assigned
41/// once from the controller's monotonic counter at first enqueue and
42/// preserved across redelivery, so every "is this message already
43/// queued / is this the seeded message" check is exact identity, never
44/// content equality — two genuinely different messages with identical
45/// text (two "yes" replies) can no longer be conflated.
46#[derive(Debug, Clone, PartialEq)]
47pub(super) struct QueuedRetryEntry {
48    pub seq: u64,
49    pub json: String,
50}
51
52/// The spawn config + the growing batch of stdin messages to redeliver if
53/// this generation's `--resume` turns out to be stale. Named separately
54/// from the state enum so `MessageAppendedToRetryBatch` can grow it in
55/// place without reconstructing the whole variant.
56#[derive(Debug, Clone, PartialEq)]
57pub(super) struct RetryPayload {
58    pub config: PersistentSpawnConfig,
59    pub messages: Vec<QueuedRetryEntry>,
60}
61
62impl RetryPayload {
63    /// Grow the batch keeping it in `seq` order, not arrival order.
64    ///
65    /// `seq` is assigned when a message is ACCEPTED, so seq order is the
66    /// order the user actually sent things. Arrival order at this batch is
67    /// not: the message that becomes the spawner seeds the batch first, and
68    /// the drain appends everything else afterwards — so a backlog retained
69    /// across a refused spawn (an eager resume whose credential gate failed,
70    /// `try_eager_resume`) would replay BEHIND the newer prompt that finally
71    /// spawned, reversing their delivery order (codex P2 on PR #3551).
72    /// Inserting by seq makes the replay order independent of which message
73    /// happened to seed.
74    pub fn append_in_seq_order(&mut self, entry: QueuedRetryEntry) {
75        let at = self.messages.iter().position(|m| m.seq > entry.seq).unwrap_or(self.messages.len());
76        self.messages.insert(at, entry);
77    }
78}
79
80/// One spawn attempt's resume/error-line lifecycle.
81#[derive(Debug, Clone, PartialEq)]
82pub(super) enum ResumeState {
83    /// No `--resume` attempt is in flight for the current generation —
84    /// either this spawn never attached `--resume`, or a prior attempt
85    /// already resolved (session id captured, retry fired, or exited
86    /// with an unrelated error). `current_generation` is whichever
87    /// generation this resolved FROM (or `0` if no spawn has ever
88    /// happened — see `Default` below). reagentx P1 (round 5 on PR
89    /// #2373): without this, `NotTracking` couldn't tell a legitimate
90    /// `ProcessExited` for the generation that just resolved apart from
91    /// a STALE one for an already-superseded older generation, letting
92    /// the older one incorrectly publish terminal status over a newer,
93    /// actively-running generation. See `ProcessExited`'s handling below.
94    NotTracking { current_generation: u64 },
95    /// `--resume <attempted_sid>` was attached at spawn; outcome not yet
96    /// known. `held_error_line` is `Some` once a terminal
97    /// `result`/`is_error:true` stdout line has arrived but its
98    /// persistence is still undecided. `stop_requested` records an
99    /// explicit user Stop that must override a retry even if one gets
100    /// confirmed later.
101    AwaitingOutcome {
102        generation: u64,
103        attempted_sid: String,
104        retry: RetryPayload,
105        held_error_line: Option<String>,
106        stop_requested: bool,
107    },
108    /// The stderr reader confirmed `attempted_sid` unreachable under the
109    /// current config dir — the retry WILL fire the moment the process
110    /// actually exits, unless `stop_requested` overrides it.
111    ///
112    /// reagentx P1 (round 9 on this PR, also flagged inline by codex):
113    /// `attempted_sid` is carried forward from `AwaitingOutcome` (not
114    /// dropped at promotion) so `SessionCaptured` can still tell an
115    /// ambiguous same-sid echo apart from unambiguous progress even
116    /// after confirmation — see that arm's own doc comment for why
117    /// treating EVERY capture as unambiguous once confirmed was wrong:
118    /// `resume_poisoned` (`persistent/mod.rs`) is a single, non-generation-
119    /// scoped, permanent field, so a lagging stderr-reader task from an
120    /// OLDER, already-superseded generation can overwrite it to a
121    /// different sid while THIS generation is still `ConfirmedRetry`,
122    /// silently disabling `try_capture_session_id`'s poison guard for
123    /// this generation's own attempted sid and letting a routine
124    /// same-sid echo reach this arm.
125    ConfirmedRetry {
126        generation: u64,
127        attempted_sid: String,
128        retry: RetryPayload,
129        held_error_line: Option<String>,
130        stop_requested: bool,
131    },
132}
133
134impl Default for ResumeState {
135    /// `current_generation: 0` — real generations start at 1
136    /// (`PersistentInner::spawn_generation` is bumped before its first
137    /// use), so this default can never accidentally match a genuine
138    /// `ProcessExited` event.
139    fn default() -> Self {
140        ResumeState::NotTracking { current_generation: 0 }
141    }
142}
143
144impl ResumeState {
145    /// Read-only accessor for the drain: is `delivered_seq` the exact
146    /// message `spawn_process` originally seeded the retry batch with
147    /// (its first entry), for the given `generation`? Used to identify
148    /// the already-recorded seed before appending any LATER message the
149    /// drain delivers. Matched by queue identity (`QueuedRetryEntry::seq`),
150    /// neither by position (see
151    /// `PersistentSubprocessController::drain_queue_after_successful_spawn`'s
152    /// own doc comment for why the front of the queue isn't necessarily
153    /// the seed) nor by content (issue #2365 — a later, genuinely
154    /// different delivery sharing identical text must not be mistaken
155    /// for the seed).
156    pub(super) fn is_seeded_message(&self, generation: u64, delivered_seq: u64) -> bool {
157        match self {
158            ResumeState::AwaitingOutcome { generation: g, retry, .. }
159            | ResumeState::ConfirmedRetry { generation: g, retry, .. }
160                if *g == generation =>
161            {
162                // By seq, not by position: the seed used to be identified
163                // as `messages.first()`, which stopped being true once
164                // `append_in_seq_order` (codex P2 on PR #3551) started
165                // placing an older backlog entry AHEAD of a newer seed —
166                // the drain then failed to recognise the seed and appended
167                // it a second time. "Already in the batch" is the property
168                // the drain actually needs, and it is position-free.
169                retry.messages.iter().any(|e| e.seq == delivered_seq)
170            }
171            _ => false,
172        }
173    }
174}
175
176/// Events the stdin writer / stdout reader / stderr reader / process-
177/// waiter sensor tasks report. Each carries the exact spawn `generation`
178/// it was observed for.
179#[derive(Debug, Clone)]
180pub(super) enum ResumeEvent {
181    /// A fresh spawn attached `--resume <attempted_sid>`; `generation` is
182    /// this spawn's identity for the rest of its lifetime.
183    SpawnedWithResume { generation: u64, attempted_sid: String, retry: RetryPayload },
184    /// A fresh spawn did NOT attach `--resume` (no session id held yet).
185    /// `generation` is this spawn's identity, carried so `NotTracking`
186    /// can tell a later, legitimate `ProcessExited` for THIS generation
187    /// apart from a stale one for whatever generation it superseded.
188    SpawnedFresh { generation: u64 },
189    /// A session-id-bearing stdout frame arrived for this generation.
190    /// `sid` is the id it carried; `is_confirmed_success` is true only
191    /// when THIS exact frame is a terminal `result` with `is_error:false`
192    /// — a fully-completed, genuinely successful turn.
193    ///
194    /// reagentx P0 on PR #2371: the CLI echoes back whatever `--resume`
195    /// sid it was given as its FIRST stdout line REGARDLESS of whether
196    /// that resume goes on to succeed or fail — this is true even for a
197    /// frame that isn't itself an error (e.g. a "system"/init frame), and
198    /// this first echo can arrive before the independently-scheduled
199    /// stderr reader has had a chance to report "No conversation found"
200    /// and poison it. So `sid == attempted_sid` alone is NOT proof of
201    /// genuine progress — it's ambiguous until EITHER a different sid
202    /// appears (the CLI gave up and started fresh — unambiguous) OR a
203    /// successful terminal result confirms the WHOLE turn actually
204    /// completed (also unambiguous). Only those two cases resolve
205    /// tracking; a same-sid echo on any other frame type is left
206    /// untouched, giving `ResumeUnreachable` a real chance to promote the
207    /// retry first if this turns out to be the doomed case.
208    SessionCaptured { generation: u64, sid: String, is_confirmed_success: bool },
209    /// The drain appended another message to this generation's retry
210    /// batch before it was known to be doomed (or after it was
211    /// confirmed doomed but before the process actually exited).
212    MessageAppendedToRetryBatch { generation: u64, entry: QueuedRetryEntry },
213    /// stderr reader saw "No conversation found" for this exact sid.
214    ResumeUnreachable { generation: u64, sid: String },
215    /// stdout reader saw a terminal `result`/`is_error:true` line.
216    ErrorResultLine { generation: u64, line: String },
217    /// The process actually exited.
218    ProcessExited { generation: u64 },
219    /// `stop_process` was called while this generation was live.
220    StopRequested { generation: u64 },
221}
222
223/// A resume attempt's outcome, once definitively known. See
224/// `ResumeEffect::EmitSessionOutcome`'s doc comment for how this is used.
225#[derive(Debug, Clone, PartialEq)]
226pub(super) enum SessionOutcome {
227    /// The CLI continued the exact session `--resume` was given.
228    Resumed,
229    /// The CLI could not continue that session — a new one was (or is
230    /// about to be) started. The model has none of the prior turns.
231    Fresh,
232}
233
234/// What the caller must actually DO in response to an event — kept
235/// separate from `ResumeState` so `update()` stays a pure function with
236/// no I/O, fully exercisable in a unit test.
237#[derive(Debug, Clone, PartialEq)]
238pub(super) enum ResumeEffect {
239    /// Persist `line` to the blockfile immediately — this was never a
240    /// resume-retry candidate (fresh spawn, or a generation that already
241    /// resolved), so today's behavior (persist as soon as it arrives) is
242    /// unchanged.
243    PersistImmediately(String),
244    /// No retry followed after all (never confirmed, or an explicit
245    /// Stop overrode a confirmed one) — flush the held-back line now.
246    FlushErrorLine(String),
247    /// Fire the retry with this exact payload. `held_error_line` is
248    /// bundled here rather than pre-decided (dropped) by this module:
249    /// whether the line should actually be dropped depends on whether
250    /// the retry ITSELF successfully launches, which this pure function
251    /// has no way to know (that's determined later, asynchronously, by
252    /// the caller's own spawn attempt). The caller drops it on success
253    /// and flushes it on failure — see
254    /// `persistent::PersistentSubprocessController::retry_after_resume_failure`.
255    /// `attempted_sid` is the id that was just confirmed unreachable —
256    /// carried through so the caller can emit the eventual
257    /// `EmitSessionOutcome` itself once it knows whether recovery
258    /// succeeded (PR #2693 — this module can no longer decide that here).
259    FireRetry { retry: RetryPayload, held_error_line: Option<String>, attempted_sid: String },
260    /// Genuinely done, not retrying — publish the terminal status.
261    PublishDone,
262    /// A `--resume <attempted_sid>` attempt's outcome just became
263    /// unambiguously known — surface it as a persisted transcript event
264    /// (not just a trace log line), so the pane's scrollback can never
265    /// silently disagree with what the model actually has in context.
266    /// `actual_sid` is `Some` when the CLI reported a different session id
267    /// in the same breath that resolved this generation (the
268    /// `SessionCaptured` divergence case); `None` for the `FireRetry` path,
269    /// where no fresh sid is known yet — the retry hasn't launched.
270    /// See SPEC_AGENT_PANE_HISTORY_ALIGNMENT_2026_08_05.md §2.1.
271    EmitSessionOutcome { outcome: SessionOutcome, attempted_sid: String, actual_sid: Option<String> },
272}
273
274/// Resolves a PRIOR generation's still-unresolved tracking
275/// (`AwaitingOutcome`/`ConfirmedRetry`) that a fresh spawn is about to
276/// supersede.
277///
278/// reagentx P1 (round 5 on PR #2373): `SpawnedWithResume`/`SpawnedFresh`
279/// used to reset straight into the new generation's state with NO
280/// effects at all — normally safe, since a new spawn_process call is only
281/// supposed to happen after the previous generation's own `ProcessExited`
282/// already resolved it, but reachable out of order via
283/// `persistent/queue.rs`'s `respawn_once_for_leftover_queue` (a stall-triggered
284/// fallback respawn, on a completely different path than this module's
285/// own confirmed-retry firing) racing the process-waiter task that would
286/// otherwise resolve the OLD generation first. Silently discarding a
287/// still-held error line lost a real user-facing error; the retry itself
288/// is dropped (not fired) rather than silently discarded-and-lost,
289/// because a brand-new spawn is already underway via a completely
290/// different code path — firing ANOTHER retry on top of it would
291/// double-spawn.
292fn resolve_superseded_generation(prior: ResumeState) -> Vec<ResumeEffect> {
293    match prior {
294        ResumeState::AwaitingOutcome { held_error_line, .. }
295        | ResumeState::ConfirmedRetry { held_error_line, .. } => {
296            held_error_line.map(|line| vec![ResumeEffect::FlushErrorLine(line)]).unwrap_or_default()
297        }
298        ResumeState::NotTracking { .. } => vec![],
299    }
300}
301
302/// Effects of a `SessionCaptured` that resolves tracking (a different sid, or a
303/// confirmed success): flush any held error line, then emit the session outcome.
304fn capture_resolution_effects(
305    attempted_sid: String,
306    held_error_line: Option<String>,
307    sid: String,
308    is_confirmed_success: bool,
309) -> Vec<ResumeEffect> {
310    // A `held_error_line` already stashed (an EARLIER turn on this same
311    // still-alive generation held one back, before this LATER capture resolves
312    // tracking) must be flushed, not silently discarded along with the state
313    // (#2373).
314    let mut effects: Vec<ResumeEffect> = held_error_line.map(ResumeEffect::FlushErrorLine).into_iter().collect();
315    // SPEC_AGENT_PANE_HISTORY_ALIGNMENT_2026_08_05.md §2.1: this is one of the
316    // two points where a resume attempt's fate becomes unambiguously known —
317    // surface it.
318    let outcome = if sid == attempted_sid && is_confirmed_success {
319        SessionOutcome::Resumed
320    } else {
321        SessionOutcome::Fresh
322    };
323    let actual_sid = if sid != attempted_sid { Some(sid) } else { None };
324    effects.push(ResumeEffect::EmitSessionOutcome { outcome, attempted_sid, actual_sid });
325    effects
326}
327
328type Transition = (ResumeState, Vec<ResumeEffect>);
329
330/// The pure state transition: one function per event, each deciding what that
331/// event does in every state. See the module doc comment for why this shape
332/// exists and what it replaces. An event whose generation (or sid) doesn't match
333/// what is tracked is a safe no-op unless its handler says otherwise.
334pub(super) fn update(state: ResumeState, event: ResumeEvent) -> Transition {
335    match event {
336        ResumeEvent::SpawnedWithResume { generation, attempted_sid, retry } => on_spawned_with_resume(state, generation, attempted_sid, retry),
337        ResumeEvent::SpawnedFresh { generation } => on_spawned_fresh(state, generation),
338        ResumeEvent::SessionCaptured { generation, sid, is_confirmed_success } => on_session_captured(state, generation, sid, is_confirmed_success),
339        ResumeEvent::MessageAppendedToRetryBatch { generation, entry } => on_message_appended(state, generation, entry),
340        ResumeEvent::ResumeUnreachable { generation, sid } => on_resume_unreachable(state, generation, sid),
341        ResumeEvent::ErrorResultLine { generation, line } => on_error_result_line(state, generation, line),
342        ResumeEvent::StopRequested { generation } => on_stop_requested(state, generation),
343        ResumeEvent::ProcessExited { generation } => on_process_exited(state, generation),
344    }
345}
346
347/// A fresh spawn always starts (or restarts) tracking from scratch. Normally the
348/// previous generation has already resolved (its own `ProcessExited` ran) before
349/// a new `spawn_process`, but `resolve_superseded_generation` closes the gap for
350/// the rare out-of-order case.
351fn on_spawned_with_resume(prior: ResumeState, generation: u64, attempted_sid: String, retry: RetryPayload) -> Transition {
352    let effects = resolve_superseded_generation(prior);
353    (ResumeState::AwaitingOutcome { generation, attempted_sid, retry, held_error_line: None, stop_requested: false }, effects)
354}
355
356fn on_spawned_fresh(prior: ResumeState, generation: u64) -> Transition {
357    let effects = resolve_superseded_generation(prior);
358    (ResumeState::NotTracking { current_generation: generation }, effects)
359}
360
361/// A capture resolves tracking ONLY when it is unambiguous (see
362/// `ResumeEvent::SessionCaptured`): a different sid (the CLI gave up and started
363/// fresh) or a genuinely successful terminal result (the whole turn completed).
364/// Anything else (the ambiguous early echo, a non-terminal frame) is left
365/// untouched so `ResumeUnreachable` still gets a chance to promote the retry if
366/// this turns out to be the doomed case.
367///
368/// That holds in `ConfirmedRetry` too. `resume_poisoned` (`persistent/mod.rs`) is
369/// one permanent field that is not scoped to a generation, so a lagging stderr
370/// reader from an older generation can overwrite it while this one is still
371/// `ConfirmedRetry`, which switches off `try_capture_session_id`'s poison guard.
372/// A routine same-sid echo then reaches here, and resolving on it would wipe the
373/// confirmed retry without firing it, losing every message the doomed process had
374/// accepted (#2368).
375fn on_session_captured(state: ResumeState, g: u64, sid: String, is_confirmed_success: bool) -> Transition {
376    match state {
377        ResumeState::AwaitingOutcome { generation, attempted_sid, retry, held_error_line, stop_requested } if generation == g => {
378            if sid != attempted_sid || is_confirmed_success {
379                (
380                    ResumeState::NotTracking { current_generation: generation },
381                    capture_resolution_effects(attempted_sid, held_error_line, sid, is_confirmed_success),
382                )
383            } else {
384                (ResumeState::AwaitingOutcome { generation, attempted_sid, retry, held_error_line, stop_requested }, vec![])
385            }
386        }
387        ResumeState::ConfirmedRetry { generation, attempted_sid, retry, held_error_line, stop_requested } if generation == g => {
388            if sid != attempted_sid || is_confirmed_success {
389                (
390                    ResumeState::NotTracking { current_generation: generation },
391                    capture_resolution_effects(attempted_sid, held_error_line, sid, is_confirmed_success),
392                )
393            } else {
394                (ResumeState::ConfirmedRetry { generation, attempted_sid, retry, held_error_line, stop_requested }, vec![])
395            }
396        }
397        other => (other, vec![]),
398    }
399}
400
401/// The drain can keep appending messages to the retry batch while it is merely
402/// pending, or even once confirmed (until the doomed process exits and the batch
403/// is redelivered).
404fn on_message_appended(state: ResumeState, g: u64, entry: QueuedRetryEntry) -> Transition {
405    match state {
406        ResumeState::AwaitingOutcome { generation, attempted_sid, mut retry, held_error_line, stop_requested } if generation == g => {
407            retry.append_in_seq_order(entry);
408            (ResumeState::AwaitingOutcome { generation, attempted_sid, retry, held_error_line, stop_requested }, vec![])
409        }
410        ResumeState::ConfirmedRetry { generation, attempted_sid, mut retry, held_error_line, stop_requested } if generation == g => {
411            retry.append_in_seq_order(entry);
412            (ResumeState::ConfirmedRetry { generation, attempted_sid, retry, held_error_line, stop_requested }, vec![])
413        }
414        other => (other, vec![]),
415    }
416}
417
418/// Promotion: only when the poisoned sid is the EXACT one this generation
419/// attempted. A different sid leaves the state untouched.
420fn on_resume_unreachable(state: ResumeState, g: u64, sid: String) -> Transition {
421    match state {
422        ResumeState::AwaitingOutcome { generation, attempted_sid, retry, held_error_line, stop_requested } if generation == g && attempted_sid == sid => {
423            (ResumeState::ConfirmedRetry { generation, attempted_sid, retry, held_error_line, stop_requested }, vec![])
424        }
425        other => (other, vec![]),
426    }
427}
428
429/// A terminal error-result line arriving while a resume outcome is undecided (or
430/// confirmed, but the process hasn't exited) is held back; its fate is decided
431/// when `ProcessExited` arrives. That is the crux of the module: ONE state enum
432/// makes "is this line still a retry candidate" a single question, whichever
433/// order stderr's confirmation and stdout's error line arrive in.
434///
435/// `held_error_line` holds exactly one line. A doomed resume produces at most one
436/// `is_error:true` before the retry decision, but persistent mode can accept
437/// another user message and get a SECOND error before the outcome settles. A
438/// second line is proof the first is a separate, already-settled turn's error, so
439/// the first is persisted at once instead of being overwritten.
440///
441/// A line whose generation does NOT match (a lagging reader's line arriving after
442/// a respawn moved on) must still persist: the catch-all would lose it with no
443/// effect and nothing to hold it, which a caller can't tell from a correct
444/// hold-back.
445fn on_error_result_line(state: ResumeState, g: u64, line: String) -> Transition {
446    match state {
447        ResumeState::AwaitingOutcome { generation, attempted_sid, retry, held_error_line, stop_requested } if generation == g => {
448            let effects = held_error_line.map(|old| vec![ResumeEffect::PersistImmediately(old)]).unwrap_or_default();
449            (ResumeState::AwaitingOutcome { generation, attempted_sid, retry, held_error_line: Some(line), stop_requested }, effects)
450        }
451        ResumeState::ConfirmedRetry { generation, attempted_sid, retry, held_error_line, stop_requested } if generation == g => {
452            let effects = held_error_line.map(|old| vec![ResumeEffect::PersistImmediately(old)]).unwrap_or_default();
453            (ResumeState::ConfirmedRetry { generation, attempted_sid, retry, held_error_line: Some(line), stop_requested }, effects)
454        }
455        other => (other, vec![ResumeEffect::PersistImmediately(line)]),
456    }
457}
458
459/// An explicit Stop must win over a retry even if one is confirmed later (or
460/// already was): recorded now, consulted when `ProcessExited` resolves the state.
461fn on_stop_requested(state: ResumeState, g: u64) -> Transition {
462    match state {
463        ResumeState::AwaitingOutcome { generation, attempted_sid, retry, held_error_line, .. } if generation == g => {
464            (ResumeState::AwaitingOutcome { generation, attempted_sid, retry, held_error_line, stop_requested: true }, vec![])
465        }
466        ResumeState::ConfirmedRetry { generation, attempted_sid, retry, held_error_line, .. } if generation == g => {
467            (ResumeState::ConfirmedRetry { generation, attempted_sid, retry, held_error_line, stop_requested: true }, vec![])
468        }
469        other => (other, vec![]),
470    }
471}
472
473/// Resolution: the only place a retry actually fires or a held-back line's fate
474/// is finally decided.
475///
476/// `NotTracking` is gated on `current_generation == g`: a STALE `ProcessExited`
477/// for a superseded generation (one a fresh spawn moved past before this exit
478/// arrived) would otherwise `PublishDone` (turn_active:false) over a new, running
479/// generation. A mismatched generation is a safe no-op, as for every other state.
480fn on_process_exited(state: ResumeState, g: u64) -> Transition {
481    match state {
482        // Never confirmed (auth failure, rate limit, network blip, or the process
483        // exited before stderr reported anything): done, not retrying. A held-back
484        // line is a real error the user must still see.
485        ResumeState::AwaitingOutcome { generation, held_error_line, .. } if generation == g => {
486            let mut effects = Vec::new();
487            if let Some(line) = held_error_line {
488                effects.push(ResumeEffect::FlushErrorLine(line));
489            }
490            effects.push(ResumeEffect::PublishDone);
491            (ResumeState::NotTracking { current_generation: generation }, effects)
492        }
493        ResumeState::ConfirmedRetry { generation, attempted_sid, retry, held_error_line, stop_requested } if generation == g => {
494            let effects = if stop_requested {
495                // The user's explicit Stop wins over a confirmed retry: treat it as
496                // done, not retrying, instead of reviving the agent with the same
497                // prompt right after being asked to stop.
498                let mut effects = Vec::new();
499                if let Some(line) = held_error_line {
500                    effects.push(ResumeEffect::FlushErrorLine(line));
501                }
502                effects.push(ResumeEffect::PublishDone);
503                effects
504            } else {
505                // The held line and the session outcome depend on whether the retry
506                // itself launches, which only the caller's spawn attempt knows: both
507                // are left to it (`retry_after_resume_failure`). Emitting `Fresh`
508                // here would be wrong whenever recovery finds a real on-disk
509                // session, and the frontend never clears one (#2693).
510                vec![ResumeEffect::FireRetry { retry, held_error_line, attempted_sid }]
511            };
512            (ResumeState::NotTracking { current_generation: generation }, effects)
513        }
514        ResumeState::NotTracking { current_generation } if current_generation == g => {
515            (ResumeState::NotTracking { current_generation }, vec![ResumeEffect::PublishDone])
516        }
517        other => (other, vec![]),
518    }
519}
520
521#[cfg(test)]
522#[path = "persistent_resume_transitions_tests.rs"]
523mod transition_tests;
524
525#[cfg(test)]
526mod tests {
527    use super::*;
528
529    fn dummy_config() -> PersistentSpawnConfig {
530        PersistentSpawnConfig {
531            cli_command: "definitely-not-a-real-binary-xyz".to_string(),
532            cli_args: vec![],
533            working_dir: String::new(),
534            env_vars: std::collections::HashMap::new(),
535            session_id_field: "session_id".to_string(),
536            resume_flag: "--resume".to_string(),
537            session_id: "dead-sid".to_string(),
538            message_id: None,
539        }
540    }
541
542    /// Shorthand for a retry-batch entry with an explicit queue seq
543    /// (issue #2365 — retry batches carry identity, not just text).
544    fn qentry(seq: u64, json: &str) -> QueuedRetryEntry {
545        QueuedRetryEntry { seq, json: json.to_string() }
546    }
547
548    fn dummy_retry() -> RetryPayload {
549        RetryPayload { config: dummy_config(), messages: vec![qentry(1, "{}")] }
550    }
551
552    fn spawned_with_resume(generation: u64) -> ResumeState {
553        let (state, effects) = update(
554            ResumeState::default(),
555            ResumeEvent::SpawnedWithResume {
556                generation,
557                attempted_sid: "dead-sid".to_string(),
558                retry: dummy_retry(),
559            },
560        );
561        assert!(effects.is_empty(), "spawning never produces an effect on its own");
562        state
563    }
564
565    #[test]
566    fn fresh_spawn_persists_error_lines_immediately() {
567        let (state, effects) = update(
568            ResumeState::default(),
569            ResumeEvent::ErrorResultLine { generation: 1, line: "boom".to_string() },
570        );
571        assert_eq!(state, ResumeState::default());
572        assert_eq!(effects, vec![ResumeEffect::PersistImmediately("boom".to_string())]);
573    }
574
575    #[test]
576    fn fresh_spawn_exit_just_publishes_done() {
577        let (state, effects) = update(ResumeState::default(), ResumeEvent::SpawnedFresh { generation: 1 });
578        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
579        assert!(effects.is_empty());
580
581        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
582        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
583        assert_eq!(effects, vec![ResumeEffect::PublishDone]);
584    }
585
586    #[test]
587    fn successful_session_capture_stands_down_tracking() {
588        let state = spawned_with_resume(1);
589        let (state, effects) = update(
590            state,
591            ResumeEvent::SessionCaptured {
592                generation: 1,
593                sid: "dead-sid".to_string(),
594                is_confirmed_success: true,
595            },
596        );
597        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
598        assert_eq!(
599            effects,
600            vec![ResumeEffect::EmitSessionOutcome {
601                outcome: SessionOutcome::Resumed,
602                attempted_sid: "dead-sid".to_string(),
603                actual_sid: None,
604            }]
605        );
606
607        // A later, unrelated exit on this now-resolved generation must
608        // not retry or dredge up anything.
609        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
610        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
611        assert_eq!(effects, vec![ResumeEffect::PublishDone]);
612    }
613
614    // reagentx P0 on PR #2373: the CLI echoes the attempted sid on its
615    // FIRST stdout line regardless of whether the resume goes on to
616    // succeed or fail (e.g. a "system"/init frame) — so a same-sid
617    // capture that is NOT a confirmed success must leave tracking
618    // untouched, giving `ResumeUnreachable` a real chance to promote the
619    // retry afterward if this turns out to be the doomed case.
620    #[test]
621    fn ambiguous_same_sid_echo_that_is_not_a_confirmed_success_leaves_tracking_untouched() {
622        let state = spawned_with_resume(1);
623        let (state, effects) = update(
624            state,
625            ResumeEvent::SessionCaptured {
626                generation: 1,
627                sid: "dead-sid".to_string(),
628                is_confirmed_success: false,
629            },
630        );
631        assert!(
632            matches!(&state, ResumeState::AwaitingOutcome { .. }),
633            "an unconfirmed same-sid echo must not resolve tracking"
634        );
635        assert!(effects.is_empty());
636
637        // The retry still gets a real chance to be promoted afterward.
638        let (state, _) =
639            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
640        assert!(matches!(state, ResumeState::ConfirmedRetry { .. }));
641    }
642
643    #[test]
644    fn error_line_before_poison_is_held_then_bundled_into_the_firing_retry() {
645        // Reproduces the ORIGINAL issue #2368 mechanism: the stdout
646        // reader's error line arrives before the stderr reader confirms
647        // the poison.
648        let state = spawned_with_resume(1);
649        let (state, effects) =
650            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "boom".to_string() });
651        assert!(effects.is_empty(), "held back, not persisted yet");
652        assert!(matches!(&state, ResumeState::AwaitingOutcome { held_error_line: Some(l), .. } if l == "boom"));
653
654        let (state, effects) =
655            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
656        assert!(effects.is_empty(), "promotion alone produces no effect");
657        assert!(matches!(&state, ResumeState::ConfirmedRetry { held_error_line: Some(l), .. } if l == "boom"));
658
659        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
660        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
661        assert_eq!(
662            effects,
663            vec![ResumeEffect::FireRetry {
664                retry: dummy_retry(),
665                held_error_line: Some("boom".to_string()),
666                attempted_sid: "dead-sid".to_string(),
667            }]
668        );
669    }
670
671    // reagentx P2 (round 4 on PR #2373): `held_error_line` holds exactly
672    // one line — a genuinely doomed resume produces at most one
673    // `is_error:true` before the retry decision resolves, but persistent
674    // mode can accept another user message and get a SECOND error before
675    // this generation's resume outcome is ever settled. The first line
676    // must not be silently lost to the second.
677    #[test]
678    fn a_second_error_line_supersedes_and_flushes_the_first_instead_of_losing_it() {
679        let state = spawned_with_resume(1);
680        let (state, effects) =
681            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "first turn's error".to_string() });
682        assert!(effects.is_empty(), "nothing was held yet, so nothing to supersede");
683        assert!(matches!(&state, ResumeState::AwaitingOutcome { held_error_line: Some(l), .. } if l == "first turn's error"));
684
685        let (state, effects) =
686            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "second turn's error".to_string() });
687        assert_eq!(
688            effects,
689            vec![ResumeEffect::PersistImmediately("first turn's error".to_string())],
690            "the first held line must be flushed immediately, not silently discarded"
691        );
692        assert!(
693            matches!(&state, ResumeState::AwaitingOutcome { held_error_line: Some(l), .. } if l == "second turn's error"),
694            "the newest line is what's still held, pending this generation's own retry decision"
695        );
696    }
697
698    #[test]
699    fn poison_before_error_line_still_holds_and_bundles_it_into_the_retry() {
700        // Reproduces the LIVE-REPRODUCED race (agent "Marks",
701        // 2026-07-30): stderr confirms the poison well before the
702        // stdout reader ever reaches the doomed line. A design that only
703        // checked "is a retry still pending" (not "is one already
704        // confirmed") missed this ordering — this state machine doesn't
705        // have that gap, because AwaitingOutcome and ConfirmedRetry are
706        // the SAME kind of "still tracking, line still undecided" state
707        // from ErrorResultLine's point of view.
708        let state = spawned_with_resume(1);
709        let (state, _) =
710            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
711        assert!(matches!(state, ResumeState::ConfirmedRetry { .. }));
712
713        let (state, effects) =
714            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "boom".to_string() });
715        assert!(effects.is_empty(), "still held back even though already confirmed");
716        assert!(matches!(&state, ResumeState::ConfirmedRetry { held_error_line: Some(l), .. } if l == "boom"));
717
718        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
719        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
720        assert_eq!(
721            effects,
722            vec![ResumeEffect::FireRetry {
723                retry: dummy_retry(),
724                held_error_line: Some("boom".to_string()),
725                attempted_sid: "dead-sid".to_string(),
726            }]
727        );
728    }
729
730    #[test]
731    fn unrelated_error_never_confirmed_flushes_instead_of_retrying() {
732        // An auth failure / rate limit / network blip on the very first
733        // message of a fresh --resume spawn: an error line arrives, but
734        // stderr never reports "No conversation found" for it, so no
735        // promotion ever happens. The line must still reach the user —
736        // just flushed at exit time instead of immediately.
737        let state = spawned_with_resume(1);
738        let (state, _) =
739            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "auth failed".to_string() });
740
741        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
742        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
743        assert_eq!(
744            effects,
745            vec![ResumeEffect::FlushErrorLine("auth failed".to_string()), ResumeEffect::PublishDone]
746        );
747    }
748
749    #[test]
750    fn mismatched_sid_does_not_promote() {
751        let state = spawned_with_resume(1);
752        let (state, effects) =
753            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "some-other-sid".to_string() });
754        assert!(effects.is_empty());
755        assert!(
756            matches!(state, ResumeState::AwaitingOutcome { .. }),
757            "a poison for an unrelated sid must not promote this generation's tentative retry"
758        );
759    }
760
761    #[test]
762    fn stale_generation_event_is_ignored() {
763        // Generation 1 already resolved; a late-arriving event still
764        // tagged with generation 1 must not corrupt generation 2's fresh
765        // state.
766        let state = spawned_with_resume(1);
767        let (state, _) = update(state, ResumeEvent::ProcessExited { generation: 1 });
768        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
769
770        let state = spawned_with_resume(2);
771        let (state, effects) =
772            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
773        assert!(effects.is_empty());
774        assert!(
775            matches!(state, ResumeState::AwaitingOutcome { generation: 2, .. }),
776            "a stale generation-1 event must not affect generation 2's state"
777        );
778    }
779
780    #[test]
781    fn message_appended_while_awaiting_outcome_grows_the_batch() {
782        let state = spawned_with_resume(1);
783        let (state, effects) =
784            update(state, ResumeEvent::MessageAppendedToRetryBatch { generation: 1, entry: qentry(2, "{\"m\":2}") });
785        assert!(effects.is_empty());
786        match state {
787            ResumeState::AwaitingOutcome { retry, .. } => {
788                assert_eq!(retry.messages, vec![qentry(1, "{}"), qentry(2, "{\"m\":2}")])
789            }
790            other => panic!("expected AwaitingOutcome, got {other:?}"),
791        }
792    }
793
794    /// Codex P2 on PR #3551: a backlog retained across a refused spawn has
795    /// OLDER seqs than the prompt that eventually seeds the next spawn, but
796    /// reaches the batch AFTER it (the seed is first, the drain appends the
797    /// rest). Replay must follow seq — acceptance — order, not arrival.
798    #[test]
799    fn a_backlog_appended_behind_a_newer_seed_replays_in_acceptance_order() {
800        let (state, _) = update(
801            ResumeState::default(),
802            ResumeEvent::SpawnedWithResume {
803                generation: 1,
804                attempted_sid: "dead-sid".to_string(),
805                retry: RetryPayload { config: dummy_config(), messages: vec![qentry(3, "{\"m\":3}")] },
806            },
807        );
808        let (state, _) =
809            update(state, ResumeEvent::MessageAppendedToRetryBatch { generation: 1, entry: qentry(1, "{\"m\":1}") });
810        let (state, _) =
811            update(state, ResumeEvent::MessageAppendedToRetryBatch { generation: 1, entry: qentry(2, "{\"m\":2}") });
812        match state {
813            ResumeState::AwaitingOutcome { retry, .. } => assert_eq!(
814                retry.messages,
815                vec![qentry(1, "{\"m\":1}"), qentry(2, "{\"m\":2}"), qentry(3, "{\"m\":3}")],
816                "older backlog entries must replay ahead of the newer seed"
817            ),
818            other => panic!("expected AwaitingOutcome, got {other:?}"),
819        }
820    }
821
822    #[test]
823    fn message_appended_after_confirmed_still_grows_the_batch() {
824        // Matches persistent/tests/send_input.rs's existing
825        // `drain_appends_to_confirmed_retry_once_already_promoted_from_pending`
826        // — the drain can still be delivering messages after the retry
827        // is confirmed but before the doomed process has actually
828        // exited.
829        let state = spawned_with_resume(1);
830        let (state, _) =
831            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
832        let (state, effects) =
833            update(state, ResumeEvent::MessageAppendedToRetryBatch { generation: 1, entry: qentry(2, "{\"m\":2}") });
834        assert!(effects.is_empty());
835        match state {
836            ResumeState::ConfirmedRetry { retry, .. } => {
837                assert_eq!(retry.messages, vec![qentry(1, "{}"), qentry(2, "{\"m\":2}")])
838            }
839            other => panic!("expected ConfirmedRetry, got {other:?}"),
840        }
841    }
842
843    #[test]
844    fn stop_requested_before_confirmation_overrides_a_later_confirmed_retry() {
845        let state = spawned_with_resume(1);
846        let (state, _) = update(state, ResumeEvent::StopRequested { generation: 1 });
847        let (state, _) =
848            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
849        assert!(matches!(state, ResumeState::ConfirmedRetry { stop_requested: true, .. }));
850
851        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
852        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
853        assert_eq!(
854            effects,
855            vec![ResumeEffect::PublishDone],
856            "an explicit stop must win over a confirmed retry, not silently revive the agent"
857        );
858    }
859
860    #[test]
861    fn stop_requested_after_confirmation_still_overrides_the_retry() {
862        let state = spawned_with_resume(1);
863        let (state, _) =
864            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
865        let (state, _) = update(state, ResumeEvent::StopRequested { generation: 1 });
866        assert!(matches!(state, ResumeState::ConfirmedRetry { stop_requested: true, .. }));
867
868        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
869        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
870        assert_eq!(effects, vec![ResumeEffect::PublishDone]);
871    }
872
873    #[test]
874    fn stop_requested_with_a_held_error_line_still_flushes_it() {
875        // A stop overriding a confirmed retry still owes the user
876        // whatever error was actually observed, same as the
877        // never-confirmed case.
878        let state = spawned_with_resume(1);
879        let (state, _) =
880            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "boom".to_string() });
881        let (state, _) =
882            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
883        let (state, _) = update(state, ResumeEvent::StopRequested { generation: 1 });
884
885        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
886        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
887        assert_eq!(
888            effects,
889            vec![ResumeEffect::FlushErrorLine("boom".to_string()), ResumeEffect::PublishDone]
890        );
891    }
892
893    // reagentx P2 on PR #2373: a `held_error_line` stashed by an EARLIER
894    // turn on this same still-alive generation must be flushed, not
895    // silently discarded, when a LATER turn's session-id capture
896    // resolves tracking before ProcessExited ever arrives.
897    #[test]
898    fn session_captured_flushes_a_held_error_line_from_an_earlier_turn() {
899        let state = spawned_with_resume(1);
900        let (state, _) =
901            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "boom".to_string() });
902        assert!(matches!(&state, ResumeState::AwaitingOutcome { held_error_line: Some(_), .. }));
903
904        let (state, effects) = update(
905            state,
906            ResumeEvent::SessionCaptured { generation: 1, sid: "dead-sid".to_string(), is_confirmed_success: true },
907        );
908        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
909        assert_eq!(
910            effects,
911            vec![
912                ResumeEffect::FlushErrorLine("boom".to_string()),
913                ResumeEffect::EmitSessionOutcome {
914                    outcome: SessionOutcome::Resumed,
915                    attempted_sid: "dead-sid".to_string(),
916                    actual_sid: None,
917                },
918            ],
919            "the held error must reach the user, not vanish along with the resolved tracking"
920        );
921    }
922
923    // Same as above, but the retry was ALREADY confirmed (defensive path
924    // — a genuine capture shouldn't happen for a poisoned sid in
925    // practice, but must not silently lose a held line if it somehow
926    // does).
927    #[test]
928    fn session_captured_flushes_a_held_error_line_even_after_confirmation() {
929        let state = spawned_with_resume(1);
930        let (state, _) =
931            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "boom".to_string() });
932        let (state, _) =
933            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
934        assert!(matches!(&state, ResumeState::ConfirmedRetry { held_error_line: Some(_), .. }));
935
936        // An unambiguous capture (a genuinely different sid, or a
937        // confirmed terminal success) still resolves tracking and
938        // flushes the held line even after confirmation.
939        let (state, effects) = update(
940            state,
941            ResumeEvent::SessionCaptured { generation: 1, sid: "dead-sid".to_string(), is_confirmed_success: true },
942        );
943        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
944        assert_eq!(
945            effects,
946            vec![
947                ResumeEffect::FlushErrorLine("boom".to_string()),
948                ResumeEffect::EmitSessionOutcome {
949                    outcome: SessionOutcome::Resumed,
950                    attempted_sid: "dead-sid".to_string(),
951                    actual_sid: None,
952                },
953            ]
954        );
955    }
956
957    // reagentx P1 (round 9 on this PR, also flagged inline by codex): the
958    // `ConfirmedRetry` + `SessionCaptured` arm used to resolve
959    // UNCONDITIONALLY, discarding the confirmed `retry` payload without
960    // ever firing it. `resume_poisoned` (persistent/mod.rs) is a single,
961    // non-generation-scoped, PERMANENT field — a lagging stderr-reader
962    // task from an OLDER, already-superseded generation can overwrite it
963    // to a different sid while THIS generation is still `ConfirmedRetry`,
964    // silently disabling `try_capture_session_id`'s poison guard for
965    // this generation's own attempted sid and letting a routine same-sid
966    // echo (ambiguous, not a confirmed success) reach this arm. That
967    // must NOT wipe out the confirmed retry — same unambiguity check as
968    // the `AwaitingOutcome` arm.
969    #[test]
970    fn ambiguous_same_sid_echo_after_confirmation_does_not_discard_the_confirmed_retry() {
971        let state = spawned_with_resume(1);
972        let (state, _) =
973            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
974        assert!(matches!(&state, ResumeState::ConfirmedRetry { attempted_sid, .. } if attempted_sid == "dead-sid"));
975
976        // The same attempted sid, echoed on a non-terminal frame — the
977        // exact ambiguous case the poison guard normally screens out,
978        // reachable here only because a stale, unrelated poison
979        // overwrote `resume_poisoned` first.
980        let (state, effects) = update(
981            state,
982            ResumeEvent::SessionCaptured { generation: 1, sid: "dead-sid".to_string(), is_confirmed_success: false },
983        );
984        assert!(effects.is_empty(), "an ambiguous echo must not flush or fire anything");
985        match &state {
986            ResumeState::ConfirmedRetry { retry, .. } => {
987                assert_eq!(retry.messages, vec![qentry(1, "{}")], "the confirmed retry must survive intact")
988            }
989            other => panic!("expected the confirmed retry to survive an ambiguous echo, got {other:?}"),
990        }
991
992        // The retry still fires normally once the process actually exits.
993        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
994        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
995        assert_eq!(
996            effects,
997            vec![ResumeEffect::FireRetry {
998                retry: dummy_retry(),
999                held_error_line: None,
1000                attempted_sid: "dead-sid".to_string(),
1001            }]
1002        );
1003    }
1004
1005    // reagentx P2 on PR #2373: an ErrorResultLine whose generation
1006    // doesn't match what's currently tracked (a stale/lagging reader's
1007    // line arriving after a respawn already moved on) must still persist
1008    // — a caller checking "were there any effects" to decide hold-back
1009    // vs. not can't otherwise distinguish this from a genuine,
1010    // correctly-tracked hold-back, silently losing the line.
1011    #[test]
1012    fn mismatched_generation_error_line_persists_instead_of_vanishing() {
1013        let state = spawned_with_resume(2);
1014        let (state, effects) =
1015            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "orphaned".to_string() });
1016        assert_eq!(
1017            effects,
1018            vec![ResumeEffect::PersistImmediately("orphaned".to_string())],
1019            "a line tagged with a generation that no longer matches must still reach the user"
1020        );
1021        // The mismatched event must not disturb generation 2's own state.
1022        assert!(matches!(state, ResumeState::AwaitingOutcome { generation: 2, held_error_line: None, .. }));
1023    }
1024
1025    #[test]
1026    fn spawned_fresh_with_no_resume_never_tracks_anything() {
1027        let (state, effects) = update(ResumeState::default(), ResumeEvent::SpawnedFresh { generation: 1 });
1028        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
1029        assert!(effects.is_empty());
1030
1031        let (state, effects) =
1032            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "boom".to_string() });
1033        assert_eq!(effects, vec![ResumeEffect::PersistImmediately("boom".to_string())]);
1034        let (_, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
1035        assert_eq!(effects, vec![ResumeEffect::PublishDone]);
1036    }
1037
1038    // reagentx P1 (round 5 on this PR): the exact race reagentx flagged —
1039    // a fresh (or resumed) respawn firing via `SpawnedFresh`/
1040    // `SpawnedWithResume` while a PRIOR generation is still
1041    // `AwaitingOutcome`/`ConfirmedRetry` (its own `ProcessExited` hasn't
1042    // arrived yet — reachable via `persistent/queue.rs`'s
1043    // `respawn_once_for_leftover_queue` racing the process-waiter task).
1044    // The prior generation's held error line must reach the user instead
1045    // of vanishing, and its own eventual (belated) `ProcessExited` must
1046    // NOT corrupt the new generation's status.
1047    #[test]
1048    fn a_fresh_spawn_superseding_an_unresolved_generation_flushes_its_held_error_and_ignores_its_stale_exit() {
1049        let state = spawned_with_resume(1);
1050        let (state, _) =
1051            update(state, ResumeEvent::ErrorResultLine { generation: 1, line: "generation 1's error".to_string() });
1052        assert!(matches!(&state, ResumeState::AwaitingOutcome { generation: 1, held_error_line: Some(_), .. }));
1053
1054        // A brand-new spawn (generation 2) supersedes generation 1 before
1055        // generation 1's own ProcessExited ever arrived.
1056        let (state, effects) = update(state, ResumeEvent::SpawnedFresh { generation: 2 });
1057        assert_eq!(
1058            effects,
1059            vec![ResumeEffect::FlushErrorLine("generation 1's error".to_string())],
1060            "generation 1's held error must reach the user, not vanish when generation 2 supersedes it"
1061        );
1062        assert_eq!(state, ResumeState::NotTracking { current_generation: 2 });
1063
1064        // Generation 1's own (belated) ProcessExited must be a safe
1065        // no-op now — NOT another PublishDone stomping generation 2.
1066        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
1067        assert!(
1068            effects.is_empty(),
1069            "a stale ProcessExited for a superseded generation must not publish done over the new one"
1070        );
1071        assert_eq!(state, ResumeState::NotTracking { current_generation: 2 });
1072
1073        // Generation 2's OWN eventual exit must still work normally.
1074        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 2 });
1075        assert_eq!(state, ResumeState::NotTracking { current_generation: 2 });
1076        assert_eq!(effects, vec![ResumeEffect::PublishDone]);
1077    }
1078
1079    // Same race, but the prior generation had already been CONFIRMED
1080    // stale (poison_resume won) before the fresh respawn superseded it —
1081    // its own queued retry must be dropped (not fired), not silently
1082    // discarded, since a brand-new spawn is already underway via a
1083    // completely different path.
1084    #[test]
1085    fn a_fresh_spawn_superseding_a_confirmed_retry_drops_it_without_double_spawning() {
1086        let state = spawned_with_resume(1);
1087        let (state, _) =
1088            update(state, ResumeEvent::ResumeUnreachable { generation: 1, sid: "dead-sid".to_string() });
1089        assert!(matches!(state, ResumeState::ConfirmedRetry { generation: 1, .. }));
1090
1091        let (state, effects) = update(state, ResumeEvent::SpawnedFresh { generation: 2 });
1092        assert!(
1093            effects.is_empty(),
1094            "no held error line existed, so superseding a confirmed (but line-less) retry produces no effect"
1095        );
1096        assert_eq!(state, ResumeState::NotTracking { current_generation: 2 });
1097
1098        let (state, effects) = update(state, ResumeEvent::ProcessExited { generation: 1 });
1099        assert!(effects.is_empty(), "generation 1's stale exit must not fire its now-superseded retry");
1100        assert_eq!(state, ResumeState::NotTracking { current_generation: 2 });
1101    }
1102
1103    // SPEC_AGENT_PANE_HISTORY_ALIGNMENT_2026_08_05.md §2.1: the CLI itself
1104    // can silently roll to a DIFFERENT session id (rather than failing
1105    // outright) before `ResumeUnreachable` ever gets a chance to fire — the
1106    // `sid != attempted_sid` branch of the unambiguity check. This must
1107    // still be reported as Fresh, with `actual_sid` carrying the id the CLI
1108    // actually landed on.
1109    #[test]
1110    fn session_captured_with_a_different_sid_emits_fresh_outcome_with_actual_sid() {
1111        let state = spawned_with_resume(1);
1112        let (state, effects) = update(
1113            state,
1114            ResumeEvent::SessionCaptured {
1115                generation: 1,
1116                sid: "brand-new-sid".to_string(),
1117                is_confirmed_success: false,
1118            },
1119        );
1120        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
1121        assert_eq!(
1122            effects,
1123            vec![ResumeEffect::EmitSessionOutcome {
1124                outcome: SessionOutcome::Fresh,
1125                attempted_sid: "dead-sid".to_string(),
1126                actual_sid: Some("brand-new-sid".to_string()),
1127            }]
1128        );
1129    }
1130
1131    // Regression guard for SPEC_AGENT_PANE_HISTORY_ALIGNMENT_2026_08_05.md
1132    // §2.1's "deliberately not touched" call: a fresh spawn with no resume
1133    // attempt at all (no session existed yet — nothing to lose), and a
1134    // resume attempt that's never confirmed either way (auth failure etc.,
1135    // §2.1's `unrelated_error_never_confirmed_flushes_instead_of_retrying`
1136    // case), must NOT emit a session-outcome event — there's no positively-
1137    // known outcome to report in either case.
1138    #[test]
1139    fn spawned_fresh_and_never_confirmed_paths_never_emit_a_session_outcome() {
1140        let (state, effects) = update(ResumeState::default(), ResumeEvent::SpawnedFresh { generation: 1 });
1141        assert!(!effects.iter().any(|e| matches!(e, ResumeEffect::EmitSessionOutcome { .. })));
1142
1143        let state2 = spawned_with_resume(2);
1144        let (state2, _) =
1145            update(state2, ResumeEvent::ErrorResultLine { generation: 2, line: "auth failed".to_string() });
1146        let (_, effects) = update(state2, ResumeEvent::ProcessExited { generation: 2 });
1147        assert!(
1148            !effects.iter().any(|e| matches!(e, ResumeEffect::EmitSessionOutcome { .. })),
1149            "a never-confirmed resume attempt has no positively-known outcome to report"
1150        );
1151
1152        // Keep `state` (generation 1) used so the compiler doesn't flag it —
1153        // its only purpose above is exercising the SpawnedFresh path.
1154        assert_eq!(state, ResumeState::NotTracking { current_generation: 1 });
1155    }
1156}