agentmux_srv_core/backend/blockcontroller/persistent/process_waiter.rs
1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The persistent CLI's process waiter task, started by `spawn_process`
5//! (`spawn.rs`): the `child.wait()` arm (the process exited on its own) and
6//! the kill arm (a stop or restart asked for it).
7
8use super::*;
9
10/// What the process waiter task captures from `spawn_process`.
11pub(super) struct ProcessWaiterCtx {
12 pub(super) child: tokio::process::Child,
13 pub(super) kill_rx: tokio::sync::oneshot::Receiver<KillRequest>,
14 pub(super) stderr_reader_handle: Option<tokio::task::JoinHandle<()>>,
15 pub(super) stdout_reader_handle: tokio::task::JoinHandle<()>,
16 pub(super) segment_wait: super::segments::SegmentRef,
17 pub(super) global_output_zone_wait: Option<String>,
18 pub(super) record_fence_wait: Option<crate::backend::agent_admission::RecordFence>,
19 pub(super) block_id_wait: String,
20 pub(super) inner_wait: Arc<Mutex<PersistentInner>>,
21 pub(super) broker_wait: Option<Arc<mps::Broker>>,
22 pub(super) mstore_wait: Option<Arc<Store>>,
23 pub(super) event_bus_wait: Option<Arc<EventBus>>,
24 pub(super) health_wait: Arc<TurnActivityTracker>,
25 pub(super) filestore_wait: Option<Arc<FileStore>>,
26 pub(super) agent_id_wait: Option<String>,
27 pub(super) self_ref_wait: std::sync::Weak<PersistentSubprocessController>,
28 pub(super) my_generation_wait: u64,
29 pub(super) pid_wait: u32,
30 pub(super) nonce_wait: u64,
31 /// This spawn's registration nonce, which the stdout reader recorded its
32 /// MCP report under (`backend::mcp_observed`).
33 pub(super) mcp_owner_wait: u64,
34}
35
36/// What the exit steps share: the task's captures other than the child, the kill channel and the
37/// reader handles, which the two arms of `run_process_waiter` consume.
38struct ProcessWaiter {
39 segment: super::segments::SegmentRef,
40 global_output_zone: Option<String>,
41 record_fence: Option<crate::backend::agent_admission::RecordFence>,
42 block_id: String,
43 inner: Arc<Mutex<PersistentInner>>,
44 broker: Option<Arc<mps::Broker>>,
45 mstore: Option<Arc<Store>>,
46 event_bus: Option<Arc<EventBus>>,
47 health: Arc<TurnActivityTracker>,
48 filestore: Option<Arc<FileStore>>,
49 agent_id: Option<String>,
50 self_ref: std::sync::Weak<PersistentSubprocessController>,
51 generation: u64,
52 pid: u32,
53 nonce: u64,
54 mcp_owner: u64,
55}
56
57/// What the locked part of an exit decided, for the steps that run once the lock is dropped.
58struct ExitRecord {
59 is_current_generation: bool,
60 effects: Vec<persistent_resume::ResumeEffect>,
61 respawn_after_restart: bool,
62}
63
64impl PersistentSubprocessController {
65 /// Body of the process waiter task.
66 pub(super) async fn run_process_waiter(ctx: ProcessWaiterCtx) {
67 let ProcessWaiterCtx {
68 mut child,
69 kill_rx,
70 stderr_reader_handle,
71 stdout_reader_handle,
72 segment_wait,
73 global_output_zone_wait,
74 record_fence_wait,
75 block_id_wait,
76 inner_wait,
77 broker_wait,
78 mstore_wait,
79 event_bus_wait,
80 health_wait,
81 filestore_wait,
82 agent_id_wait,
83 self_ref_wait,
84 my_generation_wait,
85 pid_wait,
86 nonce_wait,
87 mcp_owner_wait,
88 } = ctx;
89 let waiter = ProcessWaiter {
90 block_id: block_id_wait,
91 inner: inner_wait,
92 broker: broker_wait,
93 mstore: mstore_wait,
94 event_bus: event_bus_wait,
95 health: health_wait,
96 filestore: filestore_wait,
97 agent_id: agent_id_wait,
98 self_ref: self_ref_wait,
99 generation: my_generation_wait,
100 pid: pid_wait,
101 nonce: nonce_wait,
102 mcp_owner: mcp_owner_wait,
103 segment: segment_wait,
104 global_output_zone: global_output_zone_wait,
105 record_fence: record_fence_wait,
106 };
107 tokio::select! {
108 status = child.wait() => {
109 waiter.on_exited(status, stderr_reader_handle, stdout_reader_handle).await;
110 }
111 Ok(request) = kill_rx => {
112 waiter.on_kill(request, &mut child, stderr_reader_handle, stdout_reader_handle).await;
113 }
114 }
115 }
116}
117
118impl ProcessWaiter {
119 /// The process exited on its own: `child.wait()` resolved.
120 async fn on_exited(
121 &self,
122 status: std::io::Result<std::process::ExitStatus>,
123 stderr_reader_handle: Option<tokio::task::JoinHandle<()>>,
124 stdout_reader_handle: tokio::task::JoinHandle<()>,
125 ) {
126 let exit_code = status.map(|s| s.code().unwrap_or(-1)).unwrap_or(-1);
127 super::segments::record_segment_end(
128 &self.segment,
129 crate::backend::continuity_segments::exit_reason(exit_code),
130 crate::backend::agent_admission::fenced_zone(self.global_output_zone.as_deref(), &self.record_fence),
131 );
132 tracing::info!(
133 block_id = %self.block_id,
134 exit_code = exit_code,
135 "persistent process exited"
136 );
137
138 self.settle_after_exit(stderr_reader_handle, stdout_reader_handle).await;
139 self.wait_for_drain_idle().await;
140
141 let record = self.record_exit(exit_code);
142 self.publish_process_gone(record.is_current_generation);
143
144 if record.is_current_generation {
145 // The process is gone — nothing is waiting on the user
146 // any more (Phase 5 notifications).
147 if let Some(r) = self.broker.as_ref().and_then(crate::backend::notify::router::get) {
148 r.resolve_nonblocking(&self.block_id, crate::backend::notify::policy::Family::Input);
149 }
150 // Notify health monitor so Stalled/Dead watchdog stops.
151 self.health.set_exited(exit_code);
152
153 self.deregister_from_muxbus();
154
155 // Clear active pid — clean exit, no recovery needed.
156 self.clear_active_pid();
157 }
158
159 self.apply_exit_effects(exit_code, record.effects);
160
161 self.respawn_if_due(record.respawn_after_restart);
162 }
163
164 /// Give the stderr and stdout readers their bounded chance to finish after the process exited.
165 async fn settle_after_exit(
166 &self,
167 stderr_reader_handle: Option<tokio::task::JoinHandle<()>>,
168 stdout_reader_handle: tokio::task::JoinHandle<()>,
169 ) {
170 // Give the stderr reader a bounded chance to fully
171 // drain and react to whatever it saw right before this
172 // process exited — codex P1/P2 on PR #2360 (second
173 // review pass): `child.wait()` resolving does NOT mean
174 // the stderr reader (an independently-scheduled task)
175 // has already called `poison_resume` for a "No
176 // conversation found" line, or finished ITS OWN
177 // subsequent `persist_session_id("")` call. Without
178 // this, two failure modes were possible: (1) this task
179 // could resolve the resume state (`ProcessExited`, in `record_exit`)
180 // before the stderr reader ever promotes it to
181 // `ConfirmedRetry`, permanently losing
182 // the retry for the exact case it exists to catch, and
183 // (2) a confirmed retry's fresh session id (persisted
184 // by the NEW process's own stdout reader once
185 // respawned) could be silently overwritten by this
186 // exiting process's stderr task finally getting around
187 // to persisting an empty one, corrupting continuity
188 // despite the retry having succeeded. 500ms is
189 // generous — the stderr pipe closes and drains almost
190 // immediately once the process has genuinely exited.
191 //
192 // If it DOES take longer than that (e.g. `persist_session_id`
193 // blocked on a slow store call), a bare `timeout()` alone
194 // is not enough — codex P1 on PR #2360 (fifth review
195 // pass): `timeout()` only stops WAITING for the handle,
196 // it does not cancel the underlying task, which keeps
197 // running in the background and can still call
198 // `poison_resume`/`persist_session_id("")` AFTER this
199 // task has already moved on (discarded the still-
200 // tentative retry, or started a fresh child whose own
201 // new session id that late write would then corrupt).
202 // `abort()` on a separately-obtained `AbortHandle`
203 // actually cancels it — the task stops at its next
204 // yield point and can never reach either call again.
205 //
206 // codex P1 on PR #2371 (round 1): the stdout reader
207 // performs synchronous FileStore/SQLite writes that
208 // can legitimately contend for multiple seconds
209 // (SQLite's own busy timeout) — a short bound (the
210 // stderr reader's 500ms above) would abort it
211 // mid-line under ordinary contention, discarding
212 // still-unread assistant/result frames and
213 // truncating the persisted transcript.
214 //
215 // codex P1 on PR #2371 (round 2): but an UNBOUNDED
216 // await isn't safe either — if the CLI spawned a
217 // background descendant that inherited its stdout
218 // descriptor, killing/waiting for the direct child
219 // does NOT close that descriptor, so this reader's
220 // `lines.next_line()` may never see EOF, hanging this
221 // exit-handling step (and everything after it —
222 // health status, muxbus deregistration, the retry
223 // decision itself) forever.
224 //
225 // 10s is the compromise: generous enough that
226 // ordinary SQLite contention never triggers the
227 // abort (avoiding the round-1 truncation risk), but
228 // still a hard ceiling so a genuinely stuck
229 // descendant-held pipe (or anything else gone wrong)
230 // can't hang this task indefinitely (closing the
231 // round-2 gap). Aborting our own read loop doesn't
232 // require the OS pipe to actually close — it just
233 // stops OUR wait, accepting we may not have drained
234 // every last buffered line, the same risk profile
235 // the original 500ms bound already accepted, just at
236 // a bound wide enough not to fire under normal load.
237 settle_reader_tasks(&self.block_id, stderr_reader_handle, stdout_reader_handle, "process exit").await;
238 forget_mcp_servers(self.mcp_owner, self.broker.as_deref(), &self.block_id);
239 }
240
241 /// Wait for the queue drain to stop mid-delivery before the retry batch is read as final.
242 async fn wait_for_drain_idle(&self) {
243 // Wait (briefly, bounded) for the drain to finish
244 // appending whatever message it's currently
245 // mid-delivery on before deciding the retry batch
246 // is final (`record_exit`) (#2360): `drain_queue_after_
247 // successful_spawn`'s own "send, then append to the
248 // retry batch" sequence has an unavoidable gap at the
249 // `.await` (a mutex can't be held across it). Without
250 // this wait, the `.take()` in `record_exit` could run in that
251 // exact gap and dispatch a retry missing a message
252 // the doomed process's channel had ALREADY accepted —
253 // it stays marked "accepted" and gets persisted, but
254 // is never actually delivered to any process again.
255 // Same 500ms bound as the stderr-reader wait in `settle_after_exit`,
256 // for the same "best effort, don't hang forever"
257 // reason.
258 for _ in 0..50 {
259 if !self.inner.lock().unwrap().drain_send_in_flight {
260 break;
261 }
262 tokio::time::sleep(std::time::Duration::from_millis(10)).await;
263 }
264 }
265
266 /// The part of an exit that needs the lock: release this generation's process state and let
267 /// the resume state machine decide what the exit means.
268 fn record_exit(&self, exit_code: i32) -> ExitRecord {
269 let mut inner = self.inner.lock().unwrap();
270 // reagentx P1 (round 6 on PR #2373, extended round 8):
271 // this belated exit-handling can run AFTER a fresh
272 // spawn has already superseded this generation (see
273 // `respawn_once_for_leftover_queue`'s own doc comment
274 // and the kill arm (`stop_child`) for the documented race that
275 // makes this reachable) — `inner.spawn_generation` is
276 // bumped on every NEW spawn, so a mismatch here means
277 // this exit is for an already-superseded generation.
278 // Everything gated on it belongs to THIS exact
279 // process (its own pid/exit code/stdin/kill channel,
280 // the shared `proc_status` this process last knew to
281 // be true, its own health-monitor/muxbus/registry/
282 // session-recovery registration) — running any of it
283 // unconditionally would corrupt or tear down a newer,
284 // actively-running generation's own state as if IT
285 // had exited. reagentx round 8: the round-6 fix only
286 // gated the field writes, missing
287 // `health.set_exited` (a shared `TurnActivityTracker`
288 // across generations) and the deregistration block
289 // (`deregister_from_muxbus`) — both keyed by `block_id`/`agent_id`, not
290 // generation, so a stale exit incorrectly marked a
291 // live process's health as exited and tore down its
292 // muxbus/registry/session-recovery registration while
293 // it kept running.
294 let is_current_generation = inner.spawn_generation == self.generation;
295 if is_current_generation {
296 self.release_process(&mut inner, exit_code);
297 }
298 // One event resolves the ENTIRE retry/error-line
299 // decision — including any earlier `StopRequested`
300 // (see `stop_process`), already baked into the state
301 // by `persistent_resume::update` before this event
302 // ever arrives. See `persistent_resume`'s module doc
303 // comment for why this replaced four separate field
304 // reads/writes. Safe to call unconditionally even for
305 // a superseded generation — `update()`'s own
306 // generation-matching arms (and `NotTracking`'s
307 // `current_generation`) already no-op a stale event
308 // on their own.
309 let effects = inner
310 .apply_resume_event(persistent_resume::ResumeEvent::ProcessExited { generation: self.generation });
311 if is_current_generation {
312 PersistentSubprocessController::set_status(&mut inner, STATUS_DONE);
313 }
314 // A committed config restart whose process exited on its
315 // own before the kill was consumed: this arm won the
316 // `select!`, so it must finish the restart too (codex P1 on
317 // #3990). Acted on at the end of `on_exited`, like
318 // `on_kill`; a stale-resume retry spawning first supersedes it.
319 let respawn_after_restart = PersistentSubprocessController::config_restart_due_locked(&inner, self.generation);
320 drop(inner);
321 ExitRecord { is_current_generation, effects, respawn_after_restart }
322 }
323
324 /// This generation's process is gone: drop the handles and the lease the exit or the kill made
325 /// stale.
326 fn release_process(&self, inner: &mut PersistentInner, exit_code: i32) {
327 crate::identity::token_warmup::release(&self.block_id);
328 inner.proc_exit_code = exit_code;
329 if let Some(ended) = inner.current_pid.take() {
330 crate::backend::cli_native::pids::clear(&self.block_id, ended);
331 }
332 inner.stdin_tx = None;
333 inner.kill_tx = None;
334 // This process no longer drives the agent: release
335 // its single-live-instance lease (on the last `Arc`).
336 inner.agent_lease = None;
337 }
338
339 /// The process is gone: say so, whatever else the arm publishes.
340 fn publish_process_gone(&self, is_current_generation: bool) {
341 if is_current_generation {
342 if let Some(b) = self.broker.as_ref() {
343 super::status::publish_runtime_event(&self.inner, b, &self.block_id);
344 }
345 }
346 }
347
348 /// Deregister from muxbus so later sends fall through to the lower tiers instead of resolving to
349 /// a dead block. Mirrors the shell controller's exit path.
350 fn deregister_from_muxbus(&self) {
351 // This exact process's resources are gone either way; if a retry/fallback
352 // respawn has ALREADY re-registered, the guards below
353 // leave its fresh registration in place.
354 // All removals are compare-and-remove keyed on this
355 // spawn's process-wide registration nonce (issue
356 // #2363): the caller's `is_current_generation` gate
357 // was read once, and a fallback/retry respawn's
358 // fresh registration can land on a parallel task
359 // between that read and these calls — an
360 // unconditional removal here would wipe the NEW
361 // spawn's entry with nothing left to re-register
362 // it. Nonce, not generation: a replacement
363 // controller's spawn restarts at generation 1 and
364 // could collide with ours (codex P1 on PR #2500).
365 let registration_was_ours = crate::backend::reactive::get_global_handler()
366 .unregister_block_if_nonce(&self.block_id, self.nonce);
367 sweep_stopped_registrations(&self.block_id, self.nonce, registration_was_ours);
368 if let Some(ref agent_id) = self.agent_id {
369 remove_registration_files_by_name(agent_id, self.nonce);
370 // The cloud subscriber's agent set records no
371 // per-agent identity to compare against, so the
372 // in-memory registration's outcome above stands
373 // in: if a newer spawn already re-registered,
374 // its cloud subscription must survive too.
375 // …but a registration already gone reads `false`
376 // too; then nobody holds the agent and it must go,
377 // or its WAN lease is renewed forever.
378 // `drop_if_orphaned` re-checks after removing, so a
379 // respawn registering meanwhile keeps its entry
380 // (Codex P2 on #3897).
381 let handler = crate::backend::reactive::get_global_handler();
382 let still_held = handler.has_live_name(agent_id);
383 if crate::muxbus::cloud_subscriber::drop_cloud_subscription_on_exit(
384 registration_was_ours,
385 still_held,
386 ) {
387 if let Some(sub) = crate::muxbus::cloud_subscriber::get_global_subscriber() {
388 sub.drop_if_orphaned(agent_id, |a| handler.has_live_name(a));
389 }
390 }
391 }
392 }
393
394 /// Clear the active pid, with no recovery needed.
395 fn clear_active_pid(&self) {
396 // Compare-and-clear (issue #2363): only if the
397 // recorded pid is still THIS process's — a fallback
398 // respawn may have re-registered a fresh pid on a
399 // parallel task between the caller's generation gate
400 // and this call.
401 if let Some(ref mstore) = self.mstore {
402 super::super::session_recovery::clear_active_pid_if_pid(mstore, &self.block_id, self.pid);
403 }
404 }
405
406 /// What the resume state machine decided the exit means: say how the turn ended, or retry.
407 fn apply_exit_effects(&self, exit_code: i32, effects: Vec<persistent_resume::ResumeEffect>) {
408 // A stale `--resume <sid>` is exactly what killed this
409 // process (`retry_after_resume_failure`'s doc comment) —
410 // retry the same message once, fresh, WITHOUT publishing
411 // this transient failure as a completed turn first.
412 // codex P2 on PR #2360 (second review pass): publishing
413 // "done"/turn_active:false here would let the mounted
414 // UI (trackTurnJustEnded, a deferred controller refresh)
415 // treat this failed attempt as the real end of the
416 // user's turn before the retry's own fresh "running"
417 // status ever lands. reagentx/codex never reviewed this
418 // controller type in PR #2338 (see docs/retro/
419 // RETRO_STALE_RESUME_SESSION_ID_ACROSS_CHANNELS_2026_07_29.md).
420 for effect in effects {
421 match effect {
422 // SPEC_AGENT_PANE_HISTORY_ALIGNMENT_2026_08_05.md
423 // §2.1: the `ConfirmedRetry` + `ProcessExited`
424 // (not-stopped) arm now bundles this alongside
425 // `FireRetry` — the resume's fate (Fresh) is
426 // already known here, even though the retry
427 // hasn't launched yet (`fire_retry`).
428 persistent_resume::ResumeEffect::EmitSessionOutcome { outcome, attempted_sid, actual_sid } => {
429 self.emit_session_outcome(outcome, attempted_sid, actual_sid);
430 }
431 persistent_resume::ResumeEffect::PersistImmediately(line)
432 | persistent_resume::ResumeEffect::FlushErrorLine(line) => {
433 self.persist_exit_error(exit_code, &line);
434 }
435 persistent_resume::ResumeEffect::FireRetry { retry, held_error_line, attempted_sid } => {
436 self.fire_retry(retry, held_error_line, attempted_sid);
437 }
438 persistent_resume::ResumeEffect::PublishDone => self.publish_done(exit_code),
439 }
440 }
441 }
442
443 fn emit_session_outcome(
444 &self,
445 outcome: persistent_resume::SessionOutcome,
446 attempted_sid: String,
447 actual_sid: Option<String>,
448 ) {
449 publish_resume_retry_status(&self.broker, &self.block_id, "resolved");
450 // Same retraction as the stdout-reader site
451 // (`stdout_reader.rs`) — this arm reaches `Fresh` today, but
452 // the clear is keyed on the outcome rather
453 // than on which arm produced it, so it stays
454 // correct if that ever changes.
455 if matches!(outcome, persistent_resume::SessionOutcome::Resumed) {
456 if let Some(ref store) = self.mstore {
457 super::super::session_recovery::clear_resume_failed(
458 store,
459 &self.event_bus,
460 &self.block_id,
461 );
462 }
463 }
464 let line = session_outcome_line(outcome, attempted_sid, actual_sid);
465 self.append_output_line(&line);
466 }
467
468 fn persist_exit_error(&self, exit_code: i32, line: &str) {
469 // Safety net: a "Reconnecting…" left showing from
470 // an earlier retry attempt on this same block must
471 // not get stuck forever just because THIS exit
472 // ended up genuinely non-retryable — a harmless
473 // no-op publish in the (common) case where no
474 // retry was in flight at all.
475 publish_resume_retry_status(&self.broker, &self.block_id, "resolved");
476 self.append_output_line(line);
477 // Classify + surface this exit's error to the
478 // pane's failure-recovery UI —
479 // SPEC_PERSISTENT_CONTROLLER_FAILURE_CLASSIFICATION.
480 // Reached only for PersistImmediately/FlushErrorLine
481 // — the resume machinery has already decided this
482 // exit is NOT being silently retried (contrast
483 // FireRetry (`fire_retry`), which must stay invisible to
484 // the user).
485 surface_error_line(
486 &self.block_id,
487 Some(exit_code),
488 line,
489 self.broker.as_deref(),
490 &self.mstore,
491 &self.event_bus,
492 );
493 }
494
495 fn fire_retry(&self, retry: persistent_resume::RetryPayload, held_error_line: Option<String>, attempted_sid: String) {
496 // Issue #2368: the retry is firing and will
497 // very likely succeed within milliseconds —
498 // the doomed attempt's own terminal error
499 // result must never reach the user, so it's
500 // dropped (not flushed) as long as the retry
501 // actually launches. Handed to
502 // `retry_after_resume_failure` itself (codex
503 // P2 on PR #2371) rather than dropped here
504 // unconditionally — a retry that turns out
505 // NOT to launch (this controller already
506 // gone, or the fresh spawn itself failing)
507 // must still flush it, or an already-
508 // accepted prompt ends in total silence.
509 if let Some(ctrl) = self.self_ref.upgrade() {
510 tracing::warn!(
511 block_id = %self.block_id,
512 "stale --resume session id caused this exit — retrying now (find_recovery_session_id may still resume a real, on-disk session rather than starting blank)"
513 );
514 ctrl.retry_after_resume_failure(
515 self.generation,
516 retry.config,
517 retry.messages,
518 held_error_line,
519 attempted_sid,
520 );
521 } else {
522 // reagentx P2 on PR #2776: the controller
523 // itself is already gone — no retry will
524 // ever fire for this batch, so any
525 // "Reconnecting…" left showing from an
526 // earlier attempt on this same block must
527 // be resolved here; nothing else will.
528 publish_resume_retry_status(&self.broker, &self.block_id, "resolved");
529 if let Some(line) = held_error_line {
530 // The controller itself is already gone
531 // (weak ref invalidated) — nothing can
532 // retry this batch at all, so flush
533 // directly via this task's own captured
534 // broker/filestore rather than going
535 // through `ctrl`.
536 self.append_output_line(&line);
537 }
538 }
539 }
540
541 fn publish_done(&self, exit_code: i32) {
542 if let Some(ref broker) = self.broker {
543 let status = super::super::agent_runtime_status(
544 &self.block_id,
545 0,
546 STATUS_DONE,
547 exit_code,
548 false,
549 );
550 super::super::publish_controller_status(broker, &status);
551 }
552 }
553
554 /// Finish a committed config restart whose old process is gone.
555 fn respawn_if_due(&self, respawn_after_restart: bool) {
556 if respawn_after_restart {
557 if let Some(ctrl) = self.self_ref.upgrade() {
558 ctrl.respawn_after_config_restart(self.generation);
559 }
560 }
561 }
562
563 fn append_output_line(&self, line: &str) {
564 if let Some(ref broker) = self.broker {
565 super::super::shell::handle_append_block_file(
566 broker,
567 &self.block_id,
568 PERSISTENT_OUTPUT_SUBJECT,
569 line.as_bytes(),
570 self.filestore.as_ref(),
571 crate::backend::agent_admission::fenced_zone(self.global_output_zone.as_deref(), &self.record_fence),
572 );
573 }
574 }
575
576 /// A stop or restart asked for the process to go.
577 async fn on_kill(
578 &self,
579 request: KillRequest,
580 child: &mut tokio::process::Child,
581 stderr_reader_handle: Option<tokio::task::JoinHandle<()>>,
582 stdout_reader_handle: tokio::task::JoinHandle<()>,
583 ) {
584 let graceful_deadline = match request {
585 KillRequest::Force => None,
586 KillRequest::Graceful(deadline) => Some(deadline),
587 };
588 // Why it's going away, read before the kill changes
589 // anything: `shutdown` marks a pane close for this
590 // generation; `restart_pending` a runtime-config restart.
591 let segment_end_reason = {
592 let inner = self.inner.lock().unwrap();
593 crate::backend::continuity_segments::kill_reason(
594 inner.shutdown_generation == Some(self.generation),
595 inner.restart_pending,
596 )
597 };
598 tracing::info!(
599 block_id = %self.block_id,
600 force = graceful_deadline.is_none(),
601 "persistent process kill requested"
602 );
603 self.stop_child(child, graceful_deadline).await;
604 super::segments::record_segment_end(
605 &self.segment,
606 segment_end_reason,
607 crate::backend::agent_admission::fenced_zone(self.global_output_zone.as_deref(), &self.record_fence),
608 );
609
610 // Mirror the child.wait() arm's bounded await+abort of
611 // both reader tasks (`settle_after_exit`) before resolving the resume
612 // state (`StopRequested` + `ProcessExited`, in `record_kill`)
613 // (#2371). Without this, a stop racing the doomed
614 // attempt's in-flight terminal error line could resolve
615 // the state before the stdout reader holds the line
616 // back; the lagging reader would then find `NotTracking`
617 // and persist the line on its own, instead of it being
618 // flushed (`flush_stop_effects`) as part of this stop.
619 // codex P1 on PR #2371 (round 2): a bounded wait, not
620 // an unconditional one — see the child.wait() arm's
621 // identical comment (`settle_after_exit`) for the full reasoning. This
622 // matters MORE here: codex flagged that every
623 // remaining cleanup step (clearing current_pid/
624 // kill_tx, STATUS_DONE, muxbus deregistration) runs
625 // AFTER this await, so an unbounded hang here would
626 // leave a user-initiated Stop making the controller
627 // appear permanently alive if a descendant process
628 // ever holds the stdout descriptor open.
629 settle_reader_tasks(&self.block_id, stderr_reader_handle, stdout_reader_handle, "kill").await;
630 forget_mcp_servers(self.mcp_owner, self.broker.as_deref(), &self.block_id);
631
632 let record = self.record_kill();
633 self.publish_process_gone(record.is_current_generation);
634
635 // reagentx P1 on PR #2776: a user-initiated Stop can
636 // land at any point, including mid stale-`--resume`
637 // retry — "Reconnecting…" has no other clearing path on
638 // this branch (unlike `compacting`, which several
639 // turn-end transitions defensively reset), so without
640 // this it would stick on-screen forever with a growing
641 // counter, and a later retry on the same pane would
642 // wrongly keep the stale `startedAt` (ResumeRetryStarted
643 // is a no-op while already reconnecting). Unconditional
644 // and un-gated by `is_current_generation` on purpose —
645 // a harmless no-op when nothing was reconnecting, and
646 // the pane is stopping either way, so there's no
647 // "which generation" ambiguity worth encoding here.
648 publish_resume_retry_status(&self.broker, &self.block_id, "resolved");
649
650 // Flush a held-back error line now, if the resume
651 // state machine produced one — the `StopRequested`
652 // sent in `record_kill` guarantees `ProcessExited` resolves via
653 // the "stop wins" branch (see `persistent_resume::
654 // update`), so `FireRetry` is never actually possible
655 // here, but it's still matched defensively rather
656 // than assumed.
657 self.flush_stop_effects(record.effects);
658
659 if record.is_current_generation {
660 // Notify the turn-activity tracker of the exit —
661 // shared `Arc<TurnActivityTracker>` across
662 // generations, gated the same way as in
663 // `on_exited`.
664 self.health.set_exited(-1);
665 self.deregister_from_muxbus();
666
667 // Clear active pid — user-initiated stop, no recovery needed.
668 self.clear_active_pid();
669 }
670
671 self.respawn_if_due(record.respawn_after_restart);
672 }
673
674 /// Ask the child to go: close stdin and give it until the deadline for a graceful stop, or
675 /// kill it now. Records how it ended in `stop_exit`.
676 async fn stop_child(&self, child: &mut tokio::process::Child, graceful_deadline: Option<std::time::Instant>) {
677 if let Some(deadline) = graceful_deadline {
678 // Graceful: drop stdin to send EOF, then wait briefly
679 {
680 let mut inner = self.inner.lock().unwrap();
681 inner.stdin_tx = None; // drops the sender → stdin writer exits → stdin closes
682 // reagentx P0 on PR #2360 (sixth review pass,
683 // round 10): must clear pending_send_messages/
684 // spawning_in_progress in this SAME lock
685 // acquisition as stdin_tx, not only later
686 // (after child.wait()/the 5s timeout below).
687 // During that window,
688 // drain_queue_after_successful_spawn's
689 // independently-scheduled background task
690 // could observe stdin_tx.is_none() with
691 // messages still queued, classify it as a
692 // stall, and call
693 // respawn_once_for_leftover_queue — spawning a
694 // brand-new CLI process while the user's
695 // graceful stop is still in progress. The
696 // force-kill path doesn't have this gap (it
697 // never clears stdin_tx early — all three
698 // clear together (in `record_kill`), after child.kill()
699 // resolves), only this graceful one, since it
700 // specifically needs stdin_tx gone early to
701 // trigger EOF.
702 inner.pending_send_messages.clear();
703 inner.spawning_in_progress = false;
704 }
705 // Wait until the caller's deadline (a close shares
706 // one deadline across every agent it stops — spec
707 // §9.2), then kill.
708 let killed = tokio::select! {
709 _ = child.wait() => false,
710 _ = tokio::time::sleep_until(tokio::time::Instant::from_std(deadline)) => {
711 // With its process group: its MCP servers go too.
712 let _ = agentmux_common::process::kill_child_and_group(child).await;
713 true
714 }
715 };
716 self.inner.lock().unwrap().stop_exit = Some((self.generation, killed));
717 } else {
718 let _ = agentmux_common::process::kill_child_and_group(child).await;
719 self.inner.lock().unwrap().stop_exit = Some((self.generation, true));
720 }
721 }
722
723 /// The part of a kill that needs the lock; the kill arm's counterpart of `record_exit`.
724 fn record_kill(&self) -> ExitRecord {
725 let mut inner = self.inner.lock().unwrap();
726 // reagentx P1 (round 6 on PR #2373, extended round 8):
727 // same reasoning as `record_exit` — this
728 // graceful-stop cleanup can itself run AFTER the
729 // documented race in `stop_child` (dropping `stdin_tx`
730 // early to trigger EOF lets
731 // `respawn_once_for_leftover_queue` spawn a brand-new
732 // generation while this kill is still mid-flight) has
733 // already superseded this generation. Everything
734 // gated on it belongs to THIS exact kill (its own
735 // pid/exit code/stdin/kill channel, its own spawn
736 // claim/queue, the shared `proc_status` this stop
737 // last knew to be true, its own health-monitor/
738 // muxbus/registry/session-recovery registration) —
739 // running any of it unconditionally would corrupt or
740 // tear down a newer, actively-running generation's
741 // own state as if IT had been stopped.
742 let is_current_generation = inner.spawn_generation == self.generation;
743 if is_current_generation {
744 self.release_process(&mut inner, -1);
745 }
746 // A user-initiated kill overrides any resume-retry
747 // decision in flight, for a REUSED controller instance
748 // (`resync_controller` can reuse the same instance
749 // across a kill+restart cycle) the same way an
750 // in-flight Stop already does for the child.wait() arm (`record_exit`)
751 // — reusing that exact `StopRequested` + `ProcessExited`
752 // event pair here instead of duplicating the "stop
753 // wins" logic against raw fields. codex P2 on PR #2371:
754 // this also means a stashed error line is never
755 // silently lost on a user-initiated stop (it may be a
756 // genuine error the stop itself interrupted) — it's
757 // flushed (`flush_stop_effects`) via the effects this produces, same as
758 // the "genuinely done" case. Safe to call
759 // unconditionally even for a superseded generation —
760 // `update()`'s own generation-matching arms already
761 // no-op a stale event on their own.
762 inner.apply_resume_event(persistent_resume::ResumeEvent::StopRequested {
763 generation: self.generation,
764 });
765 let effects = inner
766 .apply_resume_event(persistent_resume::ResumeEvent::ProcessExited { generation: self.generation });
767 // codex P1 on PR #2360 (sixth review pass, round 5):
768 // an active spawn claim's own background drain
769 // (`drain_queue_after_successful_spawn`) is a
770 // SEPARATE, independently-scheduled task — killing
771 // this process does not cancel it. Left untouched, its
772 // next check would see `stdin_tx` gone with messages
773 // still queued, treat that as a stall, and hand off to
774 // `respawn_once_for_leftover_queue` — silently
775 // reviving the agent moments after the user explicitly
776 // stopped it. Clearing the queue AND releasing the
777 // claim here means that same check instead sees an
778 // empty queue and just concludes normally, with no
779 // fallback respawn triggered. Gated the same way as
780 // the process state — a NEWER generation's own claim/queue must
781 // never be cleared by this stale one's cleanup.
782 if is_current_generation {
783 inner.pending_send_messages.clear();
784 inner.spawning_in_progress = false;
785 PersistentSubprocessController::set_status(&mut inner, STATUS_DONE);
786 }
787 // This kill was a deferred config restart of THIS
788 // generation (`config_restart_due_locked`). Acted on at the
789 // end of `on_kill`, after the deregistration, because
790 // the replacement registers itself afresh. Only read here:
791 // the spawn claim consumes the token, so a Stop landing
792 // before then still wins.
793 let respawn_after_restart = PersistentSubprocessController::config_restart_due_locked(&inner, self.generation);
794 drop(inner);
795 ExitRecord { is_current_generation, effects, respawn_after_restart }
796 }
797
798 fn flush_stop_effects(&self, effects: Vec<persistent_resume::ResumeEffect>) {
799 for effect in effects {
800 let line = match effect {
801 persistent_resume::ResumeEffect::PersistImmediately(line)
802 | persistent_resume::ResumeEffect::FlushErrorLine(line) => Some(line),
803 persistent_resume::ResumeEffect::FireRetry { held_error_line, .. } => held_error_line,
804 persistent_resume::ResumeEffect::PublishDone => None,
805 // Not actually reachable here today — the "stop
806 // wins" branch of `update()`'s ConfirmedRetry +
807 // ProcessExited arm never produces this effect
808 // (see SPEC_AGENT_PANE_HISTORY_ALIGNMENT_2026_08_05.md
809 // §2.1) — but matched defensively, same as
810 // the `FireRetry` arm in this match, rather than assumed. Reuses
811 // the same "append this line" path as every
812 // other variant here.
813 persistent_resume::ResumeEffect::EmitSessionOutcome {
814 outcome,
815 attempted_sid,
816 actual_sid,
817 } => Some(session_outcome_line(outcome, attempted_sid, actual_sid)),
818 };
819 if let Some(line) = line {
820 self.append_output_line(&line);
821 }
822 }
823 }
824}
825
826/// The CLI is gone, so its MCP servers are too (`backend::mcp_observed`),
827/// unless a newer spawn already reports its own. Here, not at the reader's
828/// end of input: a reader can be aborted unfinished (`settle_reader_tasks`),
829/// and a descendant holding stdout open keeps it from ending at all.
830fn forget_mcp_servers(owner: u64, broker: Option<&mps::Broker>, block_id: &str) {
831 if crate::backend::mcp_observed::forget_owned(block_id, owner) {
832 crate::backend::mcp_observed::publish(broker, block_id);
833 }
834}
835
836/// Wait for the process's reader tasks once it has ended (stderr up to 500ms,
837/// stdout up to 10s), aborting any that overruns. `after` names how the process
838/// ended ("process exit" or "kill") in the warning.
839async fn settle_reader_tasks(
840 block_id: &str,
841 stderr_reader_handle: Option<tokio::task::JoinHandle<()>>,
842 stdout_reader_handle: tokio::task::JoinHandle<()>,
843 after: &str,
844) {
845 if let Some(handle) = stderr_reader_handle {
846 let abort_handle = handle.abort_handle();
847 if tokio::time::timeout(std::time::Duration::from_millis(500), handle).await.is_err() {
848 tracing::warn!(
849 block_id = %block_id,
850 "stderr reader did not finish within 500ms of {after} — aborting it"
851 );
852 abort_handle.abort();
853 }
854 }
855 let abort_handle = stdout_reader_handle.abort_handle();
856 if tokio::time::timeout(std::time::Duration::from_secs(10), stdout_reader_handle)
857 .await
858 .is_err()
859 {
860 tracing::warn!(
861 block_id = %block_id,
862 "stdout reader did not finish within 10s of {after} \
863 (SQLite contention, or a descendant process holding stdout open?) \
864 — aborting it"
865 );
866 abort_handle.abort();
867 }
868}
869
870/// Remove the registration files a stopped spawn left for its block, under every name they are
871/// filed by (slug, former slug, display-name route). An entry a turn wrote for the block's current
872/// name is filed under that name, with no nonce, so the removal keyed on the spawn's own name and
873/// nonce never reaches it, and the agent then reads as running to anything that reads the files
874/// (the ID update's running check). Spares a newer spawn's entries: one registered since leaves
875/// the block registered in memory under a nonce that isn't ours.
876fn sweep_stopped_registrations(block_id: &str, nonce: u64, registration_was_ours: bool) {
877 let newer_spawn_holds_block = !registration_was_ours
878 && crate::backend::reactive::get_global_handler().try_get_agent_by_block(block_id).is_some();
879 if newer_spawn_holds_block {
880 return;
881 }
882 let data_dir = crate::backend::base::get_mux_data_dir();
883 crate::backend::reactive::registry::remove_for_block(&data_dir, block_id, Some(nonce));
884 crate::backend::reactive::registry::remove_shared_for_block_from_env(block_id, Some(nonce));
885}
886
887/// The files a stopped spawn registered under `agent_id`, removed only if they are still its own
888/// (compare-and-remove on its nonce, issue #2363: a respawn's fresh entry stays).
889fn remove_registration_files_by_name(agent_id: &str, nonce: u64) {
890 let data_dir = crate::backend::base::get_mux_data_dir();
891 crate::backend::reactive::registry::remove_if_nonce(&data_dir, agent_id, nonce);
892 crate::backend::reactive::registry::remove_shared_from_env_if_nonce(agent_id, nonce);
893}