Skip to main content

agentmux_srv_core/backend/blockcontroller/persistent/
lifecycle.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Stop/restart and session-identity queries: `stop_process`, the kill request
5//! path, `session_id`, `needs_spawn`, and the deferred-restart flag.
6
7use super::*;
8
9impl PersistentSubprocessController {
10    /// A lease handle of this pane found its lease gone. When the pane's current handle still holds it, the
11    /// loss is an older handle's, superseded by this pane's own newer claim (a start that overlapped an
12    /// earlier one, 2026-10-29): the current process is not the one that lost the agent, so it keeps
13    /// running. Otherwise the pane lost the agent and stops.
14    pub(super) fn on_lease_lost(inner: &Arc<Mutex<PersistentInner>>, block_id: &str, why: &str) {
15        let current = inner.lock().unwrap().agent_lease.clone();
16        if current.is_some_and(|l| l.verify().is_ok()) {
17            tracing::warn!(block_id, why, "agent_admission: an older lease handle of this pane was superseded by its own newer claim — the current process is kept");
18            return;
19        }
20        Self::stop_after_lease_loss(inner, block_id, why);
21    }
22
23    pub fn stop_process(&self, force: bool) -> Result<(), String> {
24        let request = if force {
25            KillRequest::Force
26        } else {
27            KillRequest::Graceful(std::time::Instant::now() + super::super::SHUTDOWN_GRACE)
28        };
29        self.request_stop(request)
30    }
31
32    /// Another process already running on session `sid`: `(block id, closing)`.
33    /// Checks live persistent controllers in the registry, then blocks
34    /// mid-close (out of the registry, process not yet exited).
35    pub(super) fn session_held_elsewhere(&self, sid: &str) -> Option<(String, bool)> {
36        for (block_id, ctrl) in super::super::get_all_controllers() {
37            if block_id == self.block_id {
38                continue;
39            }
40            if let Some(other) = ctrl.as_any().downcast_ref::<PersistentSubprocessController>() {
41                let g = other.inner.lock().unwrap();
42                if g.current_pid.is_some() && g.session_id.as_deref() == Some(sid) {
43                    return Some((block_id, false));
44                }
45            }
46        }
47        let store = self.mstore.as_ref()?;
48        super::super::closing_blocks_still_running()
49            .into_iter()
50            .filter(|block_id| *block_id != self.block_id)
51            .find(|block_id| {
52                store
53                    .get::<crate::backend::obj::Block>(block_id)
54                    .ok()
55                    .flatten()
56                    .is_some_and(|b| crate::backend::obj::meta_get_string(&b.meta, core::META_SESSION_ID, "") == sid)
57            })
58            .map(|block_id| (block_id, true))
59    }
60
61    /// Another pane of this process holding agent `uid`'s single-live-instance
62    /// lease: its block id. Whatever session either pane holds — a pane with
63    /// a stale id refused because the agent's live pane holds the lease is
64    /// still "open in another pane", not "another instance" (Camper on #3935).
65    pub(super) fn agent_held_by_other_pane(&self, uid: &str) -> Option<String> {
66        local_holder_of(uid, &self.block_id)
67    }
68
69    pub(super) fn request_stop(&self, request: KillRequest) -> Result<(), String> {
70        Self::request_stop_on(&self.inner, request)
71    }
72
73    /// [`request_stop`] over just the shared state, for the `'static`
74    /// future [`Controller::shutdown`] returns.
75    pub(super) fn request_stop_on(inner_arc: &Arc<Mutex<PersistentInner>>, request: KillRequest) -> Result<(), String> {
76        Self::request_stop_inner(inner_arc, request, false, false);
77        Ok(())
78    }
79
80    /// Apply a deferred runtime-config restart: stop the current process (as
81    /// `stop_process(false)` does) WITHOUT clearing the restart token the turn
82    /// boundary set (`PersistentInner::config_restart_generation`), so the exit
83    /// handler brings the replacement up. It never sets the token either: a
84    /// Stop that landed between the boundary and this call already cleared it
85    /// and took the kill channel, and must stay in force (codex P1 on #3990).
86    pub(super) fn stop_for_config_restart(&self) {
87        let request = KillRequest::Graceful(std::time::Instant::now() + super::super::SHUTDOWN_GRACE);
88        Self::request_stop_inner(&self.inner, request, false, true);
89    }
90
91    /// `Agents fresh` (SPEC_AGENT_SELF_COMPACTION_2026_10_23.md §3.3): end
92    /// this provider session so the next message starts a new one. Clears the
93    /// session id here and on the block, so nothing resumes it, then stops the
94    /// CLI as a Stop does. The next message spawns a fresh CLI onto the pane's
95    /// history (no continuation packet: `spawn.rs` skips it for this start), and
96    /// a new segment of the agent's chain (`continuity_segments`), so the old
97    /// session stays in its record. Only between turns. Returns the old id.
98    pub fn start_fresh_session(&self) -> Result<Option<String>, &'static str> {
99        // The idle check and the stop are one `inner` acquisition, as message
100        // delivery's turn reservation is: a message arriving at the boundary
101        // either started its turn first (refused here, the caller retries) or
102        // finds the stop pending and is refused.
103        let (old, kill_tx) = {
104            let mut inner = self.inner.lock().unwrap();
105            if inner.stop_pending || inner.restart_pending {
106                return Err("the agent's process is already stopping or restarting");
107            }
108            if self.health_monitor.is_active_turn() {
109                return Err("a turn is running");
110            }
111            let old = inner.session_id.take();
112            // The retiring process's reader may still capture the old id from
113            // its result frame; a poisoned id is never adopted or resumed.
114            if let Some(sid) = &old {
115                inner.resume_poisoned = Some(sid.clone());
116            }
117            (old, Self::stop_locked(&mut inner, false, false).0)
118        };
119        super::super::core::persist_session_id(&self.block_id, "", &self.mstore, &self.event_bus);
120        if let Some(tx) = kill_tx {
121            let _ = tx.send(KillRequest::Graceful(std::time::Instant::now() + super::super::SHUTDOWN_GRACE));
122        }
123        Ok(old)
124    }
125
126    /// Whether `release_to_other_instance` would do anything: this pane holds a lease and has a process to stop.
127    pub fn can_release(&self) -> bool {
128        let inner = self.inner.lock().unwrap();
129        inner.agent_lease.is_some() && inner.kill_tx.is_some()
130    }
131
132    /// A kill for teardown: drains the deferred queue in the SAME `inner`
133    /// acquisition that issues the kill, and returns what it drained for the
134    /// caller to report. Draining in a second acquisition left a window
135    /// after the kill request where a flush could write a deferred message
136    /// into the process being killed, and leave the report an empty queue:
137    /// lost, with no stranded warning (codex P2 on #3562). Once this lock is
138    /// released, `stop_pending` holds anything queued later.
139    pub(super) fn request_stop_draining_deferred(&self, request: KillRequest) -> Vec<Deferred> {
140        Self::request_stop_inner(&self.inner, request, true, false)
141    }
142
143    /// `config_restart`: this stop is a deferred runtime-config restart's own
144    /// ([`Self::stop_for_config_restart`]), which leaves the restart token as
145    /// the boundary left it. Every other stop clears it in this same
146    /// acquisition, so a Stop or pane close landing after the restart was
147    /// committed wins, and nothing respawns behind it.
148    pub(super) fn request_stop_inner(
149        inner_arc: &Arc<Mutex<PersistentInner>>,
150        request: KillRequest,
151        drain_deferred: bool,
152        config_restart: bool,
153    ) -> Vec<Deferred> {
154        let (kill_tx, drained) = Self::stop_locked(&mut inner_arc.lock().unwrap(), drain_deferred, config_restart);
155        if let Some(tx) = kill_tx {
156            let _ = tx.send(request);
157        }
158        drained
159    }
160
161    /// The bookkeeping of a stop request, in the caller's `inner` acquisition:
162    /// the kill channel to send on, and what `drain_deferred` drained.
163    fn stop_locked(
164        inner: &mut PersistentInner,
165        drain_deferred: bool,
166        config_restart: bool,
167    ) -> (Option<tokio::sync::oneshot::Sender<KillRequest>>, Vec<Deferred>) {
168        // Recorded unconditionally, not only when `kill_tx` is already
169        // `None` — codex P1 on PR #2360 (round 16, commit ce1642d90):
170        // `stop_process` can race a process that already exited (a
171        // confirmed stale-`--resume` death) and is about to be
172        // silently retried — sending through `kill_tx` is futile in
173        // that window regardless of whether it's already `None` (the
174        // exit-handler cleared it) or still `Some` (`tokio::select!`
175        // already committed to the `child.wait()` exit arm before
176        // this call reached the lock, so the `kill_rx` arm will never
177        // be polled again even if the send succeeds). Recording this
178        // as a `StopRequested` event — resolved by
179        // `persistent_resume::update` once `ProcessExited` arrives —
180        // is the only way the exit-handler's retry decision can know
181        // the user explicitly asked to stop.
182        let generation = inner.spawn_generation;
183        inner.apply_resume_event(persistent_resume::ResumeEvent::StopRequested { generation });
184        inner.stop_pending = true;
185        if !config_restart {
186            inner.config_restart_generation = None;
187            inner.stop_watch.note_stop();
188        }
189        let drained = if drain_deferred {
190            inner.deferred_deliveries.drain(..).collect()
191        } else {
192            Vec::new()
193        };
194        (inner.kill_tx.take(), drained)
195    }
196
197    pub fn session_id(&self) -> Option<String> {
198        self.inner.lock().unwrap().session_id.clone()
199    }
200
201    /// True when this controller is registered but has **no live process and no
202    /// spawn already in flight** — the state a lazily-registered controller sits
203    /// in between `register` ("spawns on first message") and its first
204    /// `send_message`.
205    ///
206    /// In that state `inject_message` cannot deliver: it has no spawn config and
207    /// only writes to a live `stdin_tx`, so it returns "persistent process not
208    /// running". The caller can, however, start a *turn* — `run_agent_turn`
209    /// re-reads the spawn config from block metadata and calls `send_message`,
210    /// which does spawn. This predicate is what lets the reactive delivery path
211    /// tell those two situations apart. See
212    /// `docs/reports/REPORT_JEKT_DELIVERY_DROPS_UNSPAWNED_PERSISTENT_AGENTS_2026_09_03.md`.
213    ///
214    /// **The invariant this must uphold:** `needs_spawn() == true` implies a
215    /// subsequent `send_message` takes `decide_send_action`'s `BecomeSpawner`
216    /// branch — i.e. it really spawns and delivers. It must never be true in a
217    /// state where `send_message` would instead return `SendAction::Queued`,
218    /// because `Queued` returns `Ok(())` having delivered nothing, the reactive
219    /// path maps that to `Ok(true)`, and the caller is told the message landed
220    /// when it is still sitting in the queue. `cloud_subscriber` only retries
221    /// on `!success`, so a false success is a permanently lost message.
222    ///
223    /// That is why all three exclusions are here, and each mirrors one of
224    /// `decide_send_action`'s own guards:
225    ///
226    /// - `stdin_tx.is_none()` — a live process is steerable; `inject_message`
227    ///   handles it and no turn start is wanted.
228    /// - `!spawning_in_progress` — a caller has already claimed this spawn
229    ///   round (see that field's doc comment on the concurrent-spawn TOCTOU
230    ///   race). Reporting "needs spawn" here would invite a second, racing
231    ///   spawn and orphan a child.
232    /// - `!drain_claim` — a `RetryFlush` drain owns the round. This one is
233    ///   subtle and was missed on the first cut (reagent P1 on PR #2960): when
234    ///   a drain's target process dies mid-flush, the drain **deliberately
235    ///   retains** its claim for the fallback respawn while the exit handler
236    ///   clears `stdin_tx`. Without this term, that window reports "needs
237    ///   spawn", `decide_send_action` then returns `Queued` on the
238    ///   still-held claim, and the message is silently queued while the caller
239    ///   is told it was delivered.
240    ///
241    /// Both excluded windows are retryable rather than lost: the caller gets
242    /// the original delivery error back, which is what lets it come again.
243    ///
244    /// Racy by nature, and safe to be: the process can exit the instant after
245    /// this returns `false`. It is a routing hint, not a guarantee — the spawn
246    /// claim inside `send_message` is what actually serialises spawners. What
247    /// it must not do is report `true` for a state that cannot spawn.
248    pub fn needs_spawn(&self) -> bool {
249        let inner = self.inner.lock().unwrap();
250        inner.stdin_tx.is_none() && !inner.spawning_in_progress && !inner.drain_claim
251    }
252
253    /// Ask this controller to restart itself once the current turn ends,
254    /// instead of being torn down and replaced right now.
255    ///
256    /// Returns `true` when the restart was deferred (a turn is in flight, so
257    /// the caller must NOT replace the controller), `false` when the pane is
258    /// idle and an immediate replace is safe — the caller then proceeds
259    /// exactly as before.
260    ///
261    /// Called from `resync_controller`'s forced-replace path. See
262    /// [`PersistentInner::restart_when_idle`] for what the old
263    /// kill-immediately behaviour destroyed.
264    ///
265    /// Deliberately keyed on the health monitor's `is_active_turn` rather
266    /// than on `stdin_tx.is_some()`: a live process between turns is idle and
267    /// should be replaced immediately (that's the common `/model` case, and
268    /// deferring it would leave the change unapplied until the next turn
269    /// happened to end). It's specifically an IN-FLIGHT turn that must not be
270    /// interrupted.
271    pub fn request_restart_when_idle(&self) -> bool {
272        // The turn-active read and the flag write happen under ONE acquisition
273        // of `inner`, and the turn-end consumer clears `active_turn` under that
274        // same lock — so the two serialize (codex P2 on PR #2858). Interleaved,
275        // this would otherwise observe an active turn, have the consumer run to
276        // completion (seeing `restart_when_idle` still false, so restarting
277        // nothing), and then set the flag — leaving it stuck until the NEXT
278        // turn ended, so the user's next prompt ran with the old config.
279        //
280        // Lock order is `inner` -> health monitor here and in the consumer;
281        // `TurnActivityTracker` never holds its own lock across an `inner`
282        // acquisition, so the order can't invert.
283        let mut inner = self.inner.lock().unwrap();
284        if !self.health_monitor.is_active_turn() {
285            return false;
286        }
287        inner.restart_when_idle = true;
288        drop(inner);
289        // Tell the menu a restart is coming, so a selection that has not
290        // reached the process yet reads as pending and not as a mismatch.
291        self.publish_status();
292        tracing::info!(
293            block_id = %self.block_id,
294            "runtime-config change arrived mid-turn — deferring the restart to the end of this turn \
295             instead of killing the in-flight message"
296        );
297        true
298    }
299}
300
301/// The MCP self-heal's steps for this pane (`backend::mcp_health` decides
302/// them; docs/specs/SPEC_AGENT_MCP_SELF_HEAL_2026_10_10.md).
303impl PersistentSubprocessController {
304    /// A frame from process `generation`: the `agentmux` MCP server's status
305    /// (`system/init`, our `mcp_status`) or a reconnect's outcome. Anything
306    /// else, or a frame from a replaced process, is ignored.
307    pub(super) fn observe_mcp_frame(&self, frame: &serde_json::Value, generation: u64) {
308        use crate::backend::mcp_health as heal;
309        if self.inner.lock().unwrap().spawn_generation != generation {
310            return;
311        }
312        let process = self.mcp_process_key(generation);
313        let now = agentmux_common::time::now_ms_u64();
314        let report = heal::status_from_init(frame)
315            .map(|status| (status, None))
316            .or_else(|| heal::status_from_control_response(frame));
317        // A process that connects clears what an earlier one left (`mcp_health_meta`): a fresh process
318        // has nothing to repair, so it raises no notice to do it.
319        if let (Some((heal::Status::Connected, _)), Some(mstore)) = (&report, &self.mstore) {
320            crate::backend::mcp_health_meta::clear(&self.block_id, mstore, &self.event_bus);
321        }
322        let decision = if let Some((status, error)) = report {
323            heal::on_status(&self.block_id, &process, status, error, heal::auto_enabled(), now)
324        } else if let Some(result) = heal::reconnect_result(frame) {
325            heal::on_reconnect(&self.block_id, &process, result, now)
326        } else {
327            return;
328        };
329        self.carry_out_mcp_step(decision, generation);
330    }
331
332    /// A heartbeat from this pane's MCP process (`POST /api/v1/agent/self/mcp-beat`):
333    /// it says whether the server is wedged, which is repaired like one that
334    /// didn't connect (#2614).
335    pub fn mcp_beat(&self, beat: &crate::backend::mcp_health::Beat) {
336        use crate::backend::mcp_health as heal;
337        let generation = self.inner.lock().unwrap().spawn_generation;
338        let now = agentmux_common::time::now_ms_u64();
339        let Some((wedge, decision)) =
340            heal::on_beat(&self.block_id, &self.mcp_process_key(generation), beat, now)
341        else {
342            return;
343        };
344        self.repair_wedged_mcp(&wedge, decision, generation);
345    }
346
347    /// The watcher found `process`'s MCP server silent. Nothing if that
348    /// process is no longer this pane's.
349    pub fn mcp_wedged(&self, process: &str, wedge: &crate::backend::mcp_health::Wedge) {
350        use crate::backend::mcp_health as heal;
351        let (generation, running) = {
352            let inner = self.inner.lock().unwrap();
353            (
354                inner.spawn_generation,
355                inner.stdin_tx.is_some() && !inner.stop_pending,
356            )
357        };
358        if !running || self.mcp_process_key(generation) != process {
359            heal::forget_beats(&self.block_id);
360            return;
361        }
362        let decision = heal::on_wedged(
363            &self.block_id,
364            process,
365            wedge,
366            agentmux_common::time::now_ms_u64(),
367        );
368        self.repair_wedged_mcp(wedge, decision, generation);
369    }
370
371    fn repair_wedged_mcp(
372        &self,
373        wedge: &crate::backend::mcp_health::Wedge,
374        decision: crate::backend::mcp_health::Decision,
375        generation: u64,
376    ) {
377        use crate::backend::mcp_health::{self as heal, Action};
378        if matches!(decision.action, Action::None) {
379            return;
380        }
381        tracing::warn!(block_id = %self.block_id, why = %wedge.describe(), "MCP self-heal: the agentmux MCP server is wedged");
382        if !heal::auto_enabled() {
383            return;
384        }
385        self.carry_out_mcp_step(decision, generation);
386    }
387
388    /// `agentmux-mcp doctor --heal`: start the repair over now. `Err` says why
389    /// nothing started (`mcp_health::heal_now`).
390    pub fn mcp_heal_now(&self) -> Result<(), &'static str> {
391        let generation = self.inner.lock().unwrap().spawn_generation;
392        let now = agentmux_common::time::now_ms_u64();
393        let decision = crate::backend::mcp_health::heal_now(&self.block_id, &self.mcp_process_key(generation), now)?;
394        self.carry_out_mcp_step(decision, generation);
395        Ok(())
396    }
397
398    /// One CLI process of this controller: a replacement controller restarts
399    /// its generations, so the generation alone could name an older process.
400    fn mcp_process_key(&self, generation: u64) -> String {
401        format!("{:p}-{generation}", Arc::as_ptr(&self.inner))
402    }
403
404    fn carry_out_mcp_step(&self, decision: crate::backend::mcp_health::Decision, generation: u64) {
405        use crate::backend::mcp_health::{self as heal, Action};
406        if let Some(notice) = &decision.notice {
407            self.show_mcp_notice(notice);
408        }
409        match decision.action {
410            Action::None => {}
411            Action::Reconnect { after } => self.send_mcp_request(heal::reconnect_request_line(), after, generation),
412            Action::CheckStatus { after } => self.send_mcp_request(heal::status_request_line(), after, generation),
413            Action::Rewrite { shape } => self.rewrite_mcp_entry(shape, generation),
414            Action::SafeProfileRestart => self.restart_now_or_after_turn(),
415            Action::GiveUp => self.tell_agent_mcp_is_down(),
416        }
417    }
418
419    /// Rungs 3 and 4: rewrite the `agentmux` entry of the pane's `.mcp.json` (a quick read and write
420    /// under the launch's lock), then take the step that follows: a reconnect to pick it up, or the next rung.
421    fn rewrite_mcp_entry(&self, shape: crate::backend::mcp_health::Shape, generation: u64) {
422        use crate::backend::mcp_rewrite;
423        let work_dir = mcp_rewrite::workdir_of(&self.block_id).unwrap_or_default();
424        let result = match &self.mstore {
425            Some(mstore) => mcp_rewrite::run(mstore, &self.block_id, &work_dir, shape),
426            None => Err("no store".to_string()),
427        };
428        match &result {
429            Ok(changed) => tracing::info!(block_id = %self.block_id, ?shape, changed, "MCP self-heal: rewrote the agentmux entry of .mcp.json"),
430            Err(e) => tracing::warn!(block_id = %self.block_id, ?shape, "MCP self-heal: could not rewrite the agentmux entry of .mcp.json: {e}"),
431        }
432        let now = agentmux_common::time::now_ms_u64();
433        let decision = crate::backend::mcp_health::on_rewrite(&self.block_id, &self.mcp_process_key(generation), result, now);
434        self.carry_out_mcp_step(decision, generation);
435    }
436
437    /// Write a control request to process `generation`, after `after`; not if
438    /// it has been replaced by then.
439    fn send_mcp_request(&self, line: String, after: std::time::Duration, generation: u64) {
440        let inner = Arc::clone(&self.inner);
441        let send = move || {
442            if inner.lock().unwrap().spawn_generation == generation {
443                Self::push_stdin(&inner, line);
444            }
445        };
446        if after.is_zero() {
447            send();
448        } else if let Ok(rt) = tokio::runtime::Handle::try_current() {
449            rt.spawn(async move {
450                tokio::time::sleep(after).await;
451                send();
452            });
453        }
454    }
455
456    /// Restart the CLI (the same session) with the config now in force, which
457    /// for a pane in the safe profile means without the shell prefix: at once
458    /// when idle, else when the turn ends, through the deferred runtime-config
459    /// restart (`turn_boundary_locked`, `respawn_after_config_restart`). The
460    /// turn check and the flag share one acquisition, as in
461    /// [`Self::request_restart_when_idle`].
462    fn restart_now_or_after_turn(&self) {
463        let mut inner = self.inner.lock().unwrap();
464        if inner.stdin_tx.is_none() || inner.stop_pending {
465            return;
466        }
467        if self.health_monitor.is_active_turn() {
468            inner.restart_when_idle = true;
469            drop(inner);
470            self.publish_status();
471            return;
472        }
473        inner.restart_pending = true;
474        inner.config_restart_generation = Some(inner.spawn_generation);
475        drop(inner);
476        tracing::info!(block_id = %self.block_id, "MCP self-heal: restarting the agent in the safe profile");
477        self.stop_for_config_restart();
478    }
479
480    fn show_mcp_notice(&self, notice: &crate::backend::mcp_health::Notice) {
481        tracing::info!(block_id = %self.block_id, state = notice.state, step = notice.step, error = ?notice.error, "MCP self-heal");
482        // The Swarm shows it on the agent's row without opening the pane.
483        if let Some(mstore) = &self.mstore {
484            crate::backend::mcp_health_meta::persist(&self.block_id, notice, mstore, &self.event_bus);
485        }
486        let (Some(broker), Some(filestore), Some(mstore)) = (&self.broker, &self.filestore, &self.mstore) else {
487            return;
488        };
489        let (broker, filestore, mstore) = (Arc::clone(broker), Arc::clone(filestore), Arc::clone(mstore));
490        let (block_id, frame) = (self.block_id.clone(), crate::backend::mcp_health::notice_frame(notice));
491        let append = move || crate::backend::cli_notice::append_to_pane(&broker, &filestore, &mstore, &block_id, &frame);
492        match tokio::runtime::Handle::try_current() {
493            Ok(rt) => drop(rt.spawn_blocking(append)),
494            Err(_) => append(),
495        }
496    }
497
498    /// The `[AgentMux]` note that AgentMux gave up, so the agent tells the
499    /// operator and knows its tools are gone: in its running turn, else with
500    /// its next one, never a turn of its own. Audited by UID when the pane
501    /// has one.
502    fn tell_agent_mcp_is_down(&self) {
503        let error = crate::backend::mcp_health::snapshot(&self.block_id).and_then(|s| s.last_error);
504        let text = crate::backend::mcp_health::give_up_note(error.as_deref());
505        let handler = crate::backend::reactive::get_global_handler();
506        let Some(target) = handler
507            .list_agents()
508            .into_iter()
509            .find(|r| r.block_id == self.block_id)
510            .map(|r| r.uid.unwrap_or(r.agent_id))
511        else {
512            tracing::info!(block_id = %self.block_id, "MCP self-heal: no registered agent to tell");
513            return;
514        };
515        let joined = self.note_into_turn_or_hold("mcp-down", &text);
516        handler.audit_system_note(&target, &self.block_id, &text, joined);
517    }
518}
519
520/// The pane of this process, other than `except`, whose CLI process holds agent `uid`'s
521/// single-live-instance lease: its block id.
522pub fn local_holder_of(uid: &str, except: &str) -> Option<String> {
523    super::super::get_all_controllers().into_iter().find_map(|(block_id, ctrl)| {
524        if block_id == except {
525            return None;
526        }
527        let other = ctrl.as_any().downcast_ref::<PersistentSubprocessController>()?;
528        let holds = other.inner.lock().unwrap().agent_lease.as_ref().is_some_and(|l| l.agent_uid() == uid);
529        holds.then_some(block_id)
530    })
531}
532
533impl PersistentSubprocessController {
534    /// The early admission check (spec I9) for this controller's agent:
535    /// refuses while another pane of this process or another instance holds it.
536    /// Runs before any shared write.
537    pub async fn check_admission(&self, uid: &str, agent: &str) -> Result<(), String> {
538        if let Some(refusal) = self.handed_over_refusal(uid, agent) {
539            tracing::warn!(agent, uid, "agent_admission.denied (early check): the agent was handed to another computer");
540            return Err(refusal);
541        }
542        // Another pane of this process: the lease store below skips a holder with this srv's boot id,
543        // so it never sees one, and the spawn env's shared writes would run for a doomed spawn.
544        if !uid.is_empty() {
545            if let Some(other) = self.agent_held_by_other_pane(uid) {
546                tracing::warn!(agent, uid, holder_block = %other, "agent_admission.denied (early check): the agent is open in another pane");
547                return Err(super::held_elsewhere_error(&other, false));
548            }
549        }
550        crate::backend::agent_admission::check_before_spawn(self.lease_store.clone(), uid, agent, &self.boot_id).await
551    }
552
553    /// The refusal to start agent `uid` while its shared definition record says it was handed to another computer. The
554    /// mark is read fresh from the record on every start, so an edit by another instance on this host takes effect at
555    /// once and a mark cleared by `bring_back` ends the refusal at once.
556    pub(super) fn handed_over_refusal(&self, uid: &str, agent: &str) -> Option<String> {
557        if uid.is_empty() {
558            return None;
559        }
560        crate::backend::agent_admission::handed_over_check(self.mstore.as_ref()?, uid, agent)
561    }
562
563    /// [`Self::handed_over_refusal`] for the agent a spawn is about to start, named by the spawn's own environment.
564    pub(super) fn refuse_if_handed_over(&self, config: &PersistentSpawnConfig) -> Result<(), String> {
565        let uid = config.env_vars.get("AGENTMUX_AGENT_UID").map(|u| u.trim()).filter(|u| !u.is_empty());
566        let agent = super::muxbus_agent_id_from_env(&config.env_vars).unwrap_or_default();
567        match uid.and_then(|uid| self.handed_over_refusal(uid, &agent)) {
568            Some(refusal) => Err(refusal),
569            None => Ok(()),
570        }
571    }
572
573    /// Hand this pane's agent over to another AgentMux instance that asked
574    /// for it (spec §4.6, `POST /agentmux/agent/release`): if this pane's CLI
575    /// process holds the agent's single-live-instance lease, stop it
576    /// gracefully — stdin EOF, so a turn in flight finishes, then kill at
577    /// the deadline — and let its exit release the lease. `false` when this
578    /// pane holds nothing (no process, or no lease).
579    pub fn release_to_other_instance(&self, deadline: std::time::Instant) -> bool {
580        let kill = {
581            let mut inner = self.inner.lock().unwrap();
582            if inner.agent_lease.is_none() {
583                return false;
584            }
585            // A deferred runtime-config restart must not respawn the agent this hands away.
586            inner.config_restart_generation = None;
587            inner.kill_tx.take()
588        };
589        tracing::info!(block_id = %self.block_id, "agent_admission.takeover: handing this agent to another instance");
590        match kill {
591            Some(tx) => tx.send(super::KillRequest::Graceful(deadline)).is_ok(),
592            None => false,
593        }
594    }
595}