Skip to main content

agentmux_srv_core/backend/blockcontroller/persistent/
resume_retry.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Stale-`--resume` recovery: executing the effects `persistent_resume` decides,
5//! locating a recoverable session id, and the retry-batch rewrite.
6
7use super::*;
8
9impl PersistentSubprocessController {
10    /// Appends a terminal error-result line to this block's output now and
11    /// surfaces its classified failure: a held-back line confirmed final
12    /// outside the process-waiter task (its retry failed to launch, or its
13    /// generation was superseded), or an error frame synthesized for
14    /// prompts that could not be delivered. See
15    /// `retry_after_resume_failure`'s doc comment for when a held line is
16    /// flushed rather than dropped.
17    pub(super) fn flush_error_line_now(&self, line: String) {
18        let Some(ref broker) = self.broker else { return };
19        let global_output_zone = crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
20        super::super::shell::handle_append_block_file(
21            broker,
22            &self.block_id,
23            PERSISTENT_OUTPUT_SUBJECT,
24            line.as_bytes(),
25            self.filestore.as_ref(),
26            global_output_zone.as_deref(),
27        );
28        // Same gap reagentx flagged (PR #2421 P2) at the other FlushErrorLine
29        // call sites: this is also a previously held-back turn's error only
30        // now confirmed final (a fresh spawn superseding a still-tracking
31        // generation, or a retry batch exhausted with nothing left to
32        // deliver) — give it the same classify/persist/publish treatment so
33        // it isn't silently dropped from the pane's failure-recovery UI. No
34        // exit code exists for this now-superseded turn.
35        surface_error_line(&self.block_id, None, &line, Some(broker.as_ref()), &self.mstore, &self.event_bus);
36    }
37
38    /// A `Fresh` outcome whose new session will carry AgentMux's record of
39    /// the conversation, so the pane says "continued" rather than "new".
40    pub(super) fn emit_fresh_outcome_now(&self, attempted_sid: String, continued: bool, idle_start: bool) {
41        self.emit_session_outcome_now_with(
42            persistent_resume::SessionOutcome::Fresh,
43            attempted_sid,
44            None,
45            continued,
46            idle_start,
47        );
48    }
49
50    /// Whether a fresh spawn right now would carry a continuation packet
51    /// (what `spawn` gives any no-`--resume` spawn onto prior history).
52    /// Reads the transcript tail: call it on rare paths, never under `inner`.
53    pub(super) fn fresh_spawn_would_continue(&self) -> bool {
54        self.has_prior_transcript() && self.continuation_packet().is_some()
55    }
56
57    fn emit_session_outcome_now_with(
58        &self,
59        outcome: persistent_resume::SessionOutcome,
60        attempted_sid: String,
61        actual_sid: Option<String>,
62        continued: bool,
63        idle_start: bool,
64    ) {
65        let Some(ref broker) = self.broker else { return };
66        let line = session_outcome_line_with(outcome, attempted_sid, actual_sid, continued, idle_start);
67        let global_output_zone = crate::backend::transcript::append::resolve_global_output_zone(&self.mstore, &self.block_id);
68        super::super::shell::handle_append_block_file(
69            broker,
70            &self.block_id,
71            PERSISTENT_OUTPUT_SUBJECT,
72            line.as_bytes(),
73            self.filestore.as_ref(),
74            global_output_zone.as_deref(),
75        );
76    }
77
78    /// Does a transcript already exist for this pane — either in this
79    /// channel's own blockfile, or in the agent's GLOBAL transcript zone?
80    ///
81    /// The second half is the one that matters for
82    /// [`fresh_start_needs_disclosure`]: on a cross-channel or cross-version
83    /// open this channel's blockfile is empty, but the pane still renders the
84    /// full prior conversation through `app_api::global_output_source`'s read
85    /// fallback. Mirrors that function's checks (agent-anchored, not archived,
86    /// non-empty `output`) so "the pane will show history" and "we disclose a
87    /// fresh start" can't disagree.
88    ///
89    /// Two `stat` calls at most, on the spawn path only — cheap enough to run
90    /// unconditionally behind the caller's own generation gate.
91    pub(super) fn has_prior_transcript(&self) -> bool {
92        if let Some(ref fs) = self.filestore {
93            if matches!(fs.stat(&self.block_id, PERSISTENT_OUTPUT_SUBJECT), Ok(Some(ref f)) if f.size > 0)
94            {
95                return true;
96            }
97        }
98        let Some(zone) = global_prior_zone(self.mstore.as_deref(), &self.block_id) else {
99            return false;
100        };
101        // A zone found corrupt has no prior transcript to offer; the pane's own was asked above.
102        let Some(gfs) = crate::backend::transcript::damage::global_for(&zone) else {
103            return false;
104        };
105        global_zone_has_output(&gfs, &zone)
106    }
107
108    /// The session to continue on a first spawn that holds no id of its own
109    /// (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md §5 P0a): the session
110    /// of the history this pane renders ([`pane_history_session_id`]), when
111    /// `--resume` would find it under this spawn's config dir and it isn't
112    /// already poisoned.
113    pub(super) fn find_continuation_session_id(&self, config: &PersistentSpawnConfig) -> Option<String> {
114        if config.resume_flag.is_empty() {
115            return None;
116        }
117        let config_dir = config.env_vars.get("CLAUDE_CONFIG_DIR")?;
118        let sid = pane_history_session_id(
119            self.filestore.as_deref(),
120            self.mstore.as_deref(),
121            &self.block_id,
122            &config.session_id_field,
123        )?;
124        if self.inner.lock().unwrap().resume_poisoned.as_deref() == Some(sid.as_str()) {
125            return None;
126        }
127        crate::backend::session_backfill::session_is_reachable(config_dir, &config.working_dir, &sid)
128            .then_some(sid)
129    }
130
131    /// The parent session this pane's agent was forked from, when its history
132    /// is a copy of the parent's (`agent_session::fork_history`). A spawn that
133    /// resumes it forks it: a fork never writes into its parent's conversation.
134    pub(super) fn inherited_fork_session(&self) -> Option<String> {
135        let zone = global_prior_zone(self.mstore.as_deref(), &self.block_id)?;
136        let gfs = crate::backend::transcript::damage::global_for(&zone)?;
137        crate::backend::agent_session::fork_history::inherited_session(&gfs, &zone)
138    }
139
140    /// AgentMux's record of the conversation this pane renders, as a
141    /// continuation packet for a process that starts without it
142    /// (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md §4.4).
143    pub(super) fn continuation_packet(&self) -> Option<String> {
144        let zone = global_prior_zone(self.mstore.as_deref(), &self.block_id);
145        // A zone found corrupt is left out: the packet is built from the pane's own transcript.
146        let gfs = zone.as_deref().and_then(crate::backend::transcript::damage::global_for);
147        let global = zone.as_deref().zip(gfs.as_deref()).map(|(z, g)| (g, z));
148        let (tail, starts_mid_line) = packet_history_tail(
149            self.filestore.as_deref(),
150            &self.block_id,
151            global,
152            crate::backend::continuity::PACKET_TAIL_BYTES,
153        )?;
154        // The agent's running summary, kept beside its global transcript
155        // (`continuity_state.rs`). Missing for panes that aren't anchored to
156        // an agent, or until the first update has run.
157        let state = global.and_then(|(g, z)| crate::backend::continuity_state::latest_state(g, z));
158        // What AgentMux itself knows right now, written without a model: the packet
159        // is right about "in flight" even when the summary is old or was never made.
160        let now_ms = agentmux_common::time::now_ms();
161        let facts_text = self.mstore.as_deref().map(|mstore| {
162            // The claimed tasks are on the work store: the identity store, unless the build has its own.
163            let work_store = crate::backend::work_store_handle::get().or_else(|| self.identity_store.clone());
164            let facts = crate::backend::continuity_facts::collect(mstore, work_store.as_deref(), &self.block_id);
165            crate::backend::continuity_facts::render(&facts, now_ms)
166        });
167        crate::backend::continuity::build_continuation_packet(
168            &tail,
169            starts_mid_line,
170            state.as_ref().map(|s| crate::backend::continuity::RunningState {
171                text: &s.text,
172                created_at_ms: s.created_at_ms,
173            }),
174            facts_text
175                .as_deref()
176                .map(|text| crate::backend::continuity::RuntimeFacts { text, at_ms: now_ms }),
177        )
178    }
179
180    /// The continuation packet a fresh spawn onto prior history carries, or
181    /// `None` when there is no record to give it.
182    ///
183    /// Carrying one also retracts the "Couldn't resume the previous
184    /// conversation — started a new one" banner a rejected `--resume` raised
185    /// on the previous generation: the conversation wasn't lost, this session
186    /// continues it from AgentMux's record. Same reasoning as the `Resumed`
187    /// retract in the stdout reader — the banner must not contradict the
188    /// "continued" outcome the pane shows.
189    pub(super) fn carry_continuation(&self) -> Option<String> {
190        let packet = self.continuation_packet()?;
191        tracing::info!(
192            block_id = %self.block_id,
193            packet_chars = packet.len(),
194            "continuity: carrying AgentMux's record of the conversation into the fresh session"
195        );
196        if let Some(ref store) = self.mstore {
197            super::super::session_recovery::clear_resume_failed(store, &self.event_bus, &self.block_id);
198        }
199        Some(packet)
200    }
201
202    /// The handoff the agent left before a user action restarted its session
203    /// (`continuity_handoff.rs`), read once by the spawn that starts the new one: the first section
204    /// of `packet` when AgentMux's record rides on the first message, else a note held for it (the
205    /// session resumed, so the record is already there). `packet` is returned unchanged when none waits.
206    pub(super) fn carry_prep_handoff(&self, packet: Option<String>) -> Option<String> {
207        let def_id = self
208            .mstore
209            .as_deref()
210            .and_then(|m| m.get::<crate::backend::obj::Block>(&self.block_id).ok().flatten())
211            .map(|b| crate::backend::obj::meta_get_string(&b.meta, "agentId", ""))
212            .filter(|id| !id.is_empty());
213        let Some(handoff) = def_id.and_then(|id| crate::backend::continuity_handoff::take(&id)) else { return packet };
214        tracing::info!(block_id = %self.block_id, in_packet = packet.is_some(), "continuity: carrying the handoff the agent left before the change");
215        match packet {
216            Some(p) => Some(crate::backend::continuity::with_handoff_first(&p, &handoff.packet_section())),
217            None => {
218                crate::backend::reactive::held_notes::hold(&self.block_id, crate::backend::continuity_handoff::NOTE_KEY, &handoff.note());
219                None
220            }
221        }
222    }
223
224    /// After a confirmed-stale `--resume` failure, try to recover a REAL
225    /// session instead of giving up and starting blank
226    /// (`docs/status/STATUS_CROSS_CHANNEL_RESUME_STALE_SESSION_ID_2026_08_20.md`).
227    /// Looks for the largest on-disk session under this spawn's own
228    /// `CLAUDE_CONFIG_DIR`/working dir — the same "largest session wins"
229    /// recovery `session_backfill::backfill_session_ids` already trusts
230    /// for the analogous cross-channel-open case.
231    ///
232    /// Returns `None` (caller falls back to starting blank, same as
233    /// before this existed) when: `CLAUDE_CONFIG_DIR` isn't set on this
234    /// config, no session exists there, or the only candidate found is
235    /// the SAME id already confirmed poisoned — guards against looping
236    /// forever "recovering" an id that is itself dead (nothing on disk
237    /// changes between attempts, so an unguarded retry would rediscover
238    /// the identical bad id every time).
239    pub(super) fn find_recovery_session_id(&self, config: &PersistentSpawnConfig) -> Option<String> {
240        let config_dir = config.env_vars.get("CLAUDE_CONFIG_DIR")?;
241        let candidate = crate::backend::session_backfill::find_largest_session_for_working_dir(
242            config_dir,
243            &config.working_dir,
244        )?;
245        let already_poisoned = self.inner.lock().unwrap().resume_poisoned.as_deref() == Some(candidate.as_str());
246        if already_poisoned {
247            return None;
248        }
249        // The largest session under this config dir and cwd is only this
250        // conversation if it's the head of the agent's segment chain
251        // (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md §4.2). Otherwise
252        // (after an account switch, typically) it's older history. Returning
253        // `None` makes the retry a fresh session, which now carries the
254        // continuation packet.
255        if let (Some(uid), Some(gfs)) = (self.stable_agent_uid(), crate::backend::agent_session::global_transcript_store()) {
256            let chain = crate::backend::continuity_segments::segments(gfs, &uid);
257            let current = self.current_segment.lock().unwrap().clone();
258            let head = crate::backend::continuity_segments::head_session(&chain, current.as_deref());
259            if !crate::backend::continuity_segments::recovery_allowed(&candidate, head.as_deref()) {
260                tracing::info!(
261                    block_id = %self.block_id,
262                    candidate = %candidate,
263                    head = ?head,
264                    "continuity: not recovering a session that isn't the head of the agent's chain"
265                );
266                return None;
267            }
268        }
269        Some(candidate)
270    }
271
272    /// Retries the message that triggered a `--resume <sid>` attempt this
273    /// controller's own stderr reader just confirmed is unreachable ("No
274    /// conversation found with session ID" — see `poison_resume`). Called
275    /// from the process-waiter task once the doomed process has actually
276    /// exited, via the weak self-reference (mirrors `SubprocessController`'s
277    /// queued-message drain — see `set_self_ref`), and ONLY for a
278    /// `persistent_resume::ResumeEffect::FireRetry` (a `ConfirmedRetry`
279    /// generation's exit) — never for an unrelated exit.
280    ///
281    /// Respawns with the stale `session_id` replaced: by a recovered
282    /// on-disk session if `find_recovery_session_id` finds one, otherwise
283    /// cleared so no `--resume` is attempted. Redelivers EVERY message the
284    /// doomed process's stdin channel had accepted (the drain appends each
285    /// later delivery to the batch —
286    /// `persistent_resume::ResumeEvent::MessageAppendedToRetryBatch` — so
287    /// this is a batch, not just the one that triggered the spawn) — does
288    /// NOT re-persist to the blockfile or re-emit `agent-message-accepted`
289    /// for any of them, since both already happened correctly on each
290    /// message's original (failed) attempt; only the underlying CLI
291    /// process needed a fresh start.
292    ///
293    /// This is itself a spawn attempt, and must not race a genuinely
294    /// concurrent `send_message` call the same way the ORIGINAL doomed
295    /// spawn could — see `PersistentInner::spawning_in_progress`'s doc
296    /// comment. By the time this runs, the original `send_message` call
297    /// that triggered the doomed process has long since returned (its own
298    /// spawn-claim-and-deliver sequence completed synchronously, well
299    /// before this process even exited), so the WHOLE batch can safely go
300    /// through `decide_retry_batch_action` — the SAME decision
301    /// `send_message` uses, but enqueueing everything atomically in one
302    /// lock acquisition (see its own doc comment for why per-message
303    /// decisions aren't safe for a batch).
304    ///
305    /// A held-back error line must reach the user if a confirmed retry
306    /// turns out NOT to actually launch (#2371) — otherwise an
307    /// already-accepted prompt ends in total silence: neither the original
308    /// error nor a replacement one. It is flushed only when a
309    /// `BecomeSpawner` respawn fails; the `FlushClaimed` and `Queued` arms
310    /// hand off to a background drain whose own `stalled_with_leftovers`
311    /// branch already publishes a status update on genuine total failure,
312    /// so those arms drop the line instead — see the `Queued` arm below
313    /// for why flushing eagerly there would reproduce the very bubble
314    /// #2371 removed.
315    ///
316    /// `retry_generation` is the spawn generation whose `ProcessExited`
317    /// fired this retry (the process-waiter's own `my_generation_wait`) —
318    /// `decide_retry_batch_action` needs it to tell a live NEWER spawn
319    /// apart from the impossible "our own process is somehow still
320    /// running" case (issue #2367). `attempted_sid` is the id that was
321    /// just confirmed unreachable — threaded through from
322    /// `persistent_resume::ResumeEffect::FireRetry` so this function can
323    /// emit the eventual `EmitSessionOutcome` itself once recovery is
324    /// known (reagentx + Codex on PR #2693 — `persistent_resume.rs` can
325    /// no longer decide Fresh-vs-Resumed at the point it fires this
326    /// retry, since recovery might succeed).
327    pub(super) fn retry_after_resume_failure(
328        &self,
329        retry_generation: u64,
330        mut config: PersistentSpawnConfig,
331        mut entries: Vec<persistent_resume::QueuedRetryEntry>,
332        held_error_line: Option<String>,
333        attempted_sid: String,
334    ) {
335        // An empty batch is not a retry at all — see
336        // `settle_empty_resume_retry`. Decided BEFORE the "retrying" publish
337        // and the recovery search below (codex P1, second round on PR
338        // #3551): both are user-visible side effects, and for a superseded
339        // generation they must not happen either.
340        if entries.is_empty() {
341            self.settle_empty_resume_retry(retry_generation, config, held_error_line, attempted_sid);
342            return;
343        }
344        // "Reconnecting…" starts here regardless of which branch below is
345        // taken — the user-visible gap begins the moment a retry is known
346        // to be needed, not once recovery search finishes. See §6.2.
347        publish_resume_retry_status(&self.broker, &self.block_id, "retrying");
348        let recovered = self.find_recovery_session_id(&config);
349        config.session_id = recovered.clone().unwrap_or_default();
350        match &recovered {
351            // A real on-disk session was found — don't claim "Resumed"
352            // yet (codex P1 on PR #2693: the CLI can still reject this
353            // recovered id too, e.g. a corrupt file or a non-top-level
354            // session). Left unemitted here on purpose: the spawn below
355            // now threads this attempt through the SAME resume-tracking
356            // machinery a genuine first-time `--resume` uses (`Some(first
357            // .clone())`, not `None`), so `persistent_resume.rs`'s
358            // already-correct, already-tested `SessionCaptured` handling
359            // emits `Resumed` once the CLI actually confirms it — or, if
360            // this recovered id is ALSO stale, cascades into another
361            // `ConfirmedRetry` → this same function again, where
362            // `find_recovery_session_id`'s poison guard refuses to
363            // re-recover the identical dead id and this arm's `None`
364            // branch below correctly emits `Fresh` instead. "Reconnecting…"
365            // is deliberately NOT resolved here — the eventual
366            // `EmitSessionOutcome` handling (stdout-reader / process-exit
367            // match arms) is what clears it, once the CLI actually confirms
368            // this recovered id one way or the other.
369            Some(_) => {}
370            // No recovery candidate — this IS genuinely, unambiguously a
371            // fresh conversation, decided right now. Safe to emit
372            // immediately: nothing downstream can turn this back into a
373            // resume. Also resolves "Reconnecting…" immediately, in step
374            // with the outcome itself.
375            None => {
376                publish_resume_retry_status(&self.broker, &self.block_id, "resolved");
377                // The respawn below carries the continuation packet whenever
378                // there's history (§4.2.1), so say so.
379                let continued = self.fresh_spawn_would_continue();
380                // The batch being retried is messages: someone is already talking.
381                self.emit_fresh_outcome_now(attempted_sid, continued, false)
382            }
383        }
384        // Non-empty by the guard at the top.
385        let first = entries.remove(0);
386        let rest = entries;
387
388        match self.decide_retry_batch_action(retry_generation, &first, &rest) {
389            RetryBatchAction::FlushClaimed => {
390                // A live, NEWER-generation process was already running by
391                // the time this retry got scheduled (issue #2367 — the
392                // retry's own process exited; a live `stdin_tx` is by
393                // definition an unrelated spawn that raced ahead). The
394                // batch was prepended to the queue and `drain_claim` was
395                // taken in the SAME lock acquisition that decided this
396                // arm, so every concurrent `decide_send_action` caller
397                // already routes to `Queued` behind it — the queue is the
398                // single ordering authority. Flush through the same drain
399                // loop a successful spawn uses (`Sender::send`
400                // backpressure, seed-aware retry-batch appends,
401                // delivery-order persistence); it releases `drain_claim`
402                // once the queue runs dry. This subsumes the previous
403                // `try_send`-then-fall-back-to-queue design: everything
404                // goes through the queue up front, so the batch can never
405                // reorder relative to itself or to racing sends, and the
406                // spawn flag is no longer borrowed for a non-spawn (the
407                // round-7/round-8 fallback machinery this replaces).
408                self.mark_turn_active_and_publish();
409                // `allow_fallback_respawn: false` — the flush targets an
410                // already-running process; a stall means that process
411                // died, and its own exit handling (or the next send's
412                // spawn) picks the leftovers up.
413                self.drain_queue_with_claim(config.clone(), false, QueueDrainClaim::RetryFlush);
414                // reagentx P1 (round 2 on PR #2371): eventual delivery is
415                // the overwhelmingly common outcome — flushing the held
416                // line eagerly here would show a stale, wrong error
417                // bubble immediately followed by the real (successful)
418                // response. On the rare total-failure path the drain's
419                // own `stalled_with_leftovers` branch (with
420                // `allow_fallback_respawn: false`) already calls
421                // `publish_status()` — never silent forever, even without
422                // the specific original error text.
423                drop(held_error_line);
424            }
425            RetryBatchAction::Queued => {
426                // Someone else is already spawning — their own
427                // `release_spawn_claim_and_drain_queue` will deliver this
428                // (or, if their process turns out to already be dead, its
429                // own bounded fallback respawn will).
430                //
431                // reagentx P1 on PR #2371 (round 2): flushing eagerly HERE
432                // (an earlier cut of this fix did, reasoning that losing
433                // it silently on eventual failure was worse) contradicts
434                // this codebase's own established pattern for a `Queued`
435                // outcome — `decide_send_action`'s doc comment: side
436                // effects for a queued item happen "later, inside the
437                // drain, at the exact moment this message is actually
438                // delivered," not eagerly at enqueue time. Eventual
439                // success is the OVERWHELMINGLY common outcome for a
440                // queued message (that's the whole point of the
441                // queue/drain/fallback-respawn infrastructure below), so
442                // flushing eagerly would show a stale, wrong error bubble
443                // in the common case, immediately followed by the real
444                // (successful) response — reproducing the exact bug this
445                // PR exists to fix, just via a different path. Dropped
446                // instead: on the rare total-failure path (the fallback
447                // respawn ALSO fails), `release_spawn_claim_and_drain_queue`'s
448                // own stalled-fallback branch already publishes a status
449                // update and keeps the messages queued for a future spawn
450                // attempt — never silent forever, even without the
451                // specific original error text.
452                drop(held_error_line);
453            }
454            RetryBatchAction::BecomeSpawner { own_seq } => {
455                // Only clear inner.session_id now that THIS retry is
456                // actually about to spawn — codex P2 on PR #2360 (sixth
457                // review pass, round 3): clearing it unconditionally up
458                // front could erase a session id a DIFFERENT,
459                // concurrently-installed process had already legitimately
460                // captured, if this retry instead resolved via
461                // `DeliverDirect` or `Queued` above — breaking in-memory
462                // session tracking and turn-end subagent reconciliation
463                // for that process's remaining lifetime.
464                // Clear + reserve a fresh generation in one lock
465                // acquisition (same race as the leftover-queue fallback —
466                // see `clear_session_id_for_fresh_spawn`).
467                self.clear_session_id_for_fresh_spawn();
468                let retry_config = config.clone();
469                // `Some(first.clone())`, not `None` (codex P1 on PR
470                // #2693): when `config.session_id` holds a recovered
471                // on-disk session (not empty), this MUST thread through
472                // as a real resume-tracking seed — same as any first-time
473                // `--resume` attempt (mirrors `SendAction::BecomeSpawner`'s
474                // own `spawn_process` call above) — or a recovered id
475                // that turns out to be ALSO stale/rejected has no
476                // detection/retry-cascade at all, stranding the batch on
477                // that attempt's raw error instead of eventually falling
478                // through to the promised blank-conversation fallback.
479                // Harmless when there's nothing to resume: `spawn_process`
480                // only constructs `SpawnedWithResume` tracking when
481                // `inner.session_id` actually ends up populated, which it
482                // won't if `config.session_id` is empty — this always
483                // correctly falls back to `SpawnedFresh` in that case,
484                // same as passing `None` used to.
485                let spawn_result = self.spawn_process(config, Some(first.clone()));
486                match &spawn_result {
487                    Ok(_) => self.mark_turn_active_and_publish(),
488                    Err(e) => tracing::error!(
489                        block_id = %self.block_id,
490                        error = %e,
491                        "failed to respawn after a stale --resume session id"
492                    ),
493                }
494                self.release_spawn_claim_and_drain_queue(spawn_result.is_ok(), retry_config, own_seq);
495                if spawn_result.is_err() {
496                    // Surface this, or the pane hangs forever with NO
497                    // signal at all — codex P2 on PR #2360 (fifth review
498                    // pass): the outer process-waiter already suppressed
499                    // its own terminal-status publish for the ORIGINAL
500                    // exit specifically because a retry was in flight, and
501                    // send_message already returned success (possibly
502                    // emitting agent-message-accepted) for the message
503                    // this retry was supposed to deliver. If this respawn
504                    // attempt ALSO fails, nothing else will ever tell the
505                    // frontend this turn is over. `inner.proc_status`/
506                    // `turn_active` are already `STATUS_DONE`/`false` (set
507                    // by the original exit's own cleanup before this
508                    // function was ever called) — this just actually
509                    // broadcasts that state, which the original exit
510                    // deliberately withheld pending this retry's outcome.
511                    self.publish_status();
512                    // codex P2 on PR #2371: the retry never actually
513                    // launched — flush any held error line now instead
514                    // of silently dropping it, so the user gets at least
515                    // one explanation (the original error) instead of
516                    // total silence.
517                    if let Some(line) = held_error_line {
518                        self.flush_error_line_now(line);
519                    }
520                }
521            }
522        }
523    }
524
525    /// Same shape of decision as `decide_send_action`, but atomically
526    /// enqueues the ENTIRE batch (not just one message) in every arm —
527    /// used only by `retry_after_resume_failure`. codex P2 on PR #2360
528    /// (sixth review pass, round 6): deciding and enqueueing a
529    /// multi-message retry batch one call at a time (each through its own
530    /// `decide_send_action` call) left a window between them where a
531    /// genuinely new, unrelated message could interleave into the MIDDLE
532    /// of the same original batch, reordering it relative to how the
533    /// doomed process actually received it. Batch prepend/dedup rules
534    /// live in [`Self::prepend_retry_batch`].
535    ///
536    /// Issue #2367 (spec §4, option 2): the live-process outcome is no
537    /// longer a caller-side `try_send` (`DeliverDirect`) — that let a
538    /// concurrent send race ahead of, or into the middle of, the batch.
539    /// It is now [`RetryBatchAction::FlushClaimed`]: batch prepended and
540    /// `drain_claim` taken under this one lock, then flushed through the
541    /// shared queue drain.
542    pub(super) fn decide_retry_batch_action(
543        &self,
544        retry_generation: u64,
545        first: &persistent_resume::QueuedRetryEntry,
546        rest: &[persistent_resume::QueuedRetryEntry],
547    ) -> RetryBatchAction {
548        let mut inner = self.inner.lock().unwrap();
549        if inner.stdin_tx.is_some() && !inner.spawning_in_progress && !inner.drain_claim {
550            // The retry's own process exited — that exit is what fired
551            // this retry, and the exit-handler clears `stdin_tx` under
552            // the same `is_current_generation` gate — so a live
553            // `stdin_tx` here is by definition a NEWER, unrelated spawn
554            // that raced ahead during the exit-handler's cleanup window
555            // (issue #2367).
556            debug_assert!(
557                inner.spawn_generation != retry_generation,
558                "a retry's own generation cannot still be current while stdin_tx is live"
559            );
560            // Prepend the batch and take the drain claim in THIS SAME
561            // lock acquisition (spec §4 option 2): from this instant
562            // every `decide_send_action` caller routes to `Queued`
563            // behind the batch, so the queue — not a caller's own
564            // `try_send` — is the single ordering authority. The only
565            // residue is a `DeliverDirect` *decided* before this lock
566            // was taken that lands mid-batch: that send was already
567            // racing the process exit itself, and no claim scheme can
568            // sequence it.
569            inner.drain_claim = true;
570            Self::prepend_retry_batch(&mut inner, first, rest);
571            RetryBatchAction::FlushClaimed
572        } else if inner.spawning_in_progress || inner.drain_claim {
573            Self::prepend_retry_batch(&mut inner, first, rest);
574            RetryBatchAction::Queued
575        } else {
576            inner.spawning_in_progress = true;
577            inner
578                .pending_send_messages
579                .push_back(QueuedMessage::already_persisted(first.seq, first.json.clone()));
580            for entry in rest {
581                inner
582                    .pending_send_messages
583                    .push_back(QueuedMessage::already_persisted(entry.seq, entry.json.clone()));
584            }
585            RetryBatchAction::BecomeSpawner { own_seq: first.seq }
586        }
587    }
588
589    /// Prepends a retry batch to `pending_send_messages`, deduping only
590    /// `first` by seq. codex P2 on PR #2360 (sixth review pass, round
591    /// 11): prepend rather than append — this batch represents messages
592    /// accepted by the doomed process BEFORE whatever's currently
593    /// queued (anything queued arrived after the original spawn claimed
594    /// `spawning_in_progress`, so it's chronologically later); appending
595    /// would let the fresh process receive later-arriving input first.
596    ///
597    /// `first` may itself STILL be sitting in the queue (see
598    /// `decide_send_action`'s doc comment on `skip_if_seq_queued`) —
599    /// always at index 0 if so, since it's the ONLY thing ever present
600    /// when a claim starts and nothing but `push_back` ever touches
601    /// this queue elsewhere. In that case `rest` belongs immediately
602    /// after it (same batch, preserving order), not ahead of it. `rest`
603    /// is always pushed as-is: dedup must never apply WITHIN the same
604    /// batch (two entries can legitimately carry identical text and
605    /// both need redelivering).
606    pub(super) fn prepend_retry_batch(
607        inner: &mut PersistentInner,
608        first: &persistent_resume::QueuedRetryEntry,
609        rest: &[persistent_resume::QueuedRetryEntry],
610    ) {
611        let first_already_queued = inner.pending_send_messages.iter().any(|m| m.seq == first.seq);
612        if first_already_queued {
613            for (i, entry) in rest.iter().enumerate() {
614                inner
615                    .pending_send_messages
616                    .insert(i + 1, QueuedMessage::already_persisted(entry.seq, entry.json.clone()));
617            }
618        } else {
619            let mut front: VecDeque<QueuedMessage> = VecDeque::new();
620            front.push_back(QueuedMessage::already_persisted(first.seq, first.json.clone()));
621            for entry in rest {
622                front.push_back(QueuedMessage::already_persisted(entry.seq, entry.json.clone()));
623            }
624            front.append(&mut inner.pending_send_messages);
625            inner.pending_send_messages = front;
626        }
627    }
628}
629
630impl PersistentSubprocessController {
631    /// `retry_after_resume_failure`'s handling of an EMPTY retry batch:
632    /// `--resume <sid>` was attempted with nothing queued — the eager-resume
633    /// path (issue #3463) — and the CLI rejected the id before any prompt
634    /// arrived. There is no message to re-send, so this is a terminal
635    /// idle-resume failure, not a retry. Codex P1 on PR #3538: returning
636    /// early as the old empty-batch branch did left the pane with no
637    /// controller status ever published, because the process-waiter hands
638    /// `FireRetry` (not `PublishDone`) to the retry path on the assumption
639    /// that a launch follows. Complete the recovery *decision* without a
640    /// launch:
641    ///
642    /// - adopt whatever `find_recovery_session_id` found (or `None`) so the
643    ///   NEXT message resumes it through the same gated, tracked `--resume`
644    ///   a first-time resume gets — its outcome (`Resumed`) is emitted then,
645    ///   by the CLI's actual confirmation, never claimed here (codex P1 on
646    ///   PR #2693); with no candidate, `Fresh` IS decidable now and is
647    ///   disclosed now;
648    /// - publish the same terminal status a `PublishDone` exit would.
649    ///
650    /// No "Reconnecting…" is shown or resolved here, unlike the non-empty
651    /// path: no user turn is in flight, so there is no gap to narrate.
652    ///
653    /// EVERYTHING here is conditioned on this retry's generation still
654    /// owning the controller state (codex P1 on PR #3551, both rounds): a
655    /// message that arrived after the doomed process cleared `stdin_tx` but
656    /// before this ran may already have spawned a newer generation with its
657    /// own live session id — possibly resuming a DIFFERENT conversation.
658    /// Overwriting that id, stamping `done` over it, or appending a `Fresh`
659    /// disclosure to its history would each be wrong. The check runs twice:
660    /// once before the recovery search (which does disk I/O outside the
661    /// lock, and must not even start for a superseded generation), and
662    /// again under the same lock acquisition as the mutation, so nothing
663    /// that raced in during the search can be overwritten either.
664    /// `spawn_generation` is bumped in the same lock acquisition that
665    /// installs a new spawn, and `spawning_in_progress` covers the claim
666    /// window before it — together they say whether anyone has moved on.
667    ///
668    /// The side effects (outcome frame, status publish, error flush) run
669    /// UNDER that same lock acquisition, not after it (reagent P1 and codex
670    /// P1 on PR #3551, rounds three and four). Every scheme that released
671    /// the lock first had a window: a check-then-act with nothing holding
672    /// the state still, or a spawn claim that either this settlement took
673    /// (fine) or someone else already held (the eager path's own unwinding
674    /// claim — whose owner could release it mid-effect and let a send
675    /// become a newer generation while the `Fresh` line was still being
676    /// written). Holding `inner` across the effects makes the window not
677    /// exist: a concurrent `decide_send_action` blocks on the lock and,
678    /// once it gets it, becomes a spawner on the already-adopted session.
679    /// This is safe because nothing below re-enters the controller — the
680    /// broker and event bus are `mpsc` channel sends, the block-file append
681    /// and failure persistence touch the file store and SQLite only — and
682    /// cheap enough for a path taken once per failed eager resume. It is
683    /// the one deliberate exception to the file's convention of dropping
684    /// `inner` before effects, which exists because most effect handlers
685    /// call back into methods that lock it; these three do not.
686    pub(super) fn settle_empty_resume_retry(
687        &self,
688        retry_generation: u64,
689        config: PersistentSpawnConfig,
690        held_error_line: Option<String>,
691        attempted_sid: String,
692    ) {
693        // Ownership is generation + no live process — deliberately NOT
694        // `!spawning_in_progress` (codex P1 on PR #3551, third round). That
695        // flag can still be THIS generation's own eager claim: the eagerly
696        // resumed CLI can reject a stale id fast enough for its waiter to
697        // fire before `try_eager_resume` reaches the arm that releases it.
698        // Treating that as "superseded" dropped the whole settlement while
699        // `FireRetry` had already suppressed the waiter's `PublishDone` —
700        // status stuck on `running`, recovery candidate and `Fresh` lost.
701        // A genuinely newer generation is identified by `spawn_generation`,
702        // which `spawn_process` bumps under the lock before anything of the
703        // new process exists; a newer spawner that has claimed but not yet
704        // bumped has no session of its own yet, and adopting the recovered
705        // id underneath it is exactly what it would then `--resume`.
706        let owns = |inner: &PersistentInner| inner.spawn_generation == retry_generation && inner.stdin_tx.is_none();
707        if !owns(&self.inner.lock().unwrap()) {
708            tracing::debug!(
709                block_id = %self.block_id,
710                retry_generation,
711                "empty resume-retry settlement superseded by a newer generation — nothing to do"
712            );
713            return;
714        }
715        let recovered = self.find_recovery_session_id(&config);
716        // Decided before the lock below: it reads the transcript tail.
717        let continued = recovered.is_none() && self.fresh_spawn_would_continue();
718        // Second check, mutation, and every side effect under ONE lock
719        // acquisition — see the doc comment for why nothing may sit
720        // between them.
721        let mut inner = self.inner.lock().unwrap();
722        if !owns(&inner) {
723            return;
724        }
725        inner.session_id = recovered.clone();
726        // Accepted prompts queued behind the eager spawn claim (codex P1 on
727        // PR #3551, fifth round): they never reached the doomed process, so
728        // they are not in the (empty) retry batch — but they are real work,
729        // and this is NOT a message-free settlement. The eager path's own
730        // drain will find the dead `stdin_tx`, stall, and hand them to
731        // `respawn_once_for_leftover_queue`; leave it the candidate so that
732        // respawn resumes it instead of clearing to fresh, and leave the
733        // terminal status and the held error line alone — a spawn follows
734        // immediately, and the CLI's stale-resume error would otherwise
735        // show as a stale bubble right before a successful reply (reagentx
736        // P1 on PR #2371's reasoning). `Fresh` is still disclosed when
737        // there is nothing to recover: that decision is final either way.
738        let queued_behind_claim = !inner.pending_send_messages.is_empty();
739        if queued_behind_claim {
740            inner.leftover_resume_candidate = recovered.clone();
741        } else {
742            Self::set_status(&mut inner, STATUS_DONE);
743        }
744        if recovered.is_none() {
745            // This settles an empty retry batch, but a prompt accepted behind
746            // the claim can still be waiting: then a message is about to start
747            // the session, and it is not idle.
748            self.emit_fresh_outcome_now(attempted_sid, continued, !queued_behind_claim);
749        }
750        if queued_behind_claim {
751            drop(inner);
752            return;
753        }
754        // `publish_status` would re-lock `inner`; build the same snapshot
755        // from the guard we already hold.
756        if let Some(ref broker) = self.broker {
757            let status = super::super::agent_runtime_status(
758                &self.block_id,
759                inner.status_version,
760                &inner.proc_status,
761                inner.proc_exit_code,
762                self.health_monitor.is_active_turn(),
763            );
764            super::super::publish_controller_status(broker, &status);
765            // `set_status(STATUS_DONE)` above cleared what the process was
766            // spawned with; announce it from the guard already held.
767            super::status::announce_runtime(broker, &self.block_id, &inner);
768        }
769        // Nothing was accepted from the user, but the CLI's own account of
770        // why the resume failed still reaches them (codex P2 on PR #2371).
771        if let Some(line) = held_error_line {
772            self.flush_error_line_now(line);
773        }
774        drop(inner);
775    }
776}
777
778/// The session id of the conversation a pane renders: the last provider
779/// session id in its own transcript, else in the agent's global transcript
780/// zone. Same sources, same order, as `has_prior_transcript`, so "the pane
781/// shows history" and "the spawn continues it" can't disagree.
782///
783/// Taken from AgentMux's own record rather than a scan of the provider's
784/// dir, so an archived conversation (every explicit "start fresh" action
785/// archives) is never picked up, and a subagent's transcript can't pass for
786/// the agent's own. No reachability check; callers decide what an
787/// unreachable id means.
788pub fn pane_history_session_id(
789    filestore: Option<&FileStore>,
790    mstore: Option<&Store>,
791    block_id: &str,
792    session_id_field: &str,
793) -> Option<String> {
794    if session_id_field.is_empty() {
795        return None;
796    }
797    let (tail, starts_mid_line) = pane_history_tail(filestore, mstore, block_id, CONTINUATION_TAIL_BYTES)?;
798    last_session_id_in_stream(&tail, starts_mid_line, session_id_field)
799}
800
801/// The last `max_bytes` of the history a pane renders: its own transcript,
802/// else the agent's global zone. The `bool` is whether the window starts
803/// partway into the file (so its first line is a fragment).
804pub(crate) fn pane_history_tail(
805    filestore: Option<&FileStore>,
806    mstore: Option<&Store>,
807    block_id: &str,
808    max_bytes: i64,
809) -> Option<(Vec<u8>, bool)> {
810    if let Some(tail) = filestore.and_then(|fs| read_transcript_tail(fs, block_id, PERSISTENT_OUTPUT_SUBJECT, max_bytes)) {
811        return Some(tail);
812    }
813    let zone = global_prior_zone(mstore, block_id)?;
814    let gfs = crate::backend::transcript::damage::global_for(&zone)?;
815    read_transcript_tail(&gfs, &zone, crate::backend::agent_session::OUTPUT_FILE, max_bytes)
816}
817
818/// The transcript a continuation packet is built from: the agent's global
819/// zone when the pane has one, else the pane's own transcript.
820///
821/// Deliberately NOT [`pane_history_tail`]'s local-first order. The zone
822/// mirrors every append to the pane file, so it holds everything the pane
823/// does, plus the conversation from earlier channels and builds. On a new
824/// channel the pane file is created by a rejected resume's own settlement
825/// (the session-outcome line and the CLI's error result), and reading it
826/// first built no packet at all while the global record held the whole
827/// conversation (REPORT_AGENT_HISTORY_LOST_ON_NEW_BUILD_2026_09_25.md §4).
828pub(super) fn packet_history_tail(
829    filestore: Option<&FileStore>,
830    block_id: &str,
831    global: Option<(&FileStore, &str)>,
832    max_bytes: i64,
833) -> Option<(Vec<u8>, bool)> {
834    global
835        .and_then(|(gfs, zone)| read_transcript_tail(gfs, zone, crate::backend::agent_session::OUTPUT_FILE, max_bytes))
836        .or_else(|| filestore.and_then(|fs| read_transcript_tail(fs, block_id, PERSISTENT_OUTPUT_SUBJECT, max_bytes)))
837}
838
839/// The agent's global transcript zone, when this pane would render it:
840/// agent-anchored and not archived.
841pub(super) fn global_prior_zone(mstore: Option<&Store>, block_id: &str) -> Option<String> {
842    let block = mstore?.must_get::<crate::backend::obj::Block>(block_id).ok()?;
843    let archived = block
844        .meta
845        .get(crate::backend::session_archive::META_SESSION_ARCHIVED_AT)
846        .and_then(|v| v.as_i64())
847        .is_some_and(|v| v > 0);
848    if archived {
849        return None;
850    }
851    crate::backend::agent_session::agent_zone_for_block_meta(&block.meta)
852}
853
854/// The last `max_bytes` of a transcript, and whether that window starts
855/// partway into the file (so its first line is a fragment).
856fn read_transcript_tail(fs: &FileStore, zone: &str, name: &str, max_bytes: i64) -> Option<(Vec<u8>, bool)> {
857    use crate::backend::transcript::damage;
858    let file = match fs.stat(zone, name) {
859        Ok(file) => file?,
860        Err(e) => {
861            damage::note_if_shared(fs, zone, "tail read", &e);
862            return None;
863        }
864    };
865    if file.size <= 0 {
866        return None;
867    }
868    let offset = (file.size - max_bytes).max(0);
869    let (actual_offset, data) = match fs.read_at(zone, name, offset, file.size - offset) {
870        Ok(read) => read,
871        Err(e) => {
872            damage::note_if_shared(fs, zone, "tail read", &e);
873            return None;
874        }
875    };
876    (!data.is_empty()).then_some((data, actual_offset > 0))
877}
878
879/// Whether `zone` of the shared store holds an `output`; a corrupt answer marks the zone damaged ([`damage`](crate::backend::transcript::damage))
880/// and is "no".
881fn global_zone_has_output(gfs: &FileStore, zone: &str) -> bool {
882    match gfs.stat(zone, crate::backend::agent_session::OUTPUT_FILE) {
883        Ok(file) => file.is_some_and(|f| f.size > 0),
884        Err(e) => {
885            crate::backend::transcript::damage::note_if_shared(gfs, zone, "resume check", &e);
886            false
887        }
888    }
889}
890
891#[cfg(test)]
892mod damage_tests {
893    use super::*;
894    use crate::backend::storage::filestore::{FileMeta, FileOpts};
895    use crate::backend::transcript::damage::{self, test_support};
896
897    const OWN: &[u8] = b"{\"type\":\"user\",\"own\":1}\n";
898
899    fn with_output(fs: &FileStore, zone: &str, name: &str, body: &[u8]) {
900        fs.make_file(zone, name, FileMeta::default(), FileOpts::default()).unwrap();
901        fs.append_lines(zone, name, body).unwrap();
902    }
903
904    #[test]
905    fn a_corrupt_shared_zone_has_no_prior_output_and_is_marked() {
906        let zone = "agent:resume-damage-1:current";
907        let gfs = FileStore::open_in_memory().unwrap();
908        with_output(&gfs, zone, "output", b"{\"g\":1}\n");
909        let _shared = test_support::register(&gfs);
910        assert!(global_zone_has_output(&gfs, zone), "healthy: as before");
911        test_support::corrupt(&gfs);
912        assert!(!global_zone_has_output(&gfs, zone));
913        assert!(damage::is_damaged(zone));
914    }
915
916    #[test]
917    fn the_continuation_packet_tail_comes_from_the_panes_own_transcript_when_the_shared_zone_is_corrupt() {
918        let zone = "agent:resume-damage-2:current";
919        let (own, gfs) = (FileStore::open_in_memory().unwrap(), FileStore::open_in_memory().unwrap());
920        with_output(&own, "blk-resume-damage-2", PERSISTENT_OUTPUT_SUBJECT, OWN);
921        with_output(&gfs, zone, "output", b"{\"g\":1}\n");
922        let _shared = test_support::register(&gfs);
923        let (tail, _) = packet_history_tail(Some(&own), "blk-resume-damage-2", Some((&gfs, zone)), 1000).unwrap();
924        assert_eq!(tail, b"{\"g\":1}\n", "healthy: the shared zone, as before");
925        test_support::corrupt(&gfs);
926        let (tail, _) = packet_history_tail(Some(&own), "blk-resume-damage-2", Some((&gfs, zone)), 1000).unwrap();
927        assert_eq!(tail, OWN, "the pane's own transcript builds the packet");
928        assert!(damage::is_damaged(zone));
929    }
930
931    #[test]
932    fn a_tail_read_error_that_is_not_corruption_marks_nothing() {
933        let zone = "agent:resume-damage-3:current";
934        let gfs = FileStore::open_in_memory().unwrap();
935        let _shared = test_support::register(&gfs);
936        gfs.conn().lock().unwrap().execute_batch("DROP TABLE db_wave_file;").unwrap();
937        assert!(read_transcript_tail(&gfs, zone, "output", 100).is_none());
938        assert!(!global_zone_has_output(&gfs, zone));
939        assert!(!damage::is_damaged(zone));
940    }
941}