Skip to main content

agentmux_srv_core/backend/blockcontroller/persistent/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! PersistentSubprocessController: manages agent CLI as a long-running process
5//! with bidirectional NDJSON streaming via stdin/stdout.
6//!
7//! Architecture:
8//!   A single CLI process is spawned on first message and kept alive for the
9//!   entire session. User messages are written as NDJSON lines to stdin without
10//!   closing it. This enables mid-turn input (redirecting the agent while it
11//!   is still processing).
12//!
13//! State machine:
14//!   INIT ─(first message)─> RUNNING ─(idle between turns)─> RUNNING
15//!   RUNNING ─(kill/stop)─> DONE
16//!   RUNNING ─(process crash)─> DONE (auto-restart possible via session_id)
17//!
18//! I/O model (3 async tasks per session):
19//! 1. stdin_writer: mpsc channel → process stdin (NDJSON lines)
20//! 2. stdout_reader: process stdout → .jsonl persistence + MPS blockfile events
21//! 3. process_waiter: wait for exit, update status
22//!
23//! Module layout (split 2026-09-22; one `impl PersistentSubprocessController`
24//! block per file, all private methods `pub(super)`):
25//!   - `mod.rs`          — types, shared helpers, construction, `Controller` impl
26//!   - `status.rs`       — runtime status snapshot/publication and heartbeat
27//!   - `eager_resume.rs` — spawn-on-construction when a session id is on file
28//!   - `queue.rs`        — `send_message`, spawn claim, queue drain/replay
29//!   - `resume_retry.rs` — stale-`--resume` recovery effects and retry batch
30//!   - `input.rs`        — user messages, question answers, tool decisions, stdin
31//!   - `spawn.rs`        — `spawn_process`: builds the command, spawns, wires the tasks
32//!   - `stderr_reader.rs`, `stdout_reader.rs`, `process_waiter.rs`
33//!                       — the bodies of those per-session I/O tasks
34//!   - `lifecycle.rs`    — stop/restart, `session_id`, `needs_spawn`
35//!   - `tests/`          — one file per former inline test module
36
37use crate::backend::message_origin::{MessageOrigin, RecordOrigin};
38use std::collections::{HashMap, VecDeque};
39use std::sync::atomic::{AtomicU64, Ordering};
40use std::sync::{Arc, Mutex};
41
42use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
43use tokio::sync::mpsc;
44
45use super::{
46    BlockControllerRuntimeStatus, BlockInputUnion, Controller, SendOutcome, STATUS_DONE,
47    STATUS_INIT, STATUS_RUNNING,
48};
49use super::core;
50use super::health::TurnActivityTracker;
51use super::persistent_resume;
52use outcome_line::{session_outcome_line, session_outcome_line_with};
53use crate::backend::eventbus::EventBus;
54use crate::backend::storage::filestore::FileStore;
55use crate::backend::storage::store::Store;
56use crate::backend::subagent_watcher;
57use crate::backend::mps;
58
59/// MPS file subject name for persistent subprocess output.
60pub const PERSISTENT_OUTPUT_SUBJECT: &str = "output";
61
62pub const BLOCK_CONTROLLER_PERSISTENT: &str = "persistent";
63
64/// The one spawn refusal that is a *decision*, not a failure: `--resume
65/// <sid>` was asked for while another pane still holds (or is still
66/// closing) that same conversation — `session_held_elsewhere`. Built here
67/// so that `is_held_elsewhere_error` is checked against the same text
68/// `spawn_process` actually returns, rather than a second copy that could
69/// drift; `tests/reopen_guard.rs` pins the wording users see.
70pub fn held_elsewhere_error(other: &str, closing: bool) -> String {
71    if closing {
72        format!("This conversation's previous process (block {other}) is still shutting down. Try again in a few seconds.")
73    } else {
74        format!(
75            "This conversation is already open in another pane (block {other}). Close it there, or switch to it, instead of opening a second copy."
76        )
77    }
78}
79
80/// Did `spawn_process` refuse because of `session_held_elsewhere`? The
81/// answer decides whether a caller may fall back to a FRESH spawn: for any
82/// other failure a blank session is a reasonable recovery, but for this one
83/// it silently hands the user's accepted prompt to a new conversation
84/// while the real one is open next door — exactly what the guard exists to
85/// prevent (codex P1 on PR #3551).
86pub fn is_held_elsewhere_error(err: &str) -> bool {
87    err.starts_with("This conversation's previous process (block ")
88        || err.starts_with("This conversation is already open in another pane (block ")
89}
90
91/// What the process-waiter task's kill arm is asked to do.
92#[derive(Debug, Clone, Copy)]
93enum KillRequest {
94    /// Kill now.
95    Force,
96    /// Close stdin (EOF), wait for the process to exit until the deadline,
97    /// then kill.
98    Graceful(std::time::Instant),
99}
100
101/// The Claude control-protocol interrupt
102/// (docs/specs/SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md). Ends the turn in
103/// progress — measured at ~2s, with `result: error_during_execution` — while
104/// leaving the process and session alive (pane-close spec §5.1).
105fn interrupt_control_request_line() -> String {
106    serde_json::json!({
107        "type": "control_request",
108        "request_id": format!("agentmux-shutdown-{}", uuid::Uuid::new_v4()),
109        "request": { "subtype": "interrupt" },
110    })
111    .to_string()
112}
113
114/// Draws the next process-wide registration nonce (≥ 1) for a persistent
115/// spawn's muxbus/registry registrations — see the doc comment at the
116/// `my_registration_nonce` binding in `spawn_process` for why this is a
117/// srv-wide counter rather than the controller-local spawn generation
118/// (codex P1 on PR #2500: generations restart per controller instance
119/// and can collide across a `resync_controller` replacement).
120fn next_registration_nonce() -> u64 {
121    static NEXT_REGISTRATION_NONCE: AtomicU64 = AtomicU64::new(0);
122    NEXT_REGISTRATION_NONCE.fetch_add(1, Ordering::Relaxed) + 1
123}
124
125/// Should a spawn that attached NO `--resume` disclose itself as a fresh
126/// start (subject to the caller also confirming prior history actually
127/// exists — see `has_prior_transcript`)?
128///
129/// SPEC_AGENT_PANE_HISTORY_ALIGNMENT_2026_08_05.md §2.1 deliberately left
130/// this case unreported, reasoning that a spawn with no session id has
131/// "nothing to lose". That's true for a brand-new agent and false for the
132/// case `docs/status/STATUS_CROSS_CHANNEL_RESUME_STALE_SESSION_ID_2026_08_20.md`
133/// recorded: a long-lived named agent opened in a fresh channel whose shared
134/// registry pointer is empty gets no `--resume` at all, so the CLI never
135/// errors, `persistent_resume` never tracks anything, and no outcome is ever
136/// emitted — while the pane renders the entire prior conversation through
137/// `blockfile.rs`'s cross-channel read fallback. That is exactly the silent
138/// disagreement between "what the pane shows" and "what the model has" that
139/// `EmitSessionOutcome` exists to prevent.
140///
141/// `generation == 1` restricts this to a controller's FIRST spawn. Later
142/// generations also spawn without `--resume`, but each already has its own
143/// disclosure or deliberately has none: `retry_after_resume_failure`'s
144/// no-recovery-candidate path emits `Fresh` itself, and
145/// `respawn_once_for_leftover_queue` restarts a session whose fresh-vs-resumed
146/// status was decided on an earlier generation. Only a first spawn can be the
147/// "pane just opened onto history this process never had" case.
148///
149/// Kept a pure free function (the FileStore lookup stays at the call site) so
150/// the gate is unit-testable without a controller or a spawned process.
151fn fresh_start_needs_disclosure(attempted_resume_sid: Option<&str>, generation: u64) -> bool {
152    attempted_resume_sid.is_none() && generation == 1
153}
154
155/// How much of a transcript's tail `find_continuation_session_id` reads. The
156/// provider stamps its session id on every stream event, so the last few
157/// events suffice; a long-lived agent's transcript runs to many MB.
158const CONTINUATION_TAIL_BYTES: i64 = 256 * 1024;
159
160/// The last non-empty `field` on a complete JSON line of `tail`.
161/// `starts_mid_line`: `tail` was cut from a longer file, so its first line is
162/// a fragment and is dropped.
163pub(crate) fn last_session_id_in_stream(tail: &[u8], starts_mid_line: bool, field: &str) -> Option<String> {
164    let text = String::from_utf8_lossy(tail);
165    let skip = usize::from(starts_mid_line);
166    let lines: Vec<&str> = text.split('\n').skip(skip).collect();
167    lines.into_iter().rev().find_map(|line| {
168        let v: serde_json::Value = serde_json::from_str(line.trim()).ok()?;
169        let sid = v.get(field)?.as_str()?.trim();
170        (!sid.is_empty()).then(|| sid.to_string())
171    })
172}
173
174/// Publish a `mps::EVENT_AGENT_RESUME_RETRY` status ping — a free function
175/// (not a method) for the same reason `session_outcome_line` above is one:
176/// callable from the stdout-reader/process-waiter match arms, which only
177/// hold `_read`/`_wait`-suffixed clones, not `&self`. `status` is `"retrying"`
178/// (set when a stale `--resume` is detected and a retry/recovery attempt is
179/// about to fire) or `"resolved"` (set the moment the retry's outcome —
180/// Fresh or Resumed — is actually known). See
181/// `docs/status/STATUS_STALE_RESUME_LIVE_REPRO_AND_FIX_PLAN_2026_08_23.md` §6.2.
182/// No-ops if `broker` is `None` (tests / non-wired controllers), same
183/// posture as every other best-effort MPS publish in this file.
184fn publish_resume_retry_status(broker: &Option<Arc<mps::Broker>>, block_id: &str, status: &str) {
185    let Some(broker) = broker else { return };
186    let payload = crate::backend::mps_events::ResumeRetryEvent {
187        status: status.to_string(),
188        started_at: (status == "retrying").then(|| chrono::Utc::now().to_rfc3339()),
189    };
190    broker.publish_event::<crate::backend::mps_events::AgentResumeRetry>(
191        &payload,
192        vec![format!("block:{}", block_id)],
193        // `persist: 2`, not 1 — `Broker::persist_event` trims history down
194        // to exactly this many MOST RECENT events per (event, scope): a
195        // bare `persist: 1` would let the "resolved" publish immediately
196        // evict "retrying" from history, so a pane that (re)subscribes in
197        // the narrow window right after resolution sees only "resolved"
198        // with no record a retry ever happened — harmless for the simple
199        // "currently reconnecting?" check, but makes this event's own
200        // history useless for anything else. 2 keeps the latest
201        // retrying→resolved pair together; a later cascaded "retrying"
202        // still correctly evicts the OLDER pair's "retrying", not this
203        // one's "resolved".
204        2,
205    );
206}
207
208/// Resolve the muxbus address (the agent's display name) from a spawn env map.
209/// `AGENTMUX_AGENT_ID` (= `agent.name`, set at block creation) is canonical;
210/// `WAVEMUX_AGENT_ID` is the legacy fallback. Returns `None` — i.e. not
211/// muxbus-addressable — when neither is present (a non-agent persistent block).
212fn muxbus_agent_id_from_env(env: &HashMap<String, String>) -> Option<String> {
213    super::agent_id_from_env(|key| env.get(key).map(String::as_str))
214}
215
216/// Configuration for spawning the persistent process.
217/// `PartialEq` is derived for `persistent_resume::RetryPayload`'s own
218/// derive and its exhaustive unit tests — not used elsewhere in this
219/// file itself.
220#[derive(Debug, Clone, PartialEq)]
221pub struct PersistentSpawnConfig {
222    pub cli_command: String,
223    pub cli_args: Vec<String>,
224    pub working_dir: String,
225    pub env_vars: HashMap<String, String>,
226    pub session_id_field: String,
227    /// Resume flag for this provider (e.g. "--resume"), read from
228    /// `agent:resume_flag` meta. Empty = provider has no simple-flag resume.
229    /// Mirrors `SubprocessSpawnConfig::resume_flag` so a respawn (after a
230    /// runtime/model change or the picker reattach path) continues the same
231    /// conversation instead of starting fresh.
232    pub resume_flag: String,
233    /// Session id to hydrate `inner.session_id` with BEFORE spawning, when the
234    /// controller hasn't captured one yet (fresh controller after a forced
235    /// restart, or picker reattach). Read from `agent:sessionid` meta. With a
236    /// non-empty `resume_flag` this makes `--resume <sid>` land on the respawn.
237    pub session_id: String,
238    /// Echoed back as `agent-message-accepted` so the frontend can promote the
239    /// pending entry. Matches `CommandAgentInputData.message_id` on the AgentInput
240    /// command; absent for legacy callers.
241    pub message_id: Option<String>,
242}
243
244/// Inner state protected by mutex.
245struct PersistentInner {
246    proc_status: String,
247    proc_exit_code: i32,
248    status_version: i32,
249    session_id: Option<String>,
250    /// A `--resume` id the CLI has confirmed (via stderr) it can't find under
251    /// the current config dir. The stdout reader echoes back whatever
252    /// `--resume` value it was given as its first line REGARDLESS of whether
253    /// resume actually succeeds, racing the stderr reader's own clear of
254    /// `session_id` — this stops that race from re-adopting a known-dead id.
255    /// Never reset back to `None`: a genuinely fresh session id (a new CLI-
256    /// generated UUID) will never equal this one, so a stale poison value
257    /// is permanently inert rather than something that needs clearing.
258    resume_poisoned: Option<String>,
259    /// The copy the resume gate relocated for the next spawn to
260    /// `--resume … --fork-session` from
261    /// (SPEC_RESUME_GATE_AND_SAME_IDENTITY_CONTINUATION_2026_09_25.md §4.3).
262    /// Taken by that spawn; removed if it ends up resuming nothing.
263    fork_copy: Option<crate::backend::continuity_relocate::Relocated>,
264    /// The next spawn resumes with `--fork-session` (a relocation, or a
265    /// session that grew outside AgentMux, spec §4.4). Taken by that spawn.
266    fork_next: bool,
267    /// Set when a forced controller resync (a `/model`, `/effort` or
268    /// `/permission-mode` change — see `frontend/.../runtime-apply.ts`) lands
269    /// while a turn is in flight. The restart is DEFERRED to the end of that
270    /// turn instead of killing the process mid-turn.
271    ///
272    /// Killing it was the old behaviour and it silently destroyed the user's
273    /// in-flight message: `stop_process` records a `StopRequested`, which the
274    /// resume state machine treats as an explicit user stop and therefore
275    /// suppresses the retry; `remove_controller_entry_only` then discards the
276    /// controller (and its queue) outright; and the replacement controller
277    /// "spawns on first message", so nothing resumed. The message had already
278    /// been written to the dead process's stdin, so no queue entry survived to
279    /// replay. Net effect: the turn vanished with no response and no error —
280    /// the pane simply went quiet. Diagnosed live on AgentX, 2026-08-28.
281    ///
282    /// Deferring is correct rather than merely safer: model/effort flags are
283    /// baked in at spawn, so they could not have applied to the running turn
284    /// anyway. Waiting until it ends costs nothing and loses nothing.
285    restart_when_idle: bool,
286    /// A deferred restart has COMMITTED — `stop_process` has been called and
287    /// the process is on its way out, but `stdin_tx` is still live because
288    /// `stop_process` only sends on `kill_tx` and leaves the writer channel
289    /// alone until the process actually exits.
290    ///
291    /// Without this, `decide_send_action` would see a live `stdin_tx` and take
292    /// `DeliverDirect` for any message arriving in that window — writing it
293    /// into a process about to receive EOF, acknowledging it, and losing it
294    /// (codex P1 on PR #2858). The window is not hypothetical: the restart
295    /// fires exactly at turn end, which is precisely when the frontend flushes
296    /// its queued follow-ups.
297    ///
298    /// Set under the same lock that consumes `restart_when_idle`, cleared when
299    /// the replacement process spawns.
300    restart_pending: bool,
301    /// The runtime flags (model, effort, permission) in the argv of the process
302    /// that is running now; `None` when no process is. What the menu compares
303    /// its selection against: the menu shows what was asked for, this is what
304    /// the process was given. Set at spawn, cleared when the status leaves
305    /// "running" (`set_status`).
306    spawn_runtime: Option<crate::backend::agent_runtime::SpawnRuntime>,
307    /// What the running CLI itself reported using (`get_settings`'s `applied`):
308    /// the alias resolved to a concrete model, and the effort in force. `None`
309    /// until it answers, for a CLI that cannot, and when no process runs.
310    effective_runtime: Option<crate::backend::agent_runtime::EffectiveRuntime>,
311    /// Whether the running process takes control requests, so it is asked
312    /// `get_settings` and `get_context_usage` (set at spawn: a
313    /// control-protocol launch).
314    settings_readback: bool,
315    /// The last `get_context_usage` answer published for the current process,
316    /// so an unchanged answer at each turn boundary isn't re-broadcast.
317    /// Cleared at spawn.
318    context_usage: Option<crate::backend::agent_context_usage::AgentContextUsage>,
319    /// A kill has been requested for the current process (`request_stop_on`).
320    /// `stdin_tx` stays live until it actually exits. Writing an automated
321    /// message then would put it into the dying process and lose it (codex
322    /// P2 on #3562 for `stop`, and the same window on the Stop button).
323    /// `try_write_stdin_locked` refuses while this is set, so the message
324    /// stays queued for the next process.
325    ///
326    /// Set under the same lock as the kill request, cleared when the
327    /// replacement process spawns, exactly like `restart_pending`.
328    stop_pending: bool,
329    /// The spawn generation a deferred runtime-config restart is replacing:
330    /// set by `turn_boundary_locked` in the same acquisition that commits the
331    /// restart, so the old process's exit handler knows to bring the
332    /// replacement up itself once the process is gone.
333    ///
334    /// Without it the pane was left with no process until a human typed into
335    /// it: automated delivery (`send_user_message`) never spawns, and it waits
336    /// while `restart_pending` is set, so jekts queued forever (Korp on narko,
337    /// 2026-09-29; `docs/retro/RETRO_DEFERRED_RESTART_NEVER_RESPAWNS_2026_09_29.md`).
338    /// A restart is also a stop (`stop_pending`, `StopRequested`), so neither
339    /// of those can tell it apart from a user's Stop; this can. Every stop
340    /// request except the restart's own clears it, and nothing but the
341    /// boundary sets it, so an explicit Stop or a pane close landing anywhere
342    /// in the window is never undone by a respawn (#3990). It is consumed
343    /// only in the acquisition that installs the replacement's freshly
344    /// started child as the live process (`commit_restart_spawn_locked`).
345    config_restart_generation: Option<u64>,
346    /// The spawn claimed for a config restart's replacement, by generation
347    /// (`try_claim_eager_resume_spawn_for`). `spawn_process` re-checks the
348    /// restart token against it right before starting the child, so a Stop
349    /// during the (possibly slow) credential gate still cancels it.
350    restart_spawn_for: Option<u64>,
351    stop_watch: eager_resume::StopWatch,
352    /// This spawn generation's stale-`--resume` retry decision, plus any
353    /// held-back terminal error-result line — see
354    /// `persistent_resume::ResumeState`'s own doc comment for the full
355    /// design rationale. Replaces what used to be four separate fields
356    /// (`pending_resume_retry`, `confirmed_stale_resume_retry`,
357    /// `stop_requested_generation`, `pending_error_result_line`) mutated
358    /// directly by four independently-scheduled tasks racing on this same
359    /// mutex — that shape caused issue #2368 (and a live-reproduced
360    /// recurrence, agent "Marks", 2026-07-30) because no single owner
361    /// enforced valid transitions between them. Every mutation now goes
362    /// through `persistent_resume::update()`, a pure, exhaustively unit
363    /// tested `(state, event) -> (state, effects)` function — still
364    /// called under this same mutex (no new concurrency primitive is
365    /// introduced), but as ONE call per event instead of several separate
366    /// field reads/writes that could observe each other mid-transition.
367    resume: persistent_resume::ResumeState,
368    /// True from the moment a caller commits to calling `spawn_process`
369    /// (in `send_message` or `retry_after_resume_failure`) until it has
370    /// delivered every message enqueued for that spawn — see
371    /// `pending_send_messages`. Checked and set together with
372    /// `stdin_tx.is_some()` under this same lock, in one acquisition —
373    /// reagentx P1 on PR #2360 (sixth review pass): `send_message`'s
374    /// `is_running()` check and its `spawn_process()` call used to be two
375    /// separate operations; a second concurrent `send_message` call (a
376    /// genuine second RPC, or a muxbus delivery) landing in the gap
377    /// between them could ALSO observe "not running" and independently
378    /// spawn a second child process, orphaning one (leaked, unkillable via
379    /// `stop_process`, unregistered from muxbus). Whichever caller sees
380    /// `stdin_tx.is_none() && !spawning_in_progress` first becomes the
381    /// sole spawner for this round; every other caller queues instead of
382    /// racing its own spawn.
383    ///
384    /// This also fully subsumes the earlier `spawn_epoch`/
385    /// `should_skip_own_delivery` mechanism (rounds 3-5 of this same PR):
386    /// that check existed only to catch a delivery landing in the window
387    /// between a caller's own `spawn_process` returning and its own
388    /// tail-end stdin write — a window that no longer exists, since
389    /// delivery now happens as part of the same atomic spawn-claim, before
390    /// the lock is released (see `release_spawn_claim_and_drain_queue`).
391    spawning_in_progress: bool,
392    /// Messages queued while `spawning_in_progress` was `true` — includes
393    /// the enqueuing caller's own message when it became the spawner (see
394    /// `SendAction::BecomeSpawner`), so the post-spawn drain uses one
395    /// uniform delivery path regardless of whether a message triggered the
396    /// spawn or arrived while someone else's spawn was already in flight.
397    /// Drained by `release_spawn_claim_and_drain_queue`.
398    pending_send_messages: VecDeque<QueuedMessage>,
399    /// Non-human messages (jekt, muxbus, bridges, MCP `SendMessage`) that
400    /// arrived while the process could not take a write — a spawn in flight,
401    /// a committed restart, a requested stop, or another writer owning stdin
402    /// (`deferred_must_wait_locked`). Written, in order, by the watchdog once
403    /// it can. A live process that can take a write gets the message at once,
404    /// mid-turn or not (`SPEC_JEKT_IMMEDIATE_DELIVERY_2026_09_28.md` §2.1),
405    /// so nothing waits here for a turn to end.
406    ///
407    /// Distinct from `pending_send_messages`, the human path's queue around a
408    /// spawn. Entries are the fully encoded stream-json stdin lines, ready to
409    /// write. Read and written only under this mutex, together with the
410    /// must-wait state it depends on, so a message is never enqueued just as
411    /// a drain observes the queue empty and exits.
412    deferred_deliveries: VecDeque<Deferred>,
413    /// Whether a deferred-delivery watchdog task is running for this
414    /// controller — see `ensure_deferred_watchdog`. Set and cleared only
415    /// under this lock, and cleared only by the watchdog itself when it
416    /// finds the queue empty, so an enqueue can never observe "armed" from a
417    /// watchdog that has already decided to exit.
418    deferred_watchdog_armed: bool,
419    /// Exclusive claim held by a stale-resume retry batch flush (issue
420    /// #2367; spec §4 option 2 of
421    /// SPEC_PERSISTENT_SPAWN_GENERATION_AND_MESSAGE_IDENTITY_2026_08_09).
422    /// Taken by `decide_retry_batch_action` in the SAME lock acquisition
423    /// in which it decides a live, newer-generation process should
424    /// receive the batch; while held, `decide_send_action`'s
425    /// `DeliverDirect` branch routes to `Queued` instead (exactly how it
426    /// already treats `spawning_in_progress`), making the queue the
427    /// single ordering authority — a concurrent send can no longer
428    /// `try_send` ahead of earlier-accepted retry messages. Released by
429    /// the flush task (`drain_queue_with_claim`) once the queue runs dry
430    /// or the process dies. Deliberately a NEW flag, not a reuse of
431    /// `spawning_in_progress` — round-14's starvation analysis stands:
432    /// that flag is never pre-asserted while no spawn is in progress.
433    drain_claim: bool,
434    /// Monotonic counter behind `QueuedMessage::seq` (issue #2365) —
435    /// pre-incremented at every fresh enqueue, so real seqs start at 1
436    /// and are never reused for this controller's lifetime. Redelivery
437    /// paths (a stale-resume retry batch) preserve a message's original
438    /// seq instead of drawing a new one — that preservation is what
439    /// makes "already queued?" an identity check rather than a content
440    /// comparison.
441    next_message_seq: u64,
442    /// True while the drain (`drain_queue_after_successful_spawn`) is
443    /// between successfully sending a message on the live stdin channel
444    /// and finishing its OWN follow-up append of that message into the
445    /// stale-`--resume` retry batch held in `resume`
446    /// (`ResumeEvent::MessageAppendedToRetryBatch`) — see the drain's own
447    /// comment at that append for why it exists (#2360): the
448    /// `Sender::send().await` and that follow-up append are two separate
449    /// lock acquisitions with an unavoidable gap between them (a mutex
450    /// can't be held across an `.await`). Without this flag, the
451    /// process-waiter's own exit-handling — running concurrently on a
452    /// DIFFERENT task — could resolve the retry batch
453    /// (`ResumeEvent::ProcessExited`) in that exact gap, dispatching a
454    /// retry that's missing a message the doomed
455    /// process's channel had ALREADY accepted: the message stays marked
456    /// "accepted" and gets persisted, but is never actually delivered to
457    /// any process again. The exit-handling waits (briefly, bounded) for
458    /// this to go false before deciding the retry batch is final — see
459    /// its own comment at that wait loop.
460    drain_send_in_flight: bool,
461    current_pid: Option<u32>,
462    /// Channel to send messages to the stdin writer task.
463    stdin_tx: Option<mpsc::Sender<String>>,
464    /// Handle to kill the process.
465    kill_tx: Option<tokio::sync::oneshot::Sender<KillRequest>>,
466    /// Set by [`Controller::shutdown`] to the spawn generation it is closing,
467    /// BEFORE it interrupts the turn. The interrupted turn ends in an
468    /// `is_error: true` result (`error_during_execution`) that is the stop we
469    /// asked for, not a failure — the stdout reader must not classify it,
470    /// raise a failure banner, or feed it to the stale-`--resume` retry
471    /// machine (spec §9.4).
472    shutdown_generation: Option<u64>,
473    /// Set by the kill arm the moment a requested stop's process has exited:
474    /// `(spawn generation, killed)`. `killed` = it had to be force-killed
475    /// (graceful deadline passed, or a forced stop). Watched by `shutdown`,
476    /// which must not wait on the kill arm's later cleanup (that can take
477    /// seconds when a descendant holds stdout open).
478    stop_exit: Option<(u64, bool)>,
479    /// Monotonic counter bumped once per `spawn_process` call (in the same
480    /// lock acquisition that reports `SpawnedWithResume`/`SpawnedFresh` to
481    /// `resume`), uniquely identifying that one spawn attempt for the rest
482    /// of this controller instance's lifetime. Note this is NOT the
483    /// `spawn_epoch`/`should_skip_own_delivery` mechanism removed earlier
484    /// (see `spawning_in_progress`'s own doc comment) — that existed to
485    /// dedup a spawn-claim race, a job `spawning_in_progress` now fully
486    /// owns. This counter exists for a different, narrower purpose: giving
487    /// every `ResumeEvent` (and the per-spawn tokens above, such as
488    /// `config_restart_generation`) something stable to compare against.
489    ///
490    /// ALSO bumped (without a spawn) by
491    /// `clear_session_id_for_fresh_spawn` to atomically retire every
492    /// existing generation's reader tasks alongside a session-id clear —
493    /// see its doc comment (codex P1 on PR #2500, second round). The
494    /// resulting numbering gap is deliberate and inert: generations are
495    /// only ever compared for equality; the invariant is "never reused,"
496    /// not "no gaps."
497    spawn_generation: u64,
498    /// A recovery candidate adopted by `settle_empty_resume_retry` while
499    /// accepted prompts were still queued behind the eager spawn claim
500    /// (codex P1 on PR #3551, fifth round). Those prompts were never
501    /// delivered to the doomed process, so they are not in the retry batch
502    /// — the eager path's own drain will find the dead `stdin_tx`, stall,
503    /// and hand them to `respawn_once_for_leftover_queue`, whose contract
504    /// is otherwise "spawn fresh". This tells that respawn to `--resume`
505    /// the candidate instead, so a recoverable session is not thrown away
506    /// for a prompt that happened to arrive during the eager attempt.
507    /// Consumed by that respawn; invalidated by any spawn (`spawn_process`
508    /// clears it under the generation bump), since a candidate only means
509    /// anything for the spawn that immediately follows its adoption.
510    leftover_resume_candidate: Option<String>,
511    /// AskUserQuestion `can_use_tool` control_requests awaiting a user answer:
512    /// `tool_use_id -> (request_id, questions JSON)`. Filled by the stdout
513    /// reader when the CLI sends a `can_use_tool` control_request for
514    /// AskUserQuestion; consumed by `answer_question` to build the matching
515    /// `control_response`. Spec: docs/specs/SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md.
516    pending_questions: HashMap<String, (String, serde_json::Value)>,
517    /// Ordinary (non-AskUserQuestion) tool-permission `can_use_tool`
518    /// control_requests awaiting a user decision: `tool_use_id ->
519    /// (request_id, tool_name, input JSON)`. Filled by
520    /// `park_tool_permission_request` when `should_route_to_decision_panel`
521    /// says so; consumed by `decide_tool_permission` to build the matching
522    /// `control_response`. Structurally the sibling of `pending_questions`
523    /// above — same in-memory-only, per-controller-instance lifetime — but
524    /// currently always empty in production: `should_route_to_decision_panel`
525    /// is hardcoded `false` pending the Phase 2 policy decision
526    /// (SPEC_DECISION_PROMPT_2026_04_24.md, SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md §5).
527    pending_permissions: HashMap<String, (String, String, serde_json::Value)>,
528    /// The single-live-instance lease the current CLI process holds
529    /// (`backend::agent_admission`, SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24
530    /// Phase 1). Set by `spawn_process` once the child is running; cleared —
531    /// which releases it — by the process-exit arms for the current
532    /// generation. An `Arc` so the pre-turn fence can verify it without
533    /// holding this lock across file I/O.
534    agent_lease: Option<Arc<crate::backend::agent_admission::HeldAgentLease>>,
535}
536
537impl PersistentInner {
538    /// Draws the next message seq (issue #2365) — pre-incremented, so
539    /// real seqs start at 1 and 0 can serve as "never a valid seq" in
540    /// tests. Must be called under the same lock acquisition as the
541    /// enqueue it identifies.
542    fn take_next_message_seq(&mut self) -> u64 {
543        self.next_message_seq += 1;
544        self.next_message_seq
545    }
546
547    /// Applies one `persistent_resume::ResumeEvent` to `self.resume`,
548    /// storing the resulting state back and returning the effects for
549    /// the caller to execute. The one and only place `self.resume` is
550    /// ever mutated — see `persistent_resume`'s module doc comment for
551    /// why routing every transition through this single pure function
552    /// (instead of several fields each caller used to read/write
553    /// directly) closes the exact race class issue #2368 kept
554    /// resurfacing.
555    fn apply_resume_event(
556        &mut self,
557        event: persistent_resume::ResumeEvent,
558    ) -> Vec<persistent_resume::ResumeEffect> {
559        let (new_state, effects) = persistent_resume::update(std::mem::take(&mut self.resume), event);
560        self.resume = new_state;
561        effects
562    }
563
564    /// Records `bad_sid` as confirmed-unreachable (the CLI reported "No
565    /// conversation found" for it) and clears it from `session_id` if it's
566    /// currently held there. Pairs with `try_capture_session_id` below —
567    /// whichever of the stderr/stdout reader tasks runs first, the
568    /// poisoned id never survives as the live `session_id`. `generation`
569    /// is the spawn attempt this poison applies to — see
570    /// `persistent_resume::ResumeEvent`'s own doc comment for why every
571    /// event carries one.
572    fn poison_resume(&mut self, bad_sid: &str, generation: u64) {
573        self.resume_poisoned = Some(bad_sid.to_string());
574        if self.session_id.as_deref() == Some(bad_sid) {
575            self.session_id = None;
576        }
577        // Promotion to a confirmed retry (only if `bad_sid` matches this
578        // generation's actual attempted sid — see
579        // `persistent_resume::update`'s `ResumeUnreachable` handling) now
580        // happens inside `update()` itself.
581        self.apply_resume_event(persistent_resume::ResumeEvent::ResumeUnreachable {
582            generation,
583            sid: bad_sid.to_string(),
584        });
585    }
586
587    /// Attempts to adopt `sid` as the live session id. Returns `false`
588    /// (does not adopt) if a session id is already held, or if `sid` is
589    /// the confirmed-poisoned id from a prior `poison_resume` call — the
590    /// CLI echoes back whatever `--resume` it was given as its first
591    /// stdout line even when that resume goes on to fail, so without this
592    /// check a losing race would silently re-adopt a known-dead id right
593    /// after `poison_resume` cleared it. A genuinely different (fresh)
594    /// sid is unaffected and still captured normally. `generation` is the
595    /// spawn attempt this capture applies to.
596    ///
597    /// codex P1 on PR #2371: resolves the tentative/confirmed retry
598    /// tracking whenever `sid` is confirmed genuine — NOT only on the
599    /// `adopted` (session_id was previously `None`) branch. A
600    /// `--resume <sid>` spawn ALWAYS has `session_id` already `Some`
601    /// BEFORE the process even starts (that's what makes `--resume` get
602    /// attached at all — see `spawn_process`), so on the common
603    /// resume-SUCCEEDED case the CLI's echoed sid matches what's already
604    /// held and this always used to return `false` immediately, WITHOUT
605    /// ever resolving tracking. Since persistent mode never exits between
606    /// turns, that would leave a generation's resume state live for the
607    /// rest of this potentially long-lived process's life, wrongly
608    /// holding back every LATER, completely unrelated `is_error:true`
609    /// result as if it might still need to be dropped for a stale-resume
610    /// retry.
611    ///
612    /// reagentx P0 on PR #2371: `is_confirmed_success` (true only for a
613    /// terminal `result` with `is_error:false`) is threaded through to
614    /// `persistent_resume::update`, which is what ACTUALLY decides
615    /// whether this capture is unambiguous enough to resolve tracking —
616    /// see `ResumeEvent::SessionCaptured`'s own doc comment for why a
617    /// same-sid echo alone (e.g. an early "system"/init frame) is NOT
618    /// proof of genuine progress: the CLI echoes the attempted sid
619    /// regardless of whether the resume goes on to fail.
620    ///
621    /// reagentx P0 on PR #2373: returns the effects `apply_resume_event`
622    /// produced, not just the `adopted` bool — resolving tracking here
623    /// can legitimately emit `FlushErrorLine` (an EARLIER turn on this
624    /// same still-alive generation held an error line back before this
625    /// LATER capture resolved tracking — see `SessionCaptured`'s own
626    /// handling in `persistent_resume::update`). Discarding that
627    /// silently lost the held-back line instead of flushing it,
628    /// reproducing the exact #2368 bug class this PR exists to fix. The
629    /// caller (the stdout reader) is responsible for actually executing
630    /// it, same as every other `ResumeEffect` this module produces.
631    fn try_capture_session_id(
632        &mut self,
633        sid: &str,
634        generation: u64,
635        is_confirmed_success: bool,
636    ) -> (bool, Vec<persistent_resume::ResumeEffect>) {
637        if self.resume_poisoned.as_deref() == Some(sid) {
638            return (false, vec![]);
639        }
640        // reagentx P1 (round 4 on this PR): `adopted` used to be gated
641        // solely on `session_id.is_none()` — but a `--resume <sid>` spawn
642        // ALWAYS hydrates `session_id` to the attempted sid BEFORE the
643        // process even starts (`spawn_process`), so that check can never
644        // be true for a resume attempt. When the CLI genuinely gives up
645        // on `--resume` internally and starts a fresh conversation with
646        // a DIFFERENT sid, `session_id` was left stuck on the stale
647        // attempted one — the controller believed it was still talking
648        // to the old conversation while the live process had moved on.
649        // `adopted` is now true whenever the captured sid actually
650        // differs from whatever `session_id` currently holds AND either
651        // nothing was captured yet at all, or this exact call is what
652        // resolves resume tracking (checked via the state transition,
653        // since that's the same unambiguous decision `update()` itself
654        // already makes for `SessionCaptured`).
655        let sid_is_new = self.session_id.as_deref() != Some(sid);
656        let session_id_was_none = self.session_id.is_none();
657        let was_tracking = !matches!(self.resume, persistent_resume::ResumeState::NotTracking { .. });
658        let effects = self.apply_resume_event(persistent_resume::ResumeEvent::SessionCaptured {
659            generation,
660            sid: sid.to_string(),
661            is_confirmed_success,
662        });
663        let just_resolved_tracking = was_tracking && matches!(self.resume, persistent_resume::ResumeState::NotTracking { .. });
664        // Ambient adoption is gated on generation currency (issue #2366):
665        // the state machine already drops a stale generation's
666        // `SessionCaptured` for TRACKING purposes, but the
667        // `session_id_was_none` arm below used to adopt regardless — so a
668        // doomed generation's still-draining stdout reader, echoing its
669        // stale attempted sid moments after `respawn_once_for_leftover_
670        // queue`'s plain clear of `session_id` (see that function's
671        // round-13 comment, which deferred exactly this race), could
672        // re-install the stale sid into ambient state. `resume_poisoned`
673        // doesn't cover that: the fallback path deliberately does NOT
674        // poison (the death may have nothing to do with a stale resume),
675        // and the fallback respawn passes `resume_retry_payload: None`,
676        // so a later spawn re-attaching `--resume <stale-sid>` would
677        // fail with nothing re-armed to catch it. A newer spawn owns the
678        // session identity by definition — a superseded generation's
679        // capture must never adopt.
680        let is_current_generation = generation == self.spawn_generation;
681        let adopted = is_current_generation && sid_is_new && (session_id_was_none || just_resolved_tracking);
682        if adopted {
683            self.session_id = Some(sid.to_string());
684        }
685        (adopted, effects)
686    }
687
688    /// The process of `generation` is still the current one, and still holds
689    /// `sid` as a session not known to be dead. A superseded generation's
690    /// draining stdout must not settle anything on the replacement's behalf
691    /// (codex P1 on #3907).
692    fn holds_current_session(&self, sid: &str, generation: u64) -> bool {
693        generation == self.spawn_generation
694            && self.session_id.as_deref() == Some(sid)
695            && self.resume_poisoned.as_deref() != Some(sid)
696    }
697}
698
699/// What `decide_send_action` determined a message's fate should be —
700/// see its own doc comment and `PersistentInner::spawning_in_progress`.
701enum SendAction {
702    /// The process is already running — deliver directly, no spawn
703    /// decision involved at all. The turn is already marked active: the
704    /// decision reserves it under the same `inner` acquisition, so an
705    /// automated send cannot see "idle" in the gap before the write (codex P1
706    /// on #3562). `was_active` is the pre-reservation state, for the caller
707    /// to start the heartbeat and to hand the turn back if the write fails.
708    DeliverDirect { was_active: bool },
709    /// Nobody else is currently spawning — this caller claimed the
710    /// exclusive right to do so and its message has already been enqueued
711    /// for the post-spawn drain. `own_seq` is that enqueued message's
712    /// `QueuedMessage::seq`, handed back so the caller can later tell
713    /// `release_spawn_claim_and_drain_queue` exactly which entry was its
714    /// own (issue #2365 — content matching could discard a different,
715    /// identical-text message instead).
716    BecomeSpawner { own_seq: u64 },
717    /// Another caller is already spawning (or a retry-batch flush holds
718    /// the drain claim — issue #2367) — this message has been enqueued
719    /// for that claim-holder's own drain to deliver.
720    Queued,
721    /// A kill is pending and the dying process still holds stdin: neither
722    /// written nor queued, reported to the sender as this error instead.
723    /// See `decide_send_action`.
724    Refused(String),
725}
726
727/// What `decide_retry_batch_action` determined a stale-resume retry
728/// batch's fate should be (issue #2367; spec §4). Split from
729/// [`SendAction`] because the batch's live-process outcome is not a
730/// direct delivery: the batch goes through the queue under the drain
731/// claim, never through a caller's own `try_send`.
732enum RetryBatchAction {
733    /// A live, NEWER-generation process is running with no claim held.
734    /// The batch was prepended to the queue AND `drain_claim` was taken
735    /// in the same lock acquisition that decided this — the caller must
736    /// start the queue flush
737    /// (`drain_queue_with_claim(.., QueueDrainClaim::RetryFlush)`).
738    FlushClaimed,
739    /// Someone else holds a claim (a spawn in flight, or another flush)
740    /// — the batch was prepended for that claim-holder's drain.
741    Queued,
742    /// Nobody holds a claim and no process is running — this retry
743    /// claimed the exclusive spawn right; `own_seq` is the batch's first
744    /// entry's seq (see `SendAction::BecomeSpawner`).
745    BecomeSpawner { own_seq: u64 },
746}
747
748/// Which exclusivity claim a queue-drain task runs under — the spawn
749/// claim (`spawning_in_progress`, the post-spawn drain) or the retry
750/// flush claim (`drain_claim`, issue #2367). The task must release
751/// exactly the claim its initiator took, and nothing else.
752#[derive(Clone, Copy, PartialEq)]
753enum QueueDrainClaim {
754    SpawnClaim,
755    RetryFlush,
756}
757
758impl QueueDrainClaim {
759    fn release(self, inner: &mut PersistentInner) {
760        match self {
761            QueueDrainClaim::SpawnClaim => inner.spawning_in_progress = false,
762            QueueDrainClaim::RetryFlush => inner.drain_claim = false,
763        }
764    }
765}
766
767/// Result of `try_eager_resume` — see `start()`'s doc comment. `DeclinedTo`
768/// carries a short, non-exhaustive reason for the log line; it is not meant
769/// to be pattern-matched on by callers, just read.
770enum EagerResumeOutcome {
771    Spawned,
772    DeclinedTo(&'static str),
773}
774
775/// PersistentSubprocessController keeps a long-running CLI process alive,
776/// sending user messages as NDJSON lines on stdin.
777pub struct PersistentSubprocessController {
778    #[allow(dead_code)]
779    tab_id: String,
780    block_id: String,
781    inner: Arc<Mutex<PersistentInner>>,
782    broker: Option<Arc<mps::Broker>>,
783    event_bus: Option<Arc<EventBus>>,
784    mstore: Option<Arc<Store>>,
785    /// FileStore for write-through persistence of output lines (Phase 1.3).
786    filestore: Option<Arc<FileStore>>,
787    /// Dependencies for `start()`'s eager-resume path
788    /// (`SPEC_PERSISTENT_CONTROLLER_EAGER_RESUME_ON_RECONNECT_2026_09_20.md`).
789    /// Set via `with_identity_stores()`, not `new()` — see that method's own
790    /// doc comment for why this is an opt-in builder step rather than a
791    /// required constructor argument.
792    id_store: Option<Arc<Store>>,
793    identity_store: Option<Arc<Store>>,
794    /// Empty when never supplied (every existing `new()` caller) — `start()`
795    /// treats an empty `auth_key` as "identity stores unavailable" the same
796    /// as `id_store`/`identity_store` being `None`, since a real spawn
797    /// always has a real key.
798    auth_key: String,
799    health_monitor: Arc<TurnActivityTracker>,
800    /// Monotonic counter bumped for every stdout line (including control frames).
801    /// The AskUserQuestion dead-air fallback snapshots this *before* sending the
802    /// answer and re-checks after a short window; any increment means the CLI
803    /// produced output (assistant content OR a follow-up control_request), i.e.
804    /// the turn resumed. Counting *all* frames — including control frames the
805    /// reader otherwise skips — avoids a spurious fallback when the resumed
806    /// turn's first activity is a tool-permission round-trip.
807    stdout_seq: Arc<AtomicU64>,
808    /// Weak self-reference for the stale-`--resume`-session retry (see
809    /// `retry_after_resume_failure`) — set by `set_self_ref` right after
810    /// construction. The process-waiter task (a detached `tokio::spawn`
811    /// that only captures cloned Arc fields, never `&self`) needs a way to
812    /// call back into an instance method once the underlying process
813    /// actually exits; a `Weak` avoids a reference cycle (this same
814    /// struct's `spawn_process` is what schedules that task).
815    self_ref: Mutex<Option<std::sync::Weak<Self>>>,
816    /// This controller's own muxbus/jekt identity, captured once at spawn
817    /// time from `muxbus_agent_id_from_env` — the independent source of
818    /// truth `Controller::agent_id()` exposes for `inject_message_inner`'s
819    /// recipient-identity check. Deliberately its own field, not part of
820    /// `PersistentInner` — `config` (and its `env_vars`, where the identity
821    /// is read from) isn't available until `spawn_process`, well after
822    /// `new()`, and this value doesn't participate in any of `PersistentInner`'s
823    /// carefully-ordered spawn/resume/queue state transitions. `None` for a
824    /// persistent block with no muxbus identity set (a non-agent process).
825    agent_id: Mutex<Option<String>>,
826    /// The STABLE jekt identity (`AGENTMUX_AGENT_ID`), captured once in
827    /// `spawn_process` and never overwritten afterward — unlike `agent_id`
828    /// above, which `input.rs`'s Register-tail deliberately refreshes every
829    /// turn to track the live, renameable display name (#2697). Exists
830    /// specifically so `Controller::stable_agent_id()` can back the jekt
831    /// registry's alias entry and the #2695 recipient-identity check even
832    /// after `agent_id` has moved on to a post-rename value. See
833    /// `INCIDENT_2026_09_09_JEKT_STABLE_ID_ALIAS.md`.
834    stable_agent_id: Mutex<Option<String>>,
835    /// Identity M2: `AGENTMUX_AGENT_UID` from the spawn env, captured at
836    /// spawn exactly like `stable_agent_id`. `None` until spawned, or when
837    /// the spawn env carried no UID (no `db_agents` row yet). See
838    /// `Controller::stable_agent_uid`.
839    stable_agent_uid: Mutex<Option<String>>,
840    /// The segment the latest spawn recorded (`segments.rs`), so a resume
841    /// retry can tell the agent's previous segment from the one that just
842    /// failed. `None` until a spawn with an agent UID.
843    current_segment: Mutex<Option<String>>,
844    /// Reports whatever is still deferred when this controller is dropped.
845    /// See [`DeferredDropReport`].
846    deferred_drop_report: DeferredDropReport,
847    /// Where this agent's single-live-instance lease lives, and this srv's
848    /// boot id (the lease owner). Set via `with_agent_lease_store()`; `None`
849    /// (tests, a registry that can't be opened) means no lease is taken.
850    lease_store: Option<Arc<crate::registry::LeaseStore>>,
851    boot_id: Arc<str>,
852}
853
854/// The last line of defence for §4.5: whatever is still deferred when the
855/// controller goes away is reported, not silently discarded with it.
856///
857/// `stop()` and `shutdown()` drain the queue, but a sender that fetched the
858/// controller before it was unregistered can still enqueue after that drain
859/// (codex P2 on #3562). The watchdog holds only a weak reference, so it dies
860/// with the controller and cannot catch it. `stop()` cannot refuse those late
861/// senders instead: the max-runtime watchdog stops controllers that stay
862/// registered and get used again.
863///
864/// A field rather than `Drop` on the controller itself, so struct-update
865/// construction (`..c`, used throughout the tests) keeps working. Holds the
866/// controller's own `inner`; `None` only transiently inside `new()`.
867struct DeferredDropReport(Option<(String, Arc<Mutex<PersistentInner>>)>);
868
869impl Drop for DeferredDropReport {
870    fn drop(&mut self) {
871        let Some((block_id, inner)) = self.0.take() else { return };
872        // Never panic in `drop`: a poisoned lock still holds the queue.
873        let stranded: Vec<Deferred> = match inner.lock() {
874            Ok(mut g) => g.deferred_deliveries.drain(..).collect(),
875            Err(poisoned) => poisoned.into_inner().deferred_deliveries.drain(..).collect(),
876        };
877        PersistentSubprocessController::log_stranded_deferred(&block_id, "controller dropped", &stranded);
878    }
879}
880
881/// How long to wait after delivering an AskUserQuestion answer before assuming
882/// the turn did not resume and re-delivering the answer as a follow-up message.
883/// See `answer_question` and SPEC_ASK_USER_QUESTION_2026_06_15.md §10.1.
884const ANSWER_RESUME_FALLBACK_MS: u64 = 4000;
885
886/// Bound on `PersistentInner::deferred_deliveries`. Past this, enqueueing
887/// returns an error instead of a false success, so a caller is never told a
888/// message was delivered and then has it silently dropped
889/// (`SPEC_NO_MIDTURN_DELIVERY_2026_09_23.md` §4.5). Senders already handle
890/// transient delivery failure — the reactive handler, muxbus and the bridges
891/// all have to cope with an unreachable target instance — so surfacing a full
892/// queue as one more retryable failure needs no new machinery on their side.
893///
894/// 64 is chosen to be far above any plausible legitimate backlog for one
895/// startup or restart while still bounding memory: these are whole messages,
896/// and the queue is per-block.
897pub(super) const MAX_DEFERRED_DELIVERIES: usize = 64;
898
899/// How often the deferred-delivery watchdog re-checks a non-empty queue.
900/// Messages are queued only while the process cannot take a write (starting
901/// up, restarting, stopping), and the watchdog is what writes them once it
902/// can, so this bounds how long after the process comes up they arrive.
903pub(super) const DEFERRED_WATCHDOG_TICK: std::time::Duration = std::time::Duration::from_millis(500);
904
905/// Consecutive watchdog ticks with no process and no spawn in flight before
906/// the queue is declared stranded and reported (spec §4.5). Long enough to
907/// ride out the gap between a process exit and the respawn that follows it
908/// (a stale-`--resume` retry, a fallback respawn); short enough that a dead
909/// agent's backlog is surfaced rather than held forever.
910pub(super) const DEFERRED_ORPHAN_GRACE_TICKS: u32 = 20;
911
912/// Whether the deferred-delivery watchdog keeps running after a tick.
913#[derive(Debug, PartialEq)]
914pub(super) enum WatchdogStep {
915    Continue,
916    Exit,
917}
918
919/// Compose the directive follow-up message used by the AskUserQuestion dead-air
920/// fallback. `answers` maps each question's text to the selected label(s) or free
921/// text (the same object delivered in the control_response). The message is
922/// deliberately directive so the model resumes the task instead of treating it
923/// as a no-op (the "user sent an empty message" failure mode).
924fn build_answer_resume_message(answers: &serde_json::Value) -> String {
925    let mut out = String::from(
926        "[AgentMux] Your earlier question was answered, but the turn had already ended, \
927         so the answer is delivered here as a follow-up. Resume the task you were working \
928         on using this answer — do not wait for further input:\n",
929    );
930    match answers.as_object() {
931        Some(map) if !map.is_empty() => {
932            for (question, answer) in map {
933                let rendered = match answer {
934                    serde_json::Value::String(s) => s.clone(),
935                    serde_json::Value::Array(items) => items
936                        .iter()
937                        .filter_map(|v| v.as_str().map(str::to_string))
938                        .collect::<Vec<_>>()
939                        .join(", "),
940                    other => other.to_string(),
941                };
942                out.push_str(&format!("\n• {question}: {rendered}"));
943            }
944        }
945        _ => out.push_str(&format!("\nAnswer: {answers}")),
946    }
947    out
948}
949
950/// Fixed, server-owned decline message for a cancelled AskUserQuestion (the
951/// Cancel button / Escape in `AgentQuestionPanel.tsx`) — not client-suppliable,
952/// since Cancel and Escape both mean exactly one thing and there is no user-
953/// authored content to carry. See `deny_question` and
954/// docs/specs/SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md.
955///
956/// KEEP IN SYNC (no shared constant crosses the Rust/TypeScript boundary for
957/// a plain string literal): `CANCEL_FALLBACK_MESSAGE` in
958/// `frontend/app/view/agent/hooks/useAgentQuestions.ts` is a hand-copied
959/// mirror of this exact text, used only for its SAFE_TO_RETRY_VIA_FOLLOWUP
960/// fallback path. If you change this string, update that one too — the test
961/// `ask_user_question_deny_message_matches_frontend_cancel_fallback_text`
962/// below pins the literal on this side; the frontend test asserting
963/// `sendMessage` was called with this exact text (in
964/// `useAgentQuestions.test.ts`, "handleCancel fallback" describe block)
965/// pins it on that side. Neither test can see the other language's
966/// constant, so both must be updated by hand together.
967pub const ASK_USER_QUESTION_DENY_MESSAGE: &str = "The user declined to answer this question.";
968
969/// Compose the directive follow-up message used by the AskUserQuestion dead-air
970/// fallback when the answer was a DECLINE rather than a real answer. Mirrors
971/// `build_answer_resume_message`'s directive tone (resume the task, don't wait
972/// for further input) but tells the model the outcome was a decline so it
973/// doesn't hallucinate a value the user never provided.
974fn build_deny_resume_message(message: &str) -> String {
975    format!(
976        "[AgentMux] Your earlier question was declined, but the turn had already ended, \
977         so this is delivered here as a follow-up. Resume the task you were working on \
978         without this input — do not wait for further input. The user's response was: \
979         \"{message}\""
980    )
981}
982
983/// Whether a `can_use_tool` control_request for `tool_name` (anything except
984/// AskUserQuestion, which is always parked separately — see
985/// `handle_control_frame`) should be routed to the frontend decision panel
986/// instead of auto-allowed.
987///
988/// **Hardcoded to `false` — deliberately inert.** This is the one remaining
989/// product decision `SPEC_DECISION_PROMPT_2026_04_24.md` Phase 2 and
990/// `SPEC_AGENT_CONTROL_PROTOCOL_2026_06_15.md` §5 Phase 2 both leave open,
991/// and it is NOT safe to default it to "route everything non-trivial" —
992/// that spec's own §7 risk section says so directly:
993///
994/// > Permission chatter: `--permission-mode default` may route many tools
995/// > through `can_use_tool`. Mitigation: auto-allow in the handler (Phase 1);
996/// > consider `--permission-mode acceptEdits` or allow-rules to cut volume.
997///
998/// `--permission-mode default` is the mode baked into every persistent
999/// Claude agent's launch args today (`static CLAUDE` in
1000/// `crates/srv-core/src/backend/providers.rs`), and it routes most non-trivial
1001/// tool calls through this control_request. Flipping this function to
1002/// unconditionally `true` would turn every persistent Claude agent into a
1003/// prompt-per-tool-call experience the instant it ships — a real regression,
1004/// not a hypothetical one, and not something an engineering change should
1005/// decide unilaterally.
1006///
1007/// The parking/decide mechanism this gate controls —
1008/// `park_tool_permission_request` below and
1009/// `PersistentSubprocessController::decide_tool_permission` — is complete
1010/// and independently tested (see the "Phase 2 gate" tests in
1011/// `persistent/tests/send_input.rs`, which call both directly); flipping
1012/// this gate on is a policy call about which tools or modes actually
1013/// warrant a prompt (a risk-tiering scheme per
1014/// `SPEC_DECISION_PROMPT_2026_04_24.md`'s own speculative `risk` field,
1015/// `--permission-mode acceptEdits` instead of `default`, or persisted
1016/// allow-rules per that spec's §6 — none of which exist yet), not an
1017/// engineering task this function should pre-empt.
1018fn should_route_to_decision_panel(_tool_name: &str) -> bool {
1019    false
1020}
1021
1022/// Compose the directive follow-up message used by the tool-permission
1023/// dead-air fallback (mirrors `build_answer_resume_message` /
1024/// `build_deny_resume_message`'s directive tone — resume the task, don't
1025/// wait for further input — but for an ordinary tool-permission decision
1026/// rather than an AskUserQuestion answer).
1027fn build_tool_decision_resume_message(tool_name: &str, outcome: &str, feedback: Option<&str>) -> String {
1028    if outcome == "allow" {
1029        format!(
1030            "[AgentMux] Your earlier request to use `{tool_name}` was approved, but the \
1031             turn had already ended, so this is delivered here as a follow-up. Resume the \
1032             task you were working on — the tool call is approved; do not wait for further \
1033             input."
1034        )
1035    } else {
1036        let reason = feedback.unwrap_or("Denied by user.");
1037        format!(
1038            "[AgentMux] Your earlier request to use `{tool_name}` was declined, but the \
1039             turn had already ended, so this is delivered here as a follow-up. Resume the \
1040             task you were working on without using that tool — do not wait for further \
1041             input. The user's response was: \"{reason}\""
1042        )
1043    }
1044}
1045
1046impl PersistentSubprocessController {
1047    pub fn new(
1048        tab_id: String,
1049        block_id: String,
1050        broker: Option<Arc<mps::Broker>>,
1051        event_bus: Option<Arc<EventBus>>,
1052        mstore: Option<Arc<Store>>,
1053        filestore: Option<Arc<FileStore>>,
1054    ) -> Self {
1055        let health_monitor = Arc::new(TurnActivityTracker::for_block(block_id.clone(), broker.as_ref()));
1056        let mut this = Self {
1057            tab_id,
1058            block_id,
1059            inner: Arc::new(Mutex::new(PersistentInner {
1060                proc_status: STATUS_INIT.to_string(),
1061                proc_exit_code: 0,
1062                status_version: 0,
1063                session_id: None,
1064                resume_poisoned: None,
1065                fork_copy: None,
1066                fork_next: false,
1067                restart_when_idle: false,
1068                restart_pending: false,
1069                spawn_runtime: None,
1070                effective_runtime: None,
1071                settings_readback: false,
1072                context_usage: None,
1073                stop_pending: false,
1074                config_restart_generation: None,
1075                restart_spawn_for: None,
1076                stop_watch: Default::default(),
1077                resume: persistent_resume::ResumeState::default(),
1078                spawning_in_progress: false,
1079                pending_send_messages: VecDeque::new(),
1080                deferred_deliveries: VecDeque::new(),
1081                deferred_watchdog_armed: false,
1082                drain_claim: false,
1083                next_message_seq: 0,
1084                drain_send_in_flight: false,
1085                current_pid: None,
1086                stdin_tx: None,
1087                kill_tx: None,
1088                shutdown_generation: None,
1089                stop_exit: None,
1090                spawn_generation: 0,
1091                leftover_resume_candidate: None,
1092                pending_questions: HashMap::new(),
1093                pending_permissions: HashMap::new(),
1094                agent_lease: None,
1095            })),
1096            broker,
1097            event_bus,
1098            mstore,
1099            filestore,
1100            id_store: None,
1101            identity_store: None,
1102            auth_key: String::new(),
1103            health_monitor,
1104            stdout_seq: Arc::new(AtomicU64::new(0)),
1105            self_ref: Mutex::new(None),
1106            agent_id: Mutex::new(None),
1107            stable_agent_id: Mutex::new(None),
1108            stable_agent_uid: Mutex::new(None),
1109            current_segment: Mutex::new(None),
1110            deferred_drop_report: DeferredDropReport(None),
1111            lease_store: None,
1112            boot_id: Arc::from(""),
1113        };
1114        this.deferred_drop_report =
1115            DeferredDropReport(Some((this.block_id.clone(), Arc::clone(&this.inner))));
1116        this
1117    }
1118
1119    /// Supplies the dependencies `start()`'s eager-resume path needs
1120    /// (`SPEC_PERSISTENT_CONTROLLER_EAGER_RESUME_ON_RECONNECT_2026_09_20.md`):
1121    /// the Layer 3 identity/credential spawn gate's two stores, and the
1122    /// auth key a spawned CLI needs for `AGENTMUX_AUTH_KEY` (MPS publish
1123    /// scoping via the bashwrap-invoked tool wrapper).
1124    ///
1125    /// A separate builder step, not three more `new()` parameters, so every
1126    /// existing caller — the ~15 test constructions in this file among
1127    /// them — is unaffected. A controller built without this call simply
1128    /// cannot eager-resume even when `agent:sessionid` is present; it falls
1129    /// back to `start()`'s ordinary lazy "wait for the first message" path
1130    /// rather than spawning without the identity gate. That fallback is the
1131    /// deliberately safe default: eagerly resuming a possibly-deauthed
1132    /// agent's session on whatever ambient credential happens to be present
1133    /// would silently reintroduce the exact vulnerability class
1134    /// `SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4_2026_07_14.md` closed. See
1135    /// `start()`'s own doc comment for the full reasoning.
1136    pub fn with_identity_stores(
1137        mut self,
1138        id_store: Option<Arc<Store>>,
1139        identity_store: Option<Arc<Store>>,
1140        auth_key: String,
1141    ) -> Self {
1142        self.id_store = id_store;
1143        self.identity_store = identity_store;
1144        self.auth_key = auth_key;
1145        self
1146    }
1147
1148    /// Supplies the single-live-instance lease store (under the shared agent
1149    /// registry root) and this srv's boot id. A separate builder step for
1150    /// the same reason as `with_identity_stores`. Without it the controller
1151    /// takes no lease — the pre-Phase-1 behaviour.
1152    pub fn with_agent_lease_store(
1153        mut self,
1154        registry: Option<Arc<crate::registry::Registry>>,
1155        boot_id: Arc<str>,
1156    ) -> Self {
1157        self.lease_store = crate::backend::agent_admission::lease_store_for(registry);
1158        self.boot_id = boot_id;
1159        self
1160    }
1161
1162    /// Claim (or keep) this agent's single-live-instance lease for the
1163    /// process `spawn_process` is about to start. `Ok(None)` when leasing is
1164    /// unavailable (no store) or the spawn env carries no agent UID — those
1165    /// run unguarded, as before Phase 1, and are logged. `Err` is the
1166    /// user-facing refusal: another instance runs this agent.
1167    ///
1168    /// A lease this controller already holds (an earlier generation's, still
1169    /// valid) is reused rather than re-claimed: a fresh handle for the same
1170    /// key would release the shared file when the old one dropped.
1171    pub(super) fn acquire_agent_lease(
1172        &self,
1173        config: &PersistentSpawnConfig,
1174        session_hint: Option<&str>,
1175    ) -> Result<Option<Arc<crate::backend::agent_admission::HeldAgentLease>>, String> {
1176        let uid = config
1177            .env_vars
1178            .get("AGENTMUX_AGENT_UID")
1179            .map(|u| u.trim().to_string())
1180            .filter(|u| !u.is_empty());
1181        self.refuse_if_handed_over(config)?; // whatever the lease store says, an agent handed to another computer is not started here
1182        let Some(store) = self.lease_store.as_ref() else { return Ok(None) };
1183        let Some(uid) = uid else {
1184            tracing::warn!(
1185                block_id = %self.block_id,
1186                "agent_admission: spawn env carries no agent UID — no single-instance lease for this process"
1187            );
1188            return Ok(None);
1189        };
1190        let existing = self.inner.lock().unwrap().agent_lease.clone();
1191        if let Some(existing) = existing {
1192            existing.verify()?;
1193            return Ok(Some(existing));
1194        }
1195        let agent = muxbus_agent_id_from_env(&config.env_vars).unwrap_or_default();
1196        let (inner, block_id) = (Arc::clone(&self.inner), self.block_id.clone());
1197        let held = crate::backend::agent_admission::acquire(
1198            store,
1199            &uid,
1200            &agent,
1201            &self.boot_id,
1202            &self.block_id,
1203            session_hint,
1204            move |why| Self::on_lease_lost(&inner, &block_id, &why),
1205        )?;
1206        Ok(Some(Arc::new(held)))
1207    }
1208
1209    /// The pre-turn fence (spec I4): `Err` if this pane's CLI process lost
1210    /// its lease to another instance. Also stops that process, so it cannot
1211    /// keep driving the agent. `Ok` when no lease is held (nothing spawned
1212    /// yet — the spawn will claim — or leasing is unavailable).
1213    pub(super) fn fence_check(&self) -> Result<(), String> {
1214        let lease = self.inner.lock().unwrap().agent_lease.clone();
1215        let Some(lease) = lease else { return Ok(()) };
1216        if let Err(e) = lease.verify() {
1217            Self::stop_after_lease_loss(&self.inner, &self.block_id, &e);
1218            return Err(e);
1219        }
1220        Ok(())
1221    }
1222
1223    /// Kill the current CLI process after its lease was lost — the holder
1224    /// stops rather than racing the new one (spec §4.3).
1225    pub(super) fn stop_after_lease_loss(inner: &Arc<Mutex<PersistentInner>>, block_id: &str, why: &str) {
1226        let kill = inner.lock().unwrap().kill_tx.take();
1227        tracing::error!(block_id, why, "agent_admission.fenced: stopping this pane's CLI process");
1228        if let Some(tx) = kill {
1229            let _ = tx.send(KillRequest::Force);
1230        }
1231    }
1232
1233    /// Sets the weak self-reference used by the process-waiter task to call
1234    /// back into `retry_after_resume_failure` once a doomed process (stale
1235    /// `--resume` session id) actually exits. Mirrors `SubprocessController::
1236    /// set_self_ref`'s queued-message-drain pattern. Must be called by the
1237    /// caller right after wrapping a fresh instance in `Arc` — a controller
1238    /// that's never had this called simply never retries (the check is a
1239    /// harmless no-op `Weak::upgrade()` failure), so this is safe to skip
1240    /// for e.g. throwaway test instances.
1241    pub fn set_self_ref(self: &Arc<Self>) {
1242        *self.self_ref.lock().unwrap() = Some(Arc::downgrade(self));
1243    }
1244}
1245
1246impl Controller for PersistentSubprocessController {
1247    /// Lazy by default — "spawns on first message" — EXCEPT for a pane
1248    /// resuming an existing session across a backend restart/reconnect, per
1249    /// `SPEC_PERSISTENT_CONTROLLER_EAGER_RESUME_ON_RECONNECT_2026_09_20.md`.
1250    /// Without this, every persistent agent pane comes back from a crash/
1251    /// OOM/update as an inert shell — correct layout, correct chrome, `view:
1252    /// "agent"`, no live process — until a human or another agent happens to
1253    /// message it. Live incident: 3 of 7 panes in one window silently never
1254    /// respawned after 2026-09-20's restarts (issue #3463).
1255    ///
1256    /// `agent:sessionid` meta present and non-empty is the signal: this pane
1257    /// has a real, interrupted conversation rather than being genuinely new
1258    /// (which still spawns lazily, unchanged — no reason to burn a process
1259    /// before it's needed). Mirrors `ShellController::start()`'s already-
1260    /// established "transparently revive on restart" behavior for shells.
1261    ///
1262    /// **Eager resume is gated on the SAME Layer 3 identity/credential spawn
1263    /// gate a live message send goes through**
1264    /// (`identity::resolver::inject_identity_env`,
1265    /// `SPEC_ACCOUNT_DELETE_DEAUTH_LAYERS_2_4_2026_07_14.md`) — this is not
1266    /// an optional hardening pass, it is why this method does not simply
1267    /// spawn unconditionally the moment a session id is found. Skipping the
1268    /// gate here would let an agent whose bound account was deleted/revoked
1269    /// between the crash and the restart get silently respawned anyway, on
1270    /// whatever ambient credential happens to be lying around: exactly the
1271    /// vulnerability class that gate exists to close, reintroduced through a
1272    /// call site the gate was never wired into. Any of the following falls
1273    /// back to today's lazy behavior — NOT a hard error, since a pane that
1274    /// merely stays inert is still recoverable by a message, unlike one
1275    /// spawned on the wrong credentials:
1276    /// - `id_store`/`identity_store`/`auth_key` weren't supplied (i.e. this
1277    ///   controller was constructed without `with_identity_stores()` —
1278    ///   should not happen for a production `resync_controller` call, but a
1279    ///   test or future caller that omits it must not silently spawn
1280    ///   ungated rather than just not eager-resuming).
1281    /// - `mstore` is unavailable.
1282    /// - `cmd`/`cmd:args` meta is missing (should not happen for a pane
1283    ///   that has ever actually run — `agent_open.rs` always seeds them —
1284    ///   but guessing CLI flags for a persistent agent is worse than not
1285    ///   eager-resuming).
1286    /// - The gate itself returns `Err` (`SpawnGateError`).
1287    fn start(
1288        &self,
1289        block_meta: super::super::obj::MetaMapType,
1290        _rt_opts: Option<serde_json::Value>,
1291        _force: bool,
1292    ) -> Result<(), String> {
1293        let session_id = crate::backend::obj::meta_get_string(&block_meta, core::META_SESSION_ID, "");
1294        if session_id.is_empty() {
1295            tracing::info!(
1296                block_id = %self.block_id,
1297                "persistent controller registered (spawns on first message)"
1298            );
1299            return Ok(());
1300        }
1301
1302        match self.try_eager_resume(&block_meta, &session_id) {
1303            EagerResumeOutcome::Spawned => {}
1304            EagerResumeOutcome::DeclinedTo(reason) => {
1305                tracing::info!(
1306                    block_id = %self.block_id,
1307                    session_id = %session_id,
1308                    reason = %reason,
1309                    "persistent controller has a prior session but is not eager-resuming it \
1310                     — registered lazily instead (spawns on next message)"
1311                );
1312            }
1313        }
1314        Ok(())
1315    }
1316
1317    fn stop(&self, _graceful: bool, new_status: &str) -> Result<(), String> {
1318        // Not `stop_process` then a separate drain: see
1319        // `request_stop_draining_deferred` for the race between the two.
1320        let stranded = self.request_stop_draining_deferred(KillRequest::Force);
1321        Self::log_stranded_deferred(&self.block_id, "controller stopped", &stranded);
1322        let mut inner = self.inner.lock().unwrap();
1323        if inner.proc_status != new_status {
1324            Self::set_status(&mut inner, new_status);
1325        }
1326        drop(inner);
1327        // Leaving "running" clears what the process was spawned with; the menu
1328        // must hear that too, or it keeps judging a process that is gone.
1329        self.publish_runtime();
1330        Ok(())
1331    }
1332
1333    /// Pane-close shutdown (spec §9.3), built on the Phase 0 measurements
1334    /// (§5.1): EOF alone does NOT end a running turn — the CLI finishes it
1335    /// first — but the control-protocol interrupt ends it in ~2s, and EOF
1336    /// then exits the process in ~0.5s. So: interrupt an active turn, wait
1337    /// for its result, EOF, and force-kill only at the deadline.
1338    fn shutdown(&self, deadline: std::time::Instant) -> super::ShutdownFuture {
1339        use super::StopOutcome;
1340        const POLL: std::time::Duration = std::time::Duration::from_millis(50);
1341        let inner = Arc::clone(&self.inner);
1342        let health = Arc::clone(&self.health_monitor);
1343        let block_id = self.block_id.clone();
1344        Box::pin(async move {
1345            let (running, stranded) = {
1346                let mut g = inner.lock().unwrap();
1347                // Drained BEFORE the no-process return: a message deferred
1348                // behind a spawn that then failed sits here with no process,
1349                // and the watchdog holds only a weak ref, so it dies with this
1350                // controller. Returning first discarded the message unreported
1351                // (codex P2 on #3562).
1352                let stranded: Vec<Deferred> = g.deferred_deliveries.drain(..).collect();
1353                // A pane close outranks a committed config restart in EVERY
1354                // branch, including this no-process one: the restart's
1355                // replacement may still be mid-spawn with no pid yet, and
1356                // would otherwise pass `commit_restart_spawn_locked` and
1357                // install a child for a closed pane (codex P1 on #3990).
1358                g.config_restart_generation = None;
1359                g.restart_spawn_for = None;
1360                g.stop_watch.note_stop();
1361                let running = if g.current_pid.is_none() {
1362                    // Never spawned (lazy), or already gone. A spawn still in
1363                    // flight is killed by the caller's tracker drop.
1364                    None
1365                } else {
1366                    // Gate writes now, in the same section as the drain, not
1367                    // later in `request_stop_on`: a sender that already holds
1368                    // this controller can still enqueue, and the interrupt's
1369                    // own `result` would flush that into the process being
1370                    // shut down (codex P2 on #3562). The interrupt itself
1371                    // goes out on `stdin_tx` directly, not through the gate.
1372                    g.stop_pending = true;
1373                    // Nothing queued may start a new turn after the interrupt.
1374                    g.pending_send_messages.clear();
1375                    // Before the interrupt: its `is_error` result is our stop,
1376                    // not a failure (§9.4).
1377                    g.shutdown_generation = Some(g.spawn_generation);
1378                    g.stop_exit = None;
1379                    Some((g.spawn_generation, g.stdin_tx.clone()))
1380                };
1381                (running, stranded)
1382            };
1383            Self::log_stranded_deferred(&block_id, "pane shutdown", &stranded);
1384            let Some((generation, stdin_tx)) = running else {
1385                return StopOutcome::NotRunning;
1386            };
1387
1388            if health.is_active_turn() {
1389                if let Some(tx) = stdin_tx.as_ref() {
1390                    if tx.send(interrupt_control_request_line()).await.is_ok() {
1391                        // Leave a second for EOF + exit after the turn ends.
1392                        let turn_deadline = deadline
1393                            .checked_sub(std::time::Duration::from_secs(1))
1394                            .unwrap_or(deadline);
1395                        while health.is_active_turn() && std::time::Instant::now() < turn_deadline {
1396                            tokio::time::sleep(POLL).await;
1397                        }
1398                    }
1399                }
1400            }
1401            // Our clone of the stdin sender would keep stdin open — EOF needs
1402            // every sender gone.
1403            drop(stdin_tx);
1404            let _ = Self::request_stop_on(&inner, KillRequest::Graceful(deadline));
1405
1406            // The kill arm records the exit the moment it happens; allow a
1407            // little past the deadline for the forced kill itself.
1408            let give_up = deadline + std::time::Duration::from_secs(2);
1409            loop {
1410                {
1411                    let g = inner.lock().unwrap();
1412                    if let Some((gen, killed)) = g.stop_exit {
1413                        if gen == generation {
1414                            return if killed { StopOutcome::Killed } else { StopOutcome::Exited };
1415                        }
1416                    }
1417                    // Exited on its own through the natural-exit arm, or was
1418                    // replaced — either way this process is gone.
1419                    if g.spawn_generation != generation || g.current_pid.is_none() {
1420                        return StopOutcome::Exited;
1421                    }
1422                }
1423                if std::time::Instant::now() >= give_up {
1424                    tracing::warn!(
1425                        block_id = %block_id,
1426                        "agent_shutdown: no exit recorded by the deadline; the caller's tracker drop will kill it"
1427                    );
1428                    return StopOutcome::Killed;
1429                }
1430                tokio::time::sleep(POLL).await;
1431            }
1432        })
1433    }
1434
1435    fn get_runtime_status(&self) -> BlockControllerRuntimeStatus {
1436        self.get_status_snapshot()
1437    }
1438
1439    fn interrupt_turn(&self) -> Result<(), String> {
1440        stdout_reader::loop_stop::interrupt_for_cap(self)
1441    }
1442
1443    fn send_input(&self, input: BlockInputUnion, _seq: Option<u64>) -> Result<(), String> {
1444        // No PTY, no raw keystrokes: user messages go through send_message(). The Stop button / Esc sends
1445        // `ControllerInputCommand({signame:"SIGINT"})` (useAgentCommands `stopAgent`); route it to the kill path
1446        // `stop()` uses, as SubprocessController does. The session_id is retained, so the next message resumes.
1447        if let Some(sig) = input.sig_name.as_deref() {
1448            if sig == "SIGINT" || sig == "SIGTERM" {
1449                tracing::info!(
1450                    block_id = %self.block_id,
1451                    sig = %sig,
1452                    "persistent controller: received signal, stopping current process"
1453                );
1454                return self.stop_process(true);
1455            }
1456            return Err(format!(
1457                "persistent controller: unsupported signal {sig} (only SIGINT/SIGTERM)"
1458            ));
1459        }
1460        // Raw keystrokes are genuinely unsupported — user messages go through
1461        // send_message(), not the PTY input channel.
1462        if input.input_data.is_some() {
1463            return Err(
1464                "persistent controller does not accept raw input; use send_message()".to_string(),
1465            );
1466        }
1467        // Term resize / other benign input types: accepted no-op. A persistent
1468        // controller has no PTY, so there is nothing to resize — but the agent
1469        // pane's `usePtyWidth` hook sends a `termsize` on every running turn
1470        // (it can't tell a PTY-backed controller from a PTY-less one). Returning
1471        // an error here surfaced a spurious "resize to N cols failed" warning in
1472        // the agent pane's activity log. Mirror SubprocessController, which
1473        // already no-ops termsize. See AGENT_PANE_PTY_RESIZE_RACE_2026_06_16.md.
1474        Ok(())
1475    }
1476
1477    fn turn_tracker(&self) -> Option<Arc<TurnActivityTracker>> {
1478        Some(Arc::clone(&self.health_monitor))
1479    }
1480
1481    fn awaiting_user_reply(&self) -> bool {
1482        self.has_parked_request()
1483    }
1484
1485    fn pending_for_devices(&self) -> super::PendingFacts {
1486        self.parked_for_devices()
1487    }
1488
1489    fn controller_type(&self) -> &str {
1490        BLOCK_CONTROLLER_PERSISTENT
1491    }
1492
1493    fn block_id(&self) -> &str {
1494        &self.block_id
1495    }
1496
1497    fn agent_id(&self) -> Option<String> {
1498        self.agent_id.lock().unwrap().clone()
1499    }
1500
1501    fn turn_provenance(&self) -> Option<crate::backend::blockcontroller::health::TurnProvenance> {
1502        self.health_monitor.provenance()
1503    }
1504
1505    fn set_agent_id(&self, id: Option<String>) {
1506        *self.agent_id.lock().unwrap() = id;
1507    }
1508
1509    fn stable_agent_id(&self) -> Option<String> {
1510        self.stable_agent_id.lock().unwrap().clone()
1511    }
1512
1513    fn stable_agent_uid(&self) -> Option<String> {
1514        self.stable_agent_uid.lock().unwrap().clone()
1515    }
1516
1517    fn as_any(&self) -> &dyn std::any::Any {
1518        self
1519    }
1520}
1521
1522/// Classify a flushed error line, if it's confident enough to surface to
1523/// the pane's failure-recovery UI. `line` is usually the same result-frame
1524/// JSON the mid-stream error-result path handles, but
1525/// `persistent_resume::ResumeEffect::FlushErrorLine` can also carry an
1526/// earlier held-back turn's line — falls back to raw-text keyword matching
1527/// (the same `classify()` uses for a stderr tail) if it doesn't parse as
1528/// JSON. `exit_code` is `Some` at the process-exit arm and `None` at the
1529/// mid-generation flush sites (a superseded spawn generation, or a
1530/// `SessionCaptured` resolution), where no fresh exit code exists for the
1531/// line being flushed. Returns `None` for an unrecognized, non-retryable
1532/// `FailureClass::UnknownNonZero` to avoid a low-confidence banner from
1533/// noisy flushed text — every other recognized class is surfaced, not just
1534/// the retryable ones, since the recovery banner has value for e.g. `Auth`
1535/// too (see `SPEC_AGENT_FAILURE_RECOVERY_UI_2026_06_16.md`'s per-class
1536/// action matrix), just without auto-retry.
1537/// See `SPEC_PERSISTENT_CONTROLLER_FAILURE_CLASSIFICATION_2026_08_04.md`.
1538fn classify_exit_line(exit_code: Option<i32>, line: &str) -> Option<crate::agents::failure::AgentFailure> {
1539    let parsed_line: Option<serde_json::Value> = serde_json::from_str(line).ok();
1540    let stderr_text = if parsed_line.is_none() { line } else { "" };
1541    let failure = crate::agents::failure::classify(exit_code, None, stderr_text, parsed_line.as_ref());
1542    (failure.retryable || failure.code != crate::agents::failure::FailureClass::UnknownNonZero).then_some(failure)
1543}
1544
1545/// Record `failure` as the block's `agent:last_failure`, then publish it as
1546/// `agent-failure` on `block:<id>` (persisted for replay) when there is a broker.
1547fn surface_failure(
1548    block_id: &str,
1549    failure: &crate::agents::failure::AgentFailure,
1550    broker: Option<&mps::Broker>,
1551    mstore: &Option<Arc<Store>>,
1552    event_bus: &Option<Arc<EventBus>>,
1553) {
1554    let failure = &crate::agents::limit_reset::with_reset(block_id, failure); // the event and the meta agree
1555    core::persist_last_failure(block_id, Some(failure), mstore, event_bus);
1556    if let Some(broker) = broker {
1557        broker.publish_event::<crate::backend::mps_events::AgentFailed>(failure, vec![format!("block:{}", block_id)], 1);
1558    }
1559}
1560
1561/// Classify a final error line with [`classify_exit_line`] and, if it is a
1562/// failure, [`surface_failure`] it. Returns whether it was surfaced.
1563fn surface_error_line(
1564    block_id: &str,
1565    exit_code: Option<i32>,
1566    line: &str,
1567    broker: Option<&mps::Broker>,
1568    mstore: &Option<Arc<Store>>,
1569    event_bus: &Option<Arc<EventBus>>,
1570) -> bool {
1571    let Some(failure) = classify_exit_line(exit_code, line) else {
1572        return false;
1573    };
1574    surface_failure(block_id, &failure, broker, mstore, event_bus);
1575    true
1576}
1577
1578pub mod eager_resume;
1579pub mod input;
1580#[cfg(test)]
1581use input::park_tool_permission_request;
1582pub mod lifecycle;
1583pub mod outcome_line;
1584pub mod process_waiter;
1585pub mod queue;
1586pub mod queued;
1587use queued::{Deferred, QueuedMessage};
1588pub mod resume_retry;
1589pub mod segments;
1590pub use resume_retry::pane_history_session_id;
1591pub mod spawn;
1592pub mod spawn_steps;
1593pub mod status;
1594pub mod stderr_reader;
1595pub mod stdout_reader;
1596
1597#[cfg(test)]
1598mod tests;