Skip to main content

agentmux_srv_core/backend/blockcontroller/persistent/
stdout_reader.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The persistent CLI's stdout reader task, started by `spawn_process`
5//! (`spawn.rs`): control frames, session-id capture, resume-state events,
6//! API retry state, the API's reachability, failure classification, the
7//! task feed and the output append.
8
9use super::*;
10
11// What the reader does when the loop guard says the agent is stuck. Declared here, not in `mod.rs`, which is
12// at its size ratchet.
13#[path = "loop_stop.rs"]
14pub mod loop_stop;
15
16/// What the stdout reader task captures from `spawn_process`.
17pub(super) struct StdoutReaderCtx {
18    pub(super) stdout: tokio::process::ChildStdout,
19    pub(super) block_id_read: String,
20    pub(super) broker_read: Option<Arc<mps::Broker>>,
21    pub(super) inner_read: Arc<Mutex<PersistentInner>>,
22    pub(super) mstore_read: Option<Arc<Store>>,
23    pub(super) event_bus_read: Option<Arc<EventBus>>,
24    pub(super) filestore_read: Option<Arc<FileStore>>,
25    pub(super) health_read: Arc<TurnActivityTracker>,
26    pub(super) self_ref_read: Option<std::sync::Weak<PersistentSubprocessController>>,
27    pub(super) stdout_seq_read: Arc<AtomicU64>,
28    pub(super) session_id_field: String,
29    pub(super) my_generation_read: u64,
30    /// This spawn's process-wide registration nonce: whose MCP report this
31    /// reader records (`backend::mcp_observed`).
32    pub(super) mcp_owner_read: u64,
33    pub(super) global_output_zone: Option<String>,
34    pub(super) record_fence: Option<crate::backend::agent_admission::RecordFence>,
35    pub(super) segment_read: super::segments::SegmentRef,
36    pub(super) relocated_copy_read: Option<crate::backend::continuity_relocate::Relocated>,
37    pub(super) forked_from_read: Option<String>,
38    /// The user turns the stdin writer sent (`backend::cli_native::sent`).
39    pub(super) sent_prompts: crate::backend::cli_native::sent::SentPrompts,
40    /// The model API this pane's CLI calls, which its frames report on (`connectivity`).
41    pub(super) model_api: crate::connectivity::Service,
42}
43
44/// The stdout reader task: what its context carries, and what it builds up across lines.
45struct StdoutReader {
46    block_id_read: String,
47    broker_read: Option<Arc<mps::Broker>>,
48    inner_read: Arc<Mutex<PersistentInner>>,
49    mstore_read: Option<Arc<Store>>,
50    event_bus_read: Option<Arc<EventBus>>,
51    filestore_read: Option<Arc<FileStore>>,
52    health_read: Arc<TurnActivityTracker>,
53    self_ref_read: Option<std::sync::Weak<PersistentSubprocessController>>,
54    stdout_seq_read: Arc<AtomicU64>,
55    session_id_field: String,
56    my_generation_read: u64,
57    mcp_owner_read: u64,
58    global_output_zone: Option<String>,
59    record_fence: Option<crate::backend::agent_admission::RecordFence>,
60    segment_read: super::segments::SegmentRef,
61    relocated_copy_read: Option<crate::backend::continuity_relocate::Relocated>,
62    forked_from_read: Option<String>,
63    model_api: crate::connectivity::Service,
64    stats: super::super::session_stats::SessionStatsAccumulator,
65    task_feed: crate::backend::background_task_feed::TaskFeed,
66    api_retry: crate::backend::agent_api_retry::ApiRetryReader,
67    parked_notices_due: bool,
68    /// What the turn's synthetic assistant message said failed ("authentication_failed", or the limit or
69    /// error sentence it carries), for the result frame that follows: that frame names no cause of its own.
70    inband_text: String,
71    cli_native: crate::backend::cli_native::reader::CliNativeReader,
72    /// What this turn has done, for the loop guard (`agents::loop_guard`).
73    loop_guard: crate::agents::loop_guard::LoopGuard,
74    /// The guard ended this turn, and why: the interrupt's result frame is our stop, not a failure.
75    ended_by_guard: Option<String>,
76}
77
78/// What one parsed stdout line decided for the loop.
79#[derive(Default)]
80struct FrameOutcome {
81    /// A control frame: handled, and not conversation output.
82    skip: bool,
83    hold_back_for_resume_retry: bool,
84    release_parked_notices: bool,
85    /// Why we ended this result frame's turn (the loop guard, the spend cap): the frame is shown with that
86    /// text, not the CLI's generic error.
87    ended_because: Option<String>,
88}
89
90/// What a frame says about its turn, before the turn-end work.
91struct FrameVerdict {
92    is_result_frame: bool,
93    inband_error: String,
94    early_failure: Option<crate::agents::failure::AgentFailure>,
95}
96
97impl PersistentSubprocessController {
98    /// Body of the stdout reader task; `spawn_process` keeps its JoinHandle
99    /// for the process waiter.
100    pub(super) async fn run_stdout_reader(ctx: StdoutReaderCtx) {
101        let (stdout, mut reader) = StdoutReader::from_ctx(ctx);
102        let mut lines = BufReader::new(stdout).lines();
103
104        // NOTE: OSC window-title extraction is NOT done here.
105        // PersistentSubprocessController uses piped stdout with stream-json
106        // NDJSON protocol. Claude Code sets window titles via process.title
107        // (SetConsoleTitle on Windows; argv[0] on Unix), which does NOT
108        // produce OSC escape sequences in the piped stdout stream. Inserting
109        // OSC bytes into stream-json stdout would corrupt the JSON protocol.
110        // block:activity events for agent panes are instead published by
111        // the terminalSequence hooks path — see spec §2.5 and the future
112        // SPEC_AGENT_HOOKS_TERMINAL_SEQUENCE spec.
113
114        while let Ok(Some(line)) = lines.next_line().await {
115            reader.handle_line(line);
116        }
117
118        tracing::info!(block_id = %reader.block_id_read, "persistent stdout reader finished");
119    }
120}
121
122impl StdoutReader {
123    fn from_ctx(ctx: StdoutReaderCtx) -> (tokio::process::ChildStdout, Self) {
124        let StdoutReaderCtx {
125            stdout,
126            block_id_read,
127            broker_read,
128            inner_read,
129            mstore_read,
130            event_bus_read,
131            filestore_read,
132            health_read,
133            self_ref_read,
134            stdout_seq_read,
135            session_id_field,
136            my_generation_read,
137            mcp_owner_read,
138            global_output_zone,
139            record_fence,
140            segment_read,
141            relocated_copy_read,
142            forked_from_read,
143            sent_prompts,
144            model_api,
145        } = ctx;
146        let stats = super::super::session_stats::SessionStatsAccumulator::new(block_id_read.clone());
147        // The CLI's own `task_started`/`task_updated`/`task_notification`
148        // lines drive the background-task registry, including tasks a
149        // subagent owns (see `background_task_feed.rs`).
150        let task_feed = crate::backend::background_task_feed::TaskFeed::default();
151        // Clears its retry when dropped, so also when this task is aborted.
152        let api_retry =
153            crate::backend::agent_api_retry::ApiRetryReader::new(&block_id_read, my_generation_read, broker_read.clone());
154        // Messages other agents send this one through the CLI's own messaging, and the
155        // user turns the CLI replays because it is launched with `--replay-user-messages`
156        // (`backend::cli_native`).
157        let cli_native = crate::backend::cli_native::reader::CliNativeReader::new(&block_id_read, sent_prompts);
158        let reader = Self {
159            block_id_read,
160            broker_read,
161            inner_read,
162            mstore_read,
163            event_bus_read,
164            filestore_read,
165            health_read,
166            self_ref_read,
167            stdout_seq_read,
168            session_id_field,
169            my_generation_read,
170            mcp_owner_read,
171            global_output_zone,
172            record_fence,
173            segment_read,
174            relocated_copy_read,
175            forked_from_read,
176            model_api,
177            stats,
178            task_feed,
179            api_retry,
180            // Set by a compaction boundary: the memory card the hook finished
181            // before the boundary was written waits for the first line after the
182            // boundary that isn't the CLI's own user-turn text (its summary, a
183            // command's output), and is written just ahead of it
184            // (SPEC_CONTEXT_DELIVERY_2026_09_30.md §9 C2).
185            parked_notices_due: false,
186            // The turn's synthetic assistant message said what failed; its result frame follows.
187            inband_text: String::new(),
188            cli_native,
189            loop_guard: Default::default(),
190            ended_by_guard: None,
191        };
192        (stdout, reader)
193    }
194
195    /// `line` rewritten when it is a `result` frame from an agent on a model
196    /// route: the harness prices its tokens with Claude's rates, which on a
197    /// route are wrong by orders of magnitude, so the provider's own session
198    /// total replaces both totals the frame reports (#30143). `None` for any
199    /// other frame, and for an agent whose responses never carried a charge.
200    fn route_cost_frame(&self, line: &str, parsed: &serde_json::Value) -> Option<String> {
201        if parsed.get("type").and_then(serde_json::Value::as_str) != Some("result") {
202            return None;
203        }
204        let mstore = self.mstore_read.as_ref()?;
205        let agent = crate::identity::resolver::block_agent_id(mstore, &self.block_id_read)?;
206        crate::backend::model_gateway::spend::rewrite_result_total(line, &agent)
207    }
208
209    /// Settles a model change waiting on its first turn with the `result` frame that ended it; whether the change was
210    /// undone, which needs the harness restarted on the old place.
211    fn settle_route_trial(&self, parsed: &serde_json::Value) -> bool {
212        // A replaced process's late frame ends nothing the current one is doing.
213        if self.inner_read.lock().unwrap().spawn_generation != self.my_generation_read {
214            return false;
215        }
216        let Some(mstore) = self.mstore_read.as_ref() else { return false };
217        let Some(agent) = crate::identity::resolver::block_agent_id(mstore, &self.block_id_read) else { return false };
218        crate::backend::model_gateway::trial::settle(mstore, &agent, &self.block_id_read, parsed).is_some()
219    }
220
221    /// One line of the CLI's stdout.
222    fn handle_line(&mut self, line: String) {
223        if line.trim().is_empty() {
224            return;
225        }
226        // A turn the CLI found cut off with a tool call pending (we
227        // interrupted it at a restart or an upgrade) is told plainly, not
228        // as the CLI's raw diagnostic; the diagnostic stays in the log.
229        let mut line = match crate::agents::failure::plain_cut_off(&line) {
230            Some((diagnostic, plain)) => {
231                tracing::info!(block_id = %self.block_id_read, diagnostic = %diagnostic, "a turn was cut off mid-tool; shown as an interrupted turn");
232                plain
233            }
234            None => line,
235        };
236        // A replayed user turn is not output of the conversation: the echo of a turn srv wrote is
237        // recorded by srv and the pane already, and a peer message is audited here instead. The
238        // CLI's own replayed frames (a local command's output) stay.
239        if line.contains("\"isReplay\"") {
240            if let Ok(v) = serde_json::from_str::<serde_json::Value>(&line) {
241                use crate::backend::cli_native::reader::Disposition;
242                if self.cli_native.observe(&v, &crate::backend::cli_native::live::LiveEnv) == Disposition::Drop {
243                    return;
244                }
245            }
246        }
247        // Bump the activity counter for EVERY non-empty stdout line —
248        // including control frames, which `handle_frame` skips — so
249        // the AskUserQuestion dead-air fallback can tell whether the
250        // turn resumed. See `answer_question`.
251        self.stdout_seq_read.fetch_add(1, Ordering::Relaxed);
252        self.health_read.note_output();
253
254        // Track session metadata (debounced 1 s)
255        self.stats.record_line(line.len(), &self.mstore_read);
256
257        // Set (instead of persisted immediately) when this line turns
258        // out to be a terminal `result`/`is_error:true` event arriving
259        // while a stale-`--resume` retry could still be confirmed for
260        // this exact attempt — see `persistent_resume::ResumeState`'s
261        // `held_error_line`. `false` for every other line, matching
262        // today's behavior exactly.
263        let mut outcome = FrameOutcome::default();
264        // Parse JSON for control-frame handling, turn-active tracking,
265        // and session ID capture
266        if let Ok(mut parsed) = serde_json::from_str::<serde_json::Value>(&line) {
267            if let Some(rewritten) = self.route_cost_frame(&line, &parsed) {
268                if let Ok(v) = serde_json::from_str::<serde_json::Value>(&rewritten) {
269                    parsed = v;
270                    line = rewritten;
271                }
272            }
273            outcome = self.handle_frame(&line, &parsed);
274            if outcome.skip {
275                return;
276            }
277            if let Some(why) = outcome.ended_because.take() { line = loop_stop::plain_end_frame(&line, &why); }
278        }
279
280        if outcome.hold_back_for_resume_retry {
281            return;
282        }
283
284        // Publish line as MPS blockfile event and write-through to FileStore
285        // for persistent history (Phase 1.3).
286        if let Some(ref broker) = self.broker_read {
287            if outcome.release_parked_notices {
288                for notice in crate::backend::memory::delivery_state::take_parked_notices(&self.block_id_read) {
289                    crate::backend::transcript::append::append_output_line(
290                        broker,
291                        &self.block_id_read,
292                        &notice,
293                        self.filestore_read.as_ref(),
294                        crate::backend::agent_admission::fenced_zone(self.global_output_zone.as_deref(), &self.record_fence),
295                    );
296                }
297            }
298            crate::backend::transcript::append::append_agent_output_line(
299                broker,
300                &self.block_id_read,
301                &line,
302                self.filestore_read.as_ref(),
303                crate::backend::agent_admission::fenced_zone(self.global_output_zone.as_deref(), &self.record_fence),
304                crate::backend::transcript::origin_sig::WriterRuntime::Host,
305            );
306        } else {
307            tracing::warn!(block_id = %self.block_id_read, "persistent stdout: no broker available");
308        }
309    }
310
311    /// Everything a parsed line sets in motion: control frames, observers, turn end, session-id
312    /// capture, resume tracking and failure classification.
313    fn handle_frame(&mut self, line: &str, parsed: &serde_json::Value) -> FrameOutcome {
314        self.cli_native.observe(parsed, &crate::backend::cli_native::live::LiveEnv);
315        // Control-protocol frames (can_use_tool / AskUserQuestion) are
316        // NOT conversation output — handle them and skip the blockfile
317        // so the frontend stream never sees them.
318        // Spec: docs/specs/SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md.
319        if let Some(kind) = parsed.get("type").and_then(|v| v.as_str()) {
320            if kind == "control_request" || kind == "control_response" {
321                self.observe_control_frame(kind, parsed);
322                return FrameOutcome { skip: true, ..FrameOutcome::default() };
323            }
324        }
325        let release_parked_notices = self.observe_frame(parsed);
326        let FrameVerdict { is_result_frame, inband_error, early_failure } = self.frame_verdict(parsed);
327        let ended_because = self.watch_for_loops(parsed, is_result_frame).or_else(|| (is_result_frame && loop_stop::take_cap_end(&self.block_id_read)).then(|| loop_stop::CAP_ENDED.to_string()));
328        // Claude's turn-ending marker. Persistent mode never exits
329        // between turns, so this is the only place `turn_active`
330        // can go back to false without waiting for process exit —
331        // see `send_message`'s matching `set_active_turn(true)`.
332        if is_result_frame {
333            self.on_turn_end(parsed);
334        }
335        // A turn WE interrupted to close the pane ends in an
336        // `is_error: true` result (`error_during_execution`).
337        // That is the requested stop, not a failure: treat it
338        // as an ordinary end of turn — no failure banner, no
339        // stale-`--resume` retry tracking (pane-close spec §9.4).
340        let closing_this_generation = is_result_frame
341            && self.inner_read.lock().unwrap().shutdown_generation == Some(self.my_generation_read);
342        let is_error_result = is_result_frame
343            && !closing_this_generation
344            && ended_because.is_none()
345            && parsed.get("is_error").and_then(|v| v.as_bool()) == Some(true);
346        // reagentx P0 on PR #2371: the real CLI's stream-json
347        // protocol embeds `session_id_field` on EVERY event,
348        // including the terminal `result` — so the doomed
349        // attempt's own `is_error:true` line ALSO carries the
350        // (stale) sid it was given. Calling
351        // `try_capture_session_id` for THIS exact line would
352        // resolve this generation's resume tracking (a
353        // non-poisoned confirmation does — codex P1's fix,
354        // needed for the genuinely-successful-resume case)
355        // BEFORE the `ErrorResultLine` event (`track_error_result`) ever runs,
356        // reproducing the exact bubble this PR exists to
357        // suppress AND preventing PR #2360's own retry from
358        // ever being confirmed. An error frame's echoed sid is
359        // never genuine progress (the turn failed) — skip
360        // session-id capture entirely for this exact frame;
361        // every other frame type (system/init, a successful
362        // result) still captures normally.
363        // Set when `apply_capture_effects` classifies and
364        // persists a flushed OLDER turn's failure this tick — the
365        // clear-on-success step (`surface_turn_outcome`) must not immediately
366        // wipe out state it just recorded (SPEC_PERSISTENT_
367        // CONTROLLER_FAILURE_CLASSIFICATION_2026_08_04.md).
368        let mut flushed_failure_this_tick = false;
369        if !is_error_result {
370            self.capture_session_id(parsed, is_result_frame, &mut flushed_failure_this_tick);
371        }
372        let hold_back_for_resume_retry =
373            is_error_result && self.track_error_result(line, &mut flushed_failure_this_tick);
374        self.surface_turn_outcome(
375            parsed,
376            is_result_frame,
377            is_error_result,
378            hold_back_for_resume_retry,
379            early_failure.is_none(),
380            &inband_error,
381            flushed_failure_this_tick,
382        );
383        FrameOutcome { skip: false, hold_back_for_resume_retry, release_parked_notices, ended_because: ended_because.filter(|_| parsed.get("is_error").and_then(|v| v.as_bool()) == Some(true)) }
384    }
385
386    /// Feeds the frame to the loop guard and ends the turn when it says the agent is stuck. `true` for the
387    /// result frame of a turn the guard ended: what it was stuck doing.
388    fn watch_for_loops(&mut self, parsed: &serde_json::Value, is_result_frame: bool) -> Option<String> {
389        if is_result_frame {
390            self.loop_guard.new_turn();
391            return self.ended_by_guard.take();
392        }
393        if self.ended_by_guard.is_some() {
394            return None;
395        }
396        if let Some(stuck) = self.loop_guard.observe(parsed) {
397            self.ended_by_guard = loop_stop::end_the_turn(&self.inner_read, self.my_generation_read, &self.block_id_read, self.mstore_read.as_ref(), &stuck);
398        }
399        None
400    }
401
402    /// The answers to our own control requests, and the question the agent is blocked on.
403    fn observe_control_frame(&mut self, kind: &str, parsed: &serde_json::Value) {
404        // The answer to our `get_context_usage`: where this
405        // process auto-compacts. Ignored from a replaced
406        // process; re-published only when it changed.
407        if let Some(usage) =
408            crate::backend::agent_context_usage::context_usage_from_control_response(parsed)
409        {
410            let changed = {
411                let mut g = self.inner_read.lock().unwrap();
412                if g.spawn_generation == self.my_generation_read && g.context_usage.as_ref() != Some(&usage) {
413                    g.context_usage = Some(usage.clone());
414                    true
415                } else {
416                    false
417                }
418            };
419            if let (true, Some(broker)) = (changed, self.broker_read.as_ref()) {
420                crate::backend::agent_context_usage::publish_agent_context_usage(
421                    broker,
422                    &self.block_id_read,
423                    &usage,
424                );
425            }
426        }
427        // The answer to our `get_settings`: what the CLI
428        // really runs. Ignored from a replaced process.
429        if let Some(eff) = crate::backend::agent_runtime::effective_from_control_response(parsed) {
430            let changed = {
431                let mut g = self.inner_read.lock().unwrap();
432                if g.spawn_generation == self.my_generation_read && g.spawn_runtime.is_some() {
433                    let changed = g.effective_runtime.as_ref() != Some(&eff);
434                    g.effective_runtime = Some(eff);
435                    changed
436                } else {
437                    false
438                }
439            };
440            if let (true, Some(broker)) = (changed, self.broker_read.as_ref()) {
441                super::status::publish_runtime_event(&self.inner_read, broker, &self.block_id_read);
442            }
443        }
444        // The answer to a self-heal `mcp_status`/`mcp_reconnect`.
445        if let Some(ctrl) = self.self_ref_read.as_ref().and_then(|w| w.upgrade()) {
446            ctrl.observe_mcp_frame(parsed, self.my_generation_read);
447        }
448        PersistentSubprocessController::handle_control_frame(kind, parsed, &self.block_id_read, &self.inner_read);
449        // OS notification: the agent is now blocked on the
450        // user — known here even with no pane mounted
451        // (SPEC_OS_NOTIFICATIONS_SYSTEM_2026_09_24 Phase 5).
452        if let (Some(broker), Some(asked)) = (
453            self.broker_read.as_ref(),
454            crate::backend::notify::sources::ask_user_question(parsed),
455        ) {
456            if let Some(r) = crate::backend::notify::router::get(broker) {
457                r.input_waiting_nonblocking(&self.block_id_read, asked.text, asked.count);
458            }
459        }
460    }
461
462    /// What each kind of frame tells the rest of srv about the CLI. Returns whether the parked
463    /// memory notices are due ahead of this line.
464    fn observe_frame(&mut self, parsed: &serde_json::Value) -> bool {
465        let mut release_parked_notices = false;
466        self.api_retry.observe(parsed, || self.inner_read.lock().unwrap().spawn_generation);
467        crate::connectivity::observe_claude_frame(parsed, &self.model_api);
468        if let Some(store) = self.mstore_read.as_deref() {
469            let now_ms = agentmux_common::time::now_ms();
470            self.task_feed.apply(
471                store,
472                self.broker_read.as_deref(),
473                &self.block_id_read,
474                parsed,
475                now_ms,
476            );
477        }
478        // A pass the CLI starts by itself: a finished background
479        // task's `task_notification`, then a fresh `system/init` with
480        // no input from srv (turn-model spec §4.2). Recorded so the
481        // agent reads busy for that pass, everywhere `turn_active`
482        // is read. Ignored from a replaced process.
483        if parsed.get("type").and_then(|v| v.as_str()) == Some("system") {
484            let subtype = parsed.get("subtype").and_then(|v| v.as_str());
485            let current = || self.inner_read.lock().unwrap().spawn_generation == self.my_generation_read;
486            if subtype == Some("task_notification") && current() {
487                self.health_read.note_cli_task_notification(parsed.get("summary").and_then(|v| v.as_str()));
488            } else if subtype == Some("init") && current() && self.health_read.mark_turn_active_from_cli() {
489                if let Some(ctrl) = self.self_ref_read.as_ref().and_then(|w| w.upgrade()) {
490                    ctrl.cli_started_pass();
491                }
492            }
493        }
494        // Whether its `agentmux` MCP server connected, from the same
495        // frame: one that didn't is repaired (`backend::mcp_health`).
496        if parsed.get("subtype").and_then(|v| v.as_str()) == Some("init") {
497            if let Some(ctrl) = self.self_ref_read.as_ref().and_then(|w| w.upgrade()) {
498                ctrl.observe_mcp_frame(parsed, self.my_generation_read);
499            }
500            // Every server it reports, for Connectors (`backend::mcp_observed`);
501            // a replaced process's late init never writes over a newer one's.
502            if crate::backend::mcp_observed::record_init(&self.block_id_read, self.mcp_owner_read, parsed) {
503                crate::backend::mcp_observed::publish(self.broker_read.as_deref(), &self.block_id_read);
504            }
505        }
506        // The CLI version this agent now runs, from Claude's own
507        // `system/init` frame: every spawn path passes here, and
508        // it is the version that actually runs, so a self-update
509        // shows too. A change from the agent's last run puts a
510        // notice in the pane (`backend::cli_notice`).
511        if parsed.get("subtype").and_then(|v| v.as_str()) == Some("init") {
512            if let (Some(version), Some(store), Some(broker), Some(filestore)) = (
513                parsed.get("claude_code_version").and_then(|v| v.as_str()),
514                self.mstore_read.clone(),
515                self.broker_read.clone(),
516                self.filestore_read.clone(),
517            ) {
518                let (block_id, version) = (self.block_id_read.clone(), version.to_string());
519                tokio::task::spawn_blocking(move || {
520                    crate::backend::cli_notice::observe_and_notify(
521                        &broker, &filestore, &store, &block_id, None, "claude", &version,
522                    );
523                });
524            }
525        }
526        // The latest `rate_limit_event`: a usage limit stored later
527        // reads its reset from it (`agents::limit_reset`).
528        crate::agents::limit_reset::observe_frame(&self.block_id_read, parsed);
529        // The same frame's usage windows, kept for the pane's account (`backend::account_usage`).
530        if let Some(store) = self.mstore_read.as_ref() {
531            crate::backend::account_usage::observe_claude_frame(&self.block_id_read, store, parsed);
532        }
533        crate::backend::context_reading::observe_claude_frame(&self.block_id_read, parsed);
534        // A reply that names its model tells the pane's chip at once, not at the next turn's spawn.
535        let names_model = parsed.pointer("/message/model").is_some() || parsed.pointer("/event/message/model").is_some();
536        if let (true, Some(broker)) = (names_model, self.broker_read.as_ref()) {
537            crate::backend::agent_runtime_container::publish_running_reply(broker, &self.block_id_read);
538        }
539        // This block's CLI compacted: only its pane may send the
540        // hidden memory reinjection for that boundary.
541        if parsed.get("subtype").and_then(|v| v.as_str()) == Some("compact_boundary") {
542            if let Some(uuid) = parsed.get("uuid").and_then(|v| v.as_str()) {
543                crate::backend::memory::delivery_state::record_compaction_boundary(&self.block_id_read, uuid);
544            }
545            self.parked_notices_due = true;
546        } else if self.parked_notices_due
547            && !matches!(parsed.get("type").and_then(|v| v.as_str()), Some("user") | Some("system"))
548        {
549            release_parked_notices = true;
550            self.parked_notices_due = false;
551        }
552        release_parked_notices
553    }
554
555    /// Whether the frame ends the turn, and a quota or sign-in failure it carries.
556    fn frame_verdict(&mut self, parsed: &serde_json::Value) -> FrameVerdict {
557        let is_result_frame =
558            parsed.get("type").and_then(|v| v.as_str()) == Some("result");
559        if parsed.get("type").and_then(|v| v.as_str()) == Some("assistant") {
560            self.inband_text = crate::agents::limit_reset::assistant_error_evidence(parsed);
561        }
562        let inband_error = if is_result_frame { std::mem::take(&mut self.inband_text) } else { String::new() };
563        // A quota or sign-in failure is stored, and a successful turn's
564        // stale failure cleared, before the turn's end is published
565        // (`on_turn_end`): whoever reacts to that end (the Supervisor) reads the
566        // block's state from them (#5389). The steps after
567        // leave both alone, except to restore an older turn's flushed
568        // failure.
569        let result_is_error = is_result_frame && parsed.get("is_error").and_then(|v| v.as_bool()) == Some(true);
570        let early_failure = (result_is_error && self.inner_read.lock().unwrap().shutdown_generation != Some(self.my_generation_read))
571            .then(|| crate::agents::failure::classify(None, None, &inband_error, Some(parsed)))
572            .filter(|f| matches!(f.code, crate::agents::failure::FailureClass::UsageLimit | crate::agents::failure::FailureClass::Auth));
573        if let Some(failure) = &early_failure {
574            surface_failure(&self.block_id_read, failure, self.broker_read.as_deref(), &self.mstore_read, &self.event_bus_read);
575        } else if is_result_frame && !result_is_error {
576            core::persist_last_failure(&self.block_id_read, None, &self.mstore_read, &self.event_bus_read);
577            if let Some(mstore) = &self.mstore_read {
578                crate::backend::route_credits::turn_succeeded(mstore, self.broker_read.as_ref(), &self.block_id_read);
579            }
580            crate::backend::limit_evidence::clean_turn(&self.block_id_read, &self.mstore_read, &self.event_bus_read);
581        }
582        FrameVerdict { is_result_frame, inband_error, early_failure }
583    }
584
585    /// A turn ended: free what waited on it, apply a deferred restart, and publish the flip.
586    fn on_turn_end(&mut self, parsed: &serde_json::Value) {
587        // The first turn on an expired identity is over: others waiting on its refresh may go. Not a
588        // replaced process's late frame, which would free its replacement's hold.
589        if self.inner_read.lock().unwrap().spawn_generation == self.my_generation_read {
590            crate::identity::token_warmup::release(&self.block_id_read);
591        }
592        // A runtime-config change (model/effort/permission)
593        // arrived mid-turn and was deferred rather than
594        // killing this turn — see
595        // `request_restart_when_idle`. The turn is over now,
596        // so stop the process. Its kill arm eager-resumes the
597        // replacement at once (`respawn_after_config_restart`),
598        // which rebuilds `cli_args` from block meta, so the
599        // new flags take effect then. It used to wait for "the
600        // next message", which a jekt never is.
601        // Not `poison_resume` and not a user Stop — the
602        // session id is retained, so the respawn `--resume`s
603        // the same conversation.
604        // `set_active_turn(false)` happens under `inner` so it
605        // serializes with `request_restart_when_idle`'s own
606        // check — see that method for the interleaving this
607        // closes. `restart_pending` is committed in the SAME
608        // acquisition so no send can slip into `DeliverDirect`
609        // between the decision and the kill.
610        // Whether the deferred restart may apply: see
611        // `turn_boundary_locked`.
612        // The first turn on a changed model route or model decides the change: refused, the agent is put back and
613        // restarted on the place it came from, by the same deferred restart a runtime-config change uses. It is asked
614        // for before the boundary, which commits it in the acquisition that ends the turn.
615        if self.settle_route_trial(parsed) {
616            PersistentSubprocessController::restart_at_boundary_locked(&mut self.inner_read.lock().unwrap());
617        }
618        let boundary = PersistentSubprocessController::turn_boundary_locked(
619            &mut self.inner_read.lock().unwrap(),
620            &self.health_read,
621            &self.block_id_read,
622            self.my_generation_read,
623            Some(crate::backend::blockcontroller::health::PassStats::from_result_frame(parsed)),
624        );
625        // `None`: this reader's process has been replaced. Its
626        // `result` ends nothing the current process is doing,
627        // so it must not idle or restart that process (codex
628        // P1 on #3562).
629        let boundary_is_current = boundary.is_some();
630        let deferred_restart = boundary.unwrap_or(false);
631        // The model can change under a running process (the CLI
632        // falls back to another model when one is overloaded), so
633        // ask again at every turn boundary. Cheap, and not for a
634        // process that is about to be restarted anyway.
635        if boundary_is_current && !deferred_restart {
636            let ask = self.inner_read.lock().unwrap().settings_readback;
637            if ask {
638                PersistentSubprocessController::push_stdin(&self.inner_read, crate::backend::agent_runtime::settings_request_line());
639                // The threshold moves with the model (a fallback
640                // model, a /model switch applied in place).
641                PersistentSubprocessController::push_stdin(
642                    &self.inner_read,
643                    crate::backend::agent_context_usage::context_usage_request_line(),
644                );
645            }
646        }
647        if deferred_restart {
648            tracing::info!(
649                block_id = %self.block_id_read,
650                "turn ended — applying the deferred runtime-config restart"
651            );
652            // Marked as a restart, not a plain stop, so the
653            // kill arm brings the replacement up itself: the
654            // next message is often a jekt, and automated
655            // delivery never spawns.
656            if let Some(ctrl) = self.self_ref_read.as_ref().and_then(|w| w.upgrade()) {
657                ctrl.stop_for_config_restart();
658            }
659        }
660        // Publish the flip so the Swarm view's live
661        // ControllerStatus subscription reflects "turn
662        // ended" immediately instead of only on the next
663        // unrelated status change (or process exit) — see
664        // send_message's matching publish_status() call for
665        // the turn-start side of this pair.
666        // The turn ended: any "needs your input" for it is
667        // moot (answered, or abandoned by a new message / the
668        // turn finishing). srv never drains
669        // `pending_questions` on its own, so this boundary is
670        // the reliable "resolved" signal.
671        self.publish_turn_ended(boundary_is_current);
672        self.reconcile_subagents();
673    }
674
675    fn publish_turn_ended(&self, boundary_is_current: bool) {
676        if let (Some(broker), true) = (self.broker_read.as_ref(), boundary_is_current) {
677            if let Some(r) = crate::backend::notify::router::get(broker) {
678                r.resolve_nonblocking(&self.block_id_read, crate::backend::notify::policy::Family::Input);
679            }
680        }
681        if let (Some(broker), true) = (self.broker_read.as_ref(), boundary_is_current) {
682            let status = {
683                let locked = self.inner_read.lock().unwrap();
684                super::super::agent_runtime_status(
685                    &self.block_id_read,
686                    locked.status_version,
687                    &locked.proc_status,
688                    locked.proc_exit_code,
689                    false,
690                )
691            };
692            super::super::publish_controller_status(broker, &status);
693        }
694    }
695
696    fn reconcile_subagents(&self) {
697        // SPEC_SUBAGENT_LIVE_RECONCILIATION_AND_RETIRE_2026_07_20
698        // Phase A: reconcile any subagent still Active for this
699        // block the instant its turn ends, not just at the next
700        // pane reopen — closes SPEC_SUBAGENT_LIFECYCLE_
701        // RECONCILIATION_2026_07_12.md's Open Question 1. A
702        // subagent runs inside the parent's own CLI process (a
703        // Task-tool call is synchronous within the parent's
704        // turn), so this is the same "turn ended" signal
705        // scan_session_subagents already reconciles against at
706        // reopen — just fired live instead of waiting.
707        // `global()` is `None` in tests that don't call
708        // `subagent_watcher::set_global` — a safe no-op, same
709        // pattern `process_tracker::registry` already uses.
710        //
711        // On a BLOCKING thread, not this one. Reconciliation
712        // used to be a pure in-memory status flip under a
713        // mutex (O(1)), but as of the completion-detection
714        // fix (#3007) it reads the parent transcript from
715        // disk — routinely tens of MB, plus per-line JSON
716        // parsing — to decide whether each member actually
717        // returned. Doing that inline would block a tokio
718        // worker thread for the whole read, and this fires on
719        // EVERY turn-end, so several blocks finishing at once
720        // could stall the runtime (reagent P1 on #3007).
721        //
722        // Fire-and-forget: the result is a status correction
723        // broadcast to whoever's listening, not something this
724        // stdout-reader task consumes, so there is nothing to
725        // await. The backfill call site (`scan_session_
726        // subagents`) needs no equivalent — it already runs in
727        // a blocking context that walks up to 200 files.
728        let session_id_snapshot = self.inner_read.lock().unwrap().session_id.clone();
729        if let Some(sid) = session_id_snapshot {
730            if let Some(watcher) = subagent_watcher::global() {
731                let block_id = self.block_id_read.clone();
732                tokio::task::spawn_blocking(move || {
733                    watcher.reconcile_stale_subagents(&block_id, &sid);
734                });
735            }
736        }
737    }
738
739    /// Adopt the session id the frame carries, and act on what that settles for resume tracking.
740    fn capture_session_id(
741        &mut self,
742        parsed: &serde_json::Value,
743        is_result_frame: bool,
744        flushed_failure_this_tick: &mut bool,
745    ) {
746        if let Some(sid) = parsed.get(&self.session_id_field).and_then(|v| v.as_str()) {
747            let sid_string = sid.to_string();
748            // reagentx P0 on PR #2371: a genuinely
749            // successful terminal result (is_result_frame
750            // && !is_error, which is guaranteed true here
751            // since is_error_result already excluded the
752            // failing case) is the ONLY unambiguous proof
753            // that resuming THIS sid actually worked —
754            // any earlier frame (e.g. a "system"/init
755            // frame) echoes the same attempted sid
756            // regardless of whether the resume goes on to
757            // fail, per persistent_resume::update's own
758            // handling of `SessionCaptured`.
759            let is_confirmed_success = is_result_frame;
760            // See PersistentInner::try_capture_session_id — refuses
761            // to (re-)adopt an id the stderr reader (`stderr_reader.rs`) already
762            // confirmed unreachable, whichever task wins the race.
763            let (should_capture, capture_effects, holds_current) = {
764                let mut inner = self.inner_read.lock().unwrap();
765                let (adopted, effects) = inner.try_capture_session_id(&sid_string, self.my_generation_read, is_confirmed_success);
766                (adopted, effects, inner.holds_current_session(&sid_string, self.my_generation_read))
767            };
768            if should_capture {
769                tracing::info!(
770                    block_id = %self.block_id_read,
771                    session_id = %sid_string,
772                    "persistent session ID captured"
773                );
774                core::persist_session_id(&self.block_id_read, &sid_string, &self.mstore_read, &self.event_bus_read);
775            }
776            let kept_relocated_id = super::segments::kept_relocated_id(
777                should_capture,
778                is_confirmed_success,
779                holds_current,
780                self.relocated_copy_read.is_some(),
781                self.forked_from_read.as_deref(),
782                &sid_string,
783            );
784            if should_capture {
785                super::segments::record_segment_session(&self.segment_read, &sid_string);
786                // The fork has its own session now; the copy it
787                // read from goes (spec §4.3 (3), I4).
788                if let Some(copy) = self.relocated_copy_read.take() {
789                    super::segments::settle_relocated_copy(&self.block_id_read, &copy, self.forked_from_read.as_deref(), &sid_string);
790                }
791            } else if kept_relocated_id {
792                // Kept under the attempted id, the copy is the live
793                // session: recorded only while it is still this
794                // spawn's, never a replacement's at the same path.
795                if let Some(copy) = self.relocated_copy_read.take() {
796                    if super::segments::settle_relocated_copy(&self.block_id_read, &copy, self.forked_from_read.as_deref(), &sid_string) {
797                        super::segments::record_segment_session(&self.segment_read, &sid_string);
798                    }
799                }
800            }
801            // reagentx P0 on PR #2373: resolving tracking
802            // here can legitimately flush a held-back
803            // error line from an earlier turn on this
804            // same still-alive generation — execute it,
805            // same as every other `ResumeEffect` call
806            // site in this module. `SessionCaptured` can
807            // also now resolve tracking outright and
808            // produce an `EmitSessionOutcome` (see
809            // `persistent_resume::update`'s own handling,
810            // SPEC_AGENT_PANE_HISTORY_ALIGNMENT_2026_08_05.md
811            // §2.1) — handled explicitly in this match; anything
812            // else falls to the catch-all, kept exhaustive
813            // rather than assuming the effect set never
814            // grows again.
815            self.apply_capture_effects(capture_effects, flushed_failure_this_tick);
816        }
817    }
818
819    fn apply_capture_effects(
820        &mut self,
821        capture_effects: Vec<persistent_resume::ResumeEffect>,
822        flushed_failure_this_tick: &mut bool,
823    ) {
824        for effect in capture_effects {
825            match effect {
826                persistent_resume::ResumeEffect::EmitSessionOutcome {
827                    outcome,
828                    attempted_sid,
829                    actual_sid,
830                } => {
831                    // A fork reports a new id by design: that is
832                    // the resume succeeding, not a fresh start.
833                    let outcome = super::segments::forked_outcome(
834                        outcome,
835                        self.forked_from_read.as_deref(),
836                        &attempted_sid,
837                        actual_sid.as_deref(),
838                    );
839                    // The retry (if any led here) is now resolved one
840                    // way or the other — clear "Reconnecting…". A no-op
841                    // publish (still fine) when this outcome came from a
842                    // plain first-time resume that was never retried.
843                    publish_resume_retry_status(&self.broker_read, &self.block_id_read, "resolved");
844                    // A recovery scan can turn an
845                    // already-disclosed resume failure
846                    // into a genuine resume — retract the
847                    // banner so it can't contradict the
848                    // `resumed` divider appended just
849                    // after it. See
850                    // `session_recovery::clear_resume_failed`.
851                    if matches!(outcome, persistent_resume::SessionOutcome::Resumed) {
852                        if let Some(ref store) = self.mstore_read {
853                            super::super::session_recovery::clear_resume_failed(
854                                store,
855                                &self.event_bus_read,
856                                &self.block_id_read,
857                            );
858                        }
859                    }
860                    if let Some(ref broker) = self.broker_read {
861                        let line = session_outcome_line(outcome, attempted_sid, actual_sid);
862                        super::super::shell::handle_append_block_file(
863                            broker,
864                            &self.block_id_read,
865                            PERSISTENT_OUTPUT_SUBJECT,
866                            line.as_bytes(),
867                            self.filestore_read.as_ref(),
868                            crate::backend::agent_admission::fenced_zone(self.global_output_zone.as_deref(), &self.record_fence),
869                        );
870                    }
871                }
872                persistent_resume::ResumeEffect::FlushErrorLine(line) => {
873                    if let Some(ref broker) = self.broker_read {
874                        super::super::shell::handle_append_block_file(
875                            broker,
876                            &self.block_id_read,
877                            PERSISTENT_OUTPUT_SUBJECT,
878                            line.as_bytes(),
879                            self.filestore_read.as_ref(),
880                            crate::backend::agent_admission::fenced_zone(self.global_output_zone.as_deref(), &self.record_fence),
881                        );
882                    }
883                    // reagentx P2 on PR #2421: this flushes
884                    // an earlier held-back turn's error,
885                    // finally confirmed final now that
886                    // session-id tracking resolved — must
887                    // get the same classify/persist/publish
888                    // treatment as the identical
889                    // FlushErrorLine handled at the
890                    // process-exit arm, or this turn's
891                    // failure silently loses its recovery
892                    // banner. No exit code exists for this
893                    // now-superseded turn.
894                    if surface_error_line(
895                        &self.block_id_read,
896                        None,
897                        &line,
898                        self.broker_read.as_deref(),
899                        &self.mstore_read,
900                        &self.event_bus_read,
901                    ) {
902                        *flushed_failure_this_tick = true;
903                    }
904                }
905                other => {
906                    tracing::warn!(
907                        block_id = %self.block_id_read,
908                        effect = ?other,
909                        "unexpected ResumeEffect from a SessionCaptured event"
910                    );
911                }
912            }
913        }
914    }
915
916    /// Hold an error result back while a stale `--resume` retry could still be confirmed.
917    /// Returns whether this line is held back.
918    fn track_error_result(&mut self, line: &str, flushed_failure_this_tick: &mut bool) -> bool {
919        // Issue #2368: this generation's resume tracking
920        // (`persistent_resume::ResumeState`) decides whether
921        // this line is still a retry candidate — if it has
922        // already resolved (a session id was captured by `capture_session_id` or
923        // on an earlier line, or this generation never
924        // attempted an untrusted `--resume`), `update()`
925        // returns a `PersistImmediately` effect and today's
926        // immediate-persist behavior is unchanged; otherwise
927        // the line is held back pending the retry decision at
928        // process exit.
929        //
930        // reagentx P2 on PR #2373: hold-back is now decided
931        // from the RESULTING state, not `effects.is_empty()`
932        // — a still-tracking result can now ALSO carry a
933        // `PersistImmediately` effect for a SUPERSEDED
934        // held-back line from an earlier turn on this same
935        // generation (a second `is_error:true` while tracking
936        // is undecided means the first was a separate,
937        // already-settled turn's error). That effect must be
938        // flushed here explicitly; when NOT still tracking,
939        // any effect returned is THIS exact line's own
940        // `PersistImmediately`, already handled by the
941        // unchanged fallthrough (the append in `handle_line`) — executing it here too
942        // would double-persist it.
943        let (effects, still_tracking) = {
944            let mut inner = self.inner_read.lock().unwrap();
945            let effects = inner.apply_resume_event(persistent_resume::ResumeEvent::ErrorResultLine {
946                generation: self.my_generation_read,
947                line: format!("{}\n", line),
948            });
949            let still_tracking = matches!(
950                &inner.resume,
951                persistent_resume::ResumeState::AwaitingOutcome { generation, .. }
952                    if *generation == self.my_generation_read
953            ) || matches!(
954                &inner.resume,
955                persistent_resume::ResumeState::ConfirmedRetry { generation, .. }
956                    if *generation == self.my_generation_read
957            );
958            (effects, still_tracking)
959        };
960        if still_tracking {
961            for effect in effects {
962                match effect {
963                    persistent_resume::ResumeEffect::PersistImmediately(old_line)
964                    | persistent_resume::ResumeEffect::FlushErrorLine(old_line) => {
965                        if let Some(ref broker) = self.broker_read {
966                            super::super::shell::handle_append_block_file(
967                                broker,
968                                &self.block_id_read,
969                                PERSISTENT_OUTPUT_SUBJECT,
970                                old_line.as_bytes(),
971                                self.filestore_read.as_ref(),
972                                crate::backend::agent_admission::fenced_zone(self.global_output_zone.as_deref(), &self.record_fence),
973                            );
974                        }
975                        // reagentx P1 on PR #2421 (round 2):
976                        // this is a SEPARATE, already-settled
977                        // older turn's error, superseded by
978                        // the current still-tracking line —
979                        // now confirmed final, same as the
980                        // other three FlushErrorLine/
981                        // PersistImmediately call sites this
982                        // PR wired up. `is_error_result` is
983                        // true for the rest of this tick, so
984                        // this can never collide with the
985                        // clear-on-success step in `surface_turn_outcome`.
986                        if surface_error_line(
987                            &self.block_id_read,
988                            None,
989                            &old_line,
990                            self.broker_read.as_deref(),
991                            &self.mstore_read,
992                            &self.event_bus_read,
993                        ) {
994                            *flushed_failure_this_tick = true;
995                        }
996                    }
997                    other => {
998                        tracing::warn!(
999                            block_id = %self.block_id_read,
1000                            effect = ?other,
1001                            "unexpected ResumeEffect from a still-tracking ErrorResultLine event"
1002                        );
1003                    }
1004                }
1005            }
1006        }
1007        still_tracking
1008    }
1009
1010    /// Classify and surface a final error result, or clear a stale failure on a good one.
1011    #[allow(clippy::too_many_arguments)]
1012    fn surface_turn_outcome(
1013        &mut self,
1014        parsed: &serde_json::Value,
1015        is_result_frame: bool,
1016        is_error_result: bool,
1017        hold_back_for_resume_retry: bool,
1018        no_early_failure: bool,
1019        inband_error: &str,
1020        flushed_failure_this_tick: bool,
1021    ) {
1022        // Classify + surface a genuine, non-retried error result
1023        // (429/overloaded/auth/etc.) to the pane's failure-recovery
1024        // UI — SPEC_PERSISTENT_CONTROLLER_FAILURE_CLASSIFICATION.
1025        // Gated on `!hold_back_for_resume_retry`: when the stale-
1026        // `--resume` machinery (`track_error_result`) is still tracking this exact
1027        // error as a live retry candidate, it must stay invisible
1028        // to the user (per its own "must never reach the user"
1029        // invariant at `process_waiter.rs`'s ProcessExited/FireRetry arm) —
1030        // classify() only runs once this error is confirmed final.
1031        if is_error_result {
1032            // A failed turn ends without the hint, so a finished task stays no boundary.
1033            crate::backend::context_reading::clear_task_boundary(&self.block_id_read);
1034        }
1035        if is_error_result && !hold_back_for_resume_retry && no_early_failure {
1036            let failure = crate::agents::failure::classify(None, None, inband_error, Some(parsed));
1037            surface_failure(&self.block_id_read, &failure, self.broker_read.as_deref(), &self.mstore_read, &self.event_bus_read);
1038        } else if is_result_frame && !is_error_result && !flushed_failure_this_tick {
1039            // reagentx P1 on PR #2421: unlike host_spawn.rs, this
1040            // controller never exits between turns, so nothing
1041            // else ever clears a previously recorded failure —
1042            // once one rate-limit/overloaded error was persisted,
1043            // the pane's onMount seed logic kept re-showing that
1044            // stale banner on every future reload, even after
1045            // many later successful turns. A genuinely successful
1046            // terminal result on this still-alive process is the
1047            // signal that it's stale. persist_last_failure is a
1048            // no-op when there's nothing to clear, so this is
1049            // cheap on the (overwhelmingly common) already-clear
1050            // path. Skipped when `apply_capture_effects`
1051            // just persisted a freshly-flushed OLDER failure this
1052            // same tick — that state must survive, not be
1053            // immediately wiped by this frame's own success.
1054            core::persist_last_failure(&self.block_id_read, None, &self.mstore_read, &self.event_bus_read);
1055            crate::backend::limit_evidence::clean_turn(&self.block_id_read, &self.mstore_read, &self.event_bus_read);
1056            // A completed turn is when the agent's running
1057            // summary may be due for an update. Background, and
1058            // a no-op unless enough happened since the last one
1059            // (SPEC_DURABLE_CONVERSATION_MEMORY_2026_09_23.md §4.4).
1060            crate::backend::continuity_state::after_successful_turn(
1061                self.mstore_read.clone(),
1062                self.block_id_read.clone(),
1063            );
1064            // A large context when the work may continue: one note
1065            // for the next turn (SPEC_AGENT_SELF_COMPACTION §3.5).
1066            crate::backend::context_reading::hold_turn_end_hint(&self.block_id_read, true);
1067        }
1068    }
1069}