Skip to main content

agentmux_srv_core/backend/reactive/
handler.rs

1// Copyright 2025-2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4
5use std::collections::HashMap;
6use std::sync::OnceLock;
7
8use super::sanitize::{format_injected_message, is_sensitive_message, sanitize_message, validate_agent_id, wrap_jekt_message_full};
9use super::types::*;
10use super::{now_unix_millis, AUDIT_LOG_MAX, RATE_LIMIT_MAX};
11
12pub(super) use super::rate_limiter::RateLimiter;
13
14#[path = "former_slug.rs"]
15pub mod former_slug;
16pub use former_slug::FormerSlugResolver;
17pub use former_slug::{former_slug_claim, refuse_former_slug_sender, renamed};
18
19// ---- Handler ----
20
21/// Core reactive messaging handler.
22///
23/// Manages agent registrations, rate limiting, message injection,
24/// and audit logging.
25pub struct Handler {
26    // ---- Identity M2 (SPEC_AGENT_IDENTITY_CARRIED_NOT_DERIVED_2026_09_23.md
27    // §4.4): identity is the key, names are typed bindings. ----
28    //
29    /// The key, when known: the agent's UID (`db_agents.id`) → its block.
30    /// One-to-one — a UID registering on a new block evicts its old one
31    /// (a respawn). Empty for blocks the server has no row for (quick-launch
32    /// panes, PTY shells), which are then reachable by name only.
33    uid_to_block: HashMap<String, String>,
34    block_to_uid: HashMap<String, String>,
35    /// Lowercased name → every block bound to it. A name may hold several
36    /// blocks for the first time: two agents whose names collide both stay
37    /// registered (today one silently evicts the other), and delivery to
38    /// that name is refused with the candidates instead of guessed (§5.2).
39    name_to_blocks: HashMap<String, Vec<String>>,
40    /// A block's own names, typed — see [`NameBindings`].
41    block_names: HashMap<String, NameBindings>,
42    /// Keyed by block id (was: by lowercased name). `agent_id` in the record
43    /// is the block's *display* binding.
44    agent_info: HashMap<String, AgentRegistration>,
45    input_sender: Option<InputSender>,
46    /// Controller-aware delivery for non-PTY agents (persistent stream-json / ACP).
47    /// When set, it is tried before the PTY keystroke path so messages reach (and
48    /// steer) agents that have no terminal. See `set_message_sender`.
49    pub(super) message_sender: Option<MessageSender>,
50    /// Queries a resolved delivery target's own live identity before
51    /// delivering, as a check independent of this handler's own
52    /// `uid_to_block` / `name_to_blocks` registry. See
53    /// `AgentIdentityConfirmer`'s doc comment and
54    /// `set_agent_identity_confirmer`.
55    agent_identity_confirmer: Option<AgentIdentityConfirmer>,
56    /// Same shape as `agent_identity_confirmer`, but backed by
57    /// `Controller::stable_agent_id()` (the frozen `AGENTMUX_AGENT_ID`)
58    /// instead of `Controller::agent_id()` (the live, renameable display
59    /// name). Checked as an alternative match in `inject_message_inner`'s
60    /// #2695 identity check — a jekt addressed to the stable name would
61    /// otherwise always fail once the display binding has moved on
62    /// post-rename. See `NameBindings::stable`.
63    stable_agent_identity_confirmer: Option<AgentIdentityConfirmer>,
64    /// Identity M2: backed by `Controller::stable_agent_uid()`. Consulted
65    /// ONLY when the target resolved by UID, and `None` is "unverifiable"
66    /// (delivery proceeds) — never combined with the two name confirmers
67    /// above. A registered-but-unspawned persistent agent has a live name
68    /// (`set_agent_id` is called without a spawn) but no UID yet; running a
69    /// UID target through the name check would reject it as a mismatch
70    /// before the start-on-delivery fall-through could run (spec §4.4.3,
71    /// revision 4.0's P0).
72    uid_identity_confirmer: Option<AgentIdentityConfirmer>,
73    /// Identity M2: is this block still alive (has a controller)? The
74    /// garbage collector that replaces name eviction (spec §4.4.4 Q9):
75    /// when a name resolves to several blocks, the dead ones are swept
76    /// before ambiguity is decided. `None` (tests) treats every block as
77    /// live.
78    block_liveness: Option<BlockLivenessProbe>,
79    /// Tries an unbound name as a display name's route or a former name (`former_slug.rs`).
80    alias_resolvers: former_slug::AliasResolvers,
81    pub(super) audit_log: Vec<AuditLogEntry>,
82    /// The UID of the delivery in flight
83    /// (`InjectionRequest::audit_source_uid`), copied onto every audit entry
84    /// it writes. Set and restored around one `inject_message_inner` call,
85    /// under this handler's mutex, so no other delivery can see it.
86    pub(super) delivery_source_uid: String,
87    /// The WAN verdict of the delivery in flight (W3-S audit), copied onto
88    /// its audit entries. Same set-and-restore discipline as
89    /// `delivery_source_uid`.
90    pub(super) delivery_wan: Option<super::types::WanAudit>,
91    /// The LAN-claimed UID of the delivery in flight (identity M4d-6), same
92    /// set-and-restore discipline.
93    pub(super) delivery_lan_claimed_uid: String,
94    /// Whether the delivery in flight started a turn or joined one (`started` / `joined`); the
95    /// next entry `log_audit` writes takes it.
96    pub(super) delivery_turn: Option<&'static str>,
97    /// The tier and trust label of the delivery in flight (`sanitize::delivery_how`); set and restored like `delivery_wan`.
98    pub(super) delivery_how: Option<(String, String)>,
99    rate_limiter: RateLimiter,
100    include_source_in_message: bool,
101}
102
103#[path = "name_bindings.rs"]
104pub mod name_bindings;
105#[path = "deliver_steps.rs"]
106pub mod deliver_steps;
107pub use name_bindings::NameBindings;
108
109/// What a by-name unregister did (identity M2, spec §4.4.4 Q7). A name held
110/// by several live blocks is refused, never silently no-op'd as success.
111#[derive(Debug, Clone)]
112pub enum UnregisterOutcome {
113    Removed {
114        block_id: String,
115        /// Every name the block was bound under, so the caller can tear
116        /// down name-keyed side state (file registry, cloud subscription)
117        /// for each of them, not just the display name.
118        names: Vec<String>,
119    },
120    NotFound,
121    Ambiguous(Vec<AgentRegistration>),
122}
123
124/// What a read-only name lookup found (identity M2) — see
125/// [`Handler::lookup_by_name`].
126#[derive(Debug, Clone)]
127pub enum LookupOutcome {
128    One(AgentRegistration),
129    Ambiguous(Vec<AgentRegistration>),
130    NotFound,
131}
132
133/// How `inject_message_inner` resolved its target (spec §4.4.3).
134pub(super) enum TargetResolution {
135    Uid(String),
136    Name(String),
137    /// A slug the agent `uid` was renamed from, which it answers to by UID.
138    FormerSlug { block: String, uid: String },
139    Ambiguous(Vec<AgentRegistration>),
140    NotFound,
141}
142
143/// Human-readable candidate list for an ambiguity refusal — the §5.2 shape:
144/// enough for a model to retry by UID and for a human to act on.
145fn describe_candidates(candidates: &[AgentRegistration]) -> String {
146    candidates
147        .iter()
148        .map(|c| {
149            format!(
150                "uid={} block={} name={}",
151                c.uid.as_deref().unwrap_or("none"),
152                c.block_id,
153                c.agent_id
154            )
155        })
156        .collect::<Vec<_>>()
157        .join("; ")
158}
159
160impl Handler {
161    /// Create a new handler without an input sender.
162    /// Call `set_input_sender` before injecting messages.
163    pub fn new() -> Self {
164        Self {
165            uid_to_block: HashMap::new(),
166            block_to_uid: HashMap::new(),
167            name_to_blocks: HashMap::new(),
168            block_names: HashMap::new(),
169            agent_info: HashMap::new(),
170            input_sender: None,
171            message_sender: None,
172            agent_identity_confirmer: None,
173            stable_agent_identity_confirmer: None,
174            uid_identity_confirmer: None,
175            block_liveness: None,
176            alias_resolvers: Default::default(),
177            audit_log: Vec::with_capacity(AUDIT_LOG_MAX),
178            delivery_source_uid: String::new(),
179            delivery_wan: None,
180            delivery_lan_claimed_uid: String::new(),
181            delivery_turn: None,
182            delivery_how: None,
183            rate_limiter: RateLimiter::new(RATE_LIMIT_MAX),
184            include_source_in_message: false,
185        }
186    }
187
188    /// Set the input sender function for message injection.
189    pub fn set_input_sender(&mut self, sender: InputSender) {
190        self.input_sender = Some(sender);
191    }
192
193    /// Set the controller-aware message sender. When present, `inject_message`
194    /// tries it first: persistent stream-json and ACP agents receive a structured
195    /// message on their live channel (mid-turn steering); PTY-based agents report
196    /// back so injection falls through to the keystroke path.
197    pub fn set_message_sender(&mut self, sender: MessageSender) {
198        self.message_sender = Some(sender);
199    }
200
201    /// Set the agent-identity confirmer used by `inject_message_inner` to
202    /// double-check a resolved delivery target against its own live,
203    /// spawn-time-captured identity before delivering. Optional — if never
204    /// set, delivery proceeds exactly as before this check existed (fail-open).
205    pub fn set_agent_identity_confirmer(&mut self, confirmer: AgentIdentityConfirmer) {
206        self.agent_identity_confirmer = Some(confirmer);
207    }
208
209    /// See `stable_agent_identity_confirmer`'s field doc comment.
210    pub fn set_stable_agent_identity_confirmer(&mut self, confirmer: AgentIdentityConfirmer) {
211        self.stable_agent_identity_confirmer = Some(confirmer);
212    }
213
214    /// See `uid_identity_confirmer`'s field doc comment (identity M2).
215    pub fn set_uid_identity_confirmer(&mut self, confirmer: AgentIdentityConfirmer) {
216        self.uid_identity_confirmer = Some(confirmer);
217    }
218
219    /// See `block_liveness`'s field doc comment (identity M2).
220    pub fn set_block_liveness(&mut self, probe: BlockLivenessProbe) {
221        self.block_liveness = Some(probe);
222    }
223
224    /// Set whether to include source agent prefix in injected messages.
225    #[allow(dead_code)]
226    pub fn set_include_source(&mut self, include: bool) {
227        self.include_source_in_message = include;
228    }
229
230    /// Register an agent with a block.
231    /// Name-only registration. Every production site now goes through
232    /// [`register_agent_full`] with its UID and counter site; this is the
233    /// test-facing form (and the shape the pre-M2 API had).
234    #[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
235    pub fn register_agent(
236        &mut self,
237        agent_id: &str,
238        block_id: &str,
239        tab_id: Option<&str>,
240    ) -> Result<(), String> {
241        self.register_agent_full(
242            agent_id,
243            block_id,
244            tab_id,
245            0,
246            None,
247            None,
248            "registration.no_uid.unspecified",
249        )
250    }
251
252    /// [`register_agent`], recording the registering persistent-controller
253    /// spawn's process-wide registration nonce
254    /// (`AgentRegistration::registration_nonce`) so its own exit-handler
255    /// can later compare-and-remove ([`unregister_block_if_nonce`])
256    /// instead of blindly wiping a fallback respawn's fresh registration
257    /// (issue #2363).
258    ///
259    /// `alias`, if given, becomes the block's *stable* name binding
260    /// ([`NameBindings::stable`]): kept when a later call replaces the
261    /// display binding, so a jekt addressed to `AGENTMUX_AGENT_ID` still
262    /// resolves after the display name has moved on post-rename.
263    #[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
264    pub fn register_agent_with_nonce(
265        &mut self,
266        agent_id: &str,
267        block_id: &str,
268        tab_id: Option<&str>,
269        registration_nonce: u64,
270        alias: Option<&str>,
271    ) -> Result<(), String> {
272        self.register_agent_full(
273            agent_id,
274            block_id,
275            tab_id,
276            registration_nonce,
277            alias,
278            None,
279            "registration.no_uid.unspecified",
280        )
281    }
282
283    /// The full registration (identity M2, spec §4.4.2): `display` is the
284    /// block's display binding, `stable` its stable binding (set or kept),
285    /// `uid` its identity when the caller knows it, and `no_uid_counter` the
286    /// §9.2 counter to bump when it does not.
287    ///
288    /// **Eviction is by identity, never by name:**
289    /// - `uid` already registered on another block → that block is evicted
290    ///   entirely (a respawn).
291    /// - a name already held by another block is left alone **unless**
292    ///   neither block has a UID — that case keeps today's name eviction
293    ///   exactly, and is counted.
294    /// - a block that has a UID keeps it when re-registered without one
295    ///   (sticky — a transient row miss on the presence path must not drop a
296    ///   live block out of `uid_to_block`); a block without one is upgraded
297    ///   in place when a later registration supplies one.
298    // Eight parameters because the three identity facets (display, stable,
299    // uid) plus the counter site are each optional independently; bundling
300    // them would move the same eight names into a struct literal at every
301    // call site without making any of them clearer.
302    #[allow(clippy::too_many_arguments)]
303    pub fn register_agent_full(
304        &mut self,
305        display: &str,
306        block_id: &str,
307        tab_id: Option<&str>,
308        registration_nonce: u64,
309        stable: Option<&str>,
310        uid: Option<&str>,
311        no_uid_counter: &'static str,
312    ) -> Result<(), String> {
313        // A display name that isn't a valid id ("Loap #3") binds by route name.
314        let display = &super::sanitize::registrable_id(display).ok_or_else(|| format!("invalid agent ID: {display}"))?;
315        let stable = stable.filter(|s| validate_agent_id(s));
316        let uid = uid
317            .map(str::trim)
318            .filter(|u| !u.is_empty() && validate_agent_id(u));
319
320        let mut evicted_block: Option<String> = None;
321        let mut evicted_agent: Option<String> = None;
322
323        // 1. Identity eviction: this UID on a different block is a respawn.
324        if let Some(uid) = uid {
325            if let Some(old) = self.uid_to_block.get(uid).cloned() {
326                if old != block_id {
327                    evicted_agent = self.block_names.get(&old).map(|n| n.display.clone());
328                    self.remove_block_bindings(&old);
329                    evicted_block = Some(old);
330                }
331            }
332        }
333
334        // 2. This block's effective UID: supplied, else whatever it already
335        //    had (sticky). A block that changes UID — rare: a reconfigured
336        //    pane, or a pane reused for a different agent whose spawn env
337        //    now carries the new row's id — drops its OLD `uid_to_block`
338        //    entry here, otherwise a delivery addressed to the old UID would
339        //    still resolve to this block and then fail the UID confirmer as
340        //    a spurious mismatch instead of a clean not-found (ReAgent P2 on
341        //    PR #3560).
342        let effective_uid: Option<String> = uid
343            .map(str::to_string)
344            .or_else(|| self.block_to_uid.get(block_id).cloned());
345        if let (Some(new_uid), Some(old_uid)) = (uid, self.block_to_uid.get(block_id).cloned()) {
346            if old_uid != new_uid {
347                tracing::info!(
348                    block_id = %block_id,
349                    old_uid = %old_uid,
350                    new_uid = %new_uid,
351                    "reactive: block re-registered under a different uid — dropping the old uid mapping (identity M2)"
352                );
353                if self
354                    .uid_to_block
355                    .get(&old_uid)
356                    .is_some_and(|b| b == block_id)
357                {
358                    self.uid_to_block.remove(&old_uid);
359                }
360            }
361        }
362        if effective_uid.is_none() {
363            crate::backend::agent_resolve::record_uid_fallback(no_uid_counter);
364        }
365
366        // 3. Name eviction — only when neither side has a UID (today's
367        //    semantics, counted). Two identified agents sharing a name both
368        //    stay; delivery to that name is then refused with candidates.
369        let prev = self.block_names.get(block_id).cloned();
370        let new_keys: Vec<String> = {
371            let mut k = vec![display.to_lowercase()];
372            if let Some(s) = stable {
373                let s = s.to_lowercase();
374                if !k.contains(&s) {
375                    k.push(s);
376                }
377            }
378            k
379        };
380        if effective_uid.is_none() {
381            for key in &new_keys {
382                let others: Vec<String> = self
383                    .name_to_blocks
384                    .get(key)
385                    .map(|v| v.iter().filter(|b| b.as_str() != block_id).cloned().collect())
386                    .unwrap_or_default();
387                for other in others {
388                    if self.block_to_uid.contains_key(&other) {
389                        continue;
390                    }
391                    if evicted_agent.is_none() {
392                        evicted_agent = self.block_names.get(&other).map(|n| n.display.clone());
393                    }
394                    self.remove_block_bindings(&other);
395                    if evicted_block.is_none() {
396                        evicted_block = Some(other);
397                    }
398                    crate::backend::agent_resolve::record_uid_fallback("registration.name_evicted_no_uid");
399                }
400            }
401        }
402
403        // 4. Replace the display binding; set or keep the stable one.
404        let stable_final: Option<String> = stable
405            .map(str::to_string)
406            .or_else(|| prev.as_ref().and_then(|p| p.stable.clone()));
407        if let Some(prev) = &prev {
408            for key in prev.keys() {
409                self.unbind_name(&key, block_id);
410            }
411            if prev.display.to_lowercase() != display.to_lowercase() && evicted_agent.is_none() {
412                evicted_agent = Some(prev.display.clone());
413            }
414        }
415        let bindings = NameBindings {
416            display: display.to_string(),
417            stable: stable_final,
418        };
419        for key in bindings.keys() {
420            self.bind_name(&key, block_id);
421        }
422        self.block_names.insert(block_id.to_string(), bindings);
423        if let Some(u) = &effective_uid {
424            self.uid_to_block.insert(u.clone(), block_id.to_string());
425            self.block_to_uid.insert(block_id.to_string(), u.clone());
426        }
427
428        let now = now_unix_millis();
429        self.agent_info.insert(
430            block_id.to_string(),
431            AgentRegistration {
432                agent_id: display.to_string(),
433                block_id: block_id.to_string(),
434                tab_id: tab_id.map(|s| s.to_string()),
435                registered_at: now,
436                last_seen: now,
437                registration_nonce,
438                uid: effective_uid,
439            },
440        );
441
442        self.log_audit_registration(
443            "register",
444            display,
445            block_id,
446            evicted_block.as_deref(),
447            evicted_agent.as_deref(),
448        );
449        super::registered(block_id);
450
451        Ok(())
452    }
453
454    fn bind_name(&mut self, key: &str, block_id: &str) {
455        let blocks = self.name_to_blocks.entry(key.to_string()).or_default();
456        if !blocks.iter().any(|b| b == block_id) {
457            blocks.push(block_id.to_string());
458        }
459    }
460
461    fn unbind_name(&mut self, key: &str, block_id: &str) {
462        if let Some(blocks) = self.name_to_blocks.get_mut(key) {
463            blocks.retain(|b| b != block_id);
464            if blocks.is_empty() {
465                self.name_to_blocks.remove(key);
466            }
467        }
468    }
469
470    /// Drop every trace of `block_id` — names, UID, record. No audit entry;
471    /// callers log with the context they have.
472    fn remove_block_bindings(&mut self, block_id: &str) {
473        if let Some(names) = self.block_names.remove(block_id) {
474            for key in names.keys() {
475                self.unbind_name(&key, block_id);
476            }
477        }
478        if let Some(uid) = self.block_to_uid.remove(block_id) {
479            if self.uid_to_block.get(&uid).is_some_and(|b| b == block_id) {
480                self.uid_to_block.remove(&uid);
481            }
482        }
483        self.agent_info.remove(block_id);
484    }
485
486    /// Blocks bound to `key` (lowercased name) that are still alive, per the
487    /// liveness probe. Read-only: does not sweep. `None` probe = all live.
488    fn live_blocks_for_key(&self, key: &str) -> Vec<String> {
489        let Some(blocks) = self.name_to_blocks.get(key) else {
490            return Vec::new();
491        };
492        match &self.block_liveness {
493            Some(probe) => blocks.iter().filter(|b| probe(b)).cloned().collect(),
494            None => blocks.clone(),
495        }
496    }
497
498    /// Does any live block hold `name` (case-insensitive, like the cloud
499    /// subscription's keys)? An exit's own nonce check can't answer this:
500    /// it reports `false` both when a newer spawn owns the registration and
501    /// when nobody holds it any more.
502    pub fn has_live_name(&self, name: &str) -> bool {
503        !self.live_blocks_for_key(&name.to_lowercase()).is_empty()
504    }
505
506    /// Is `block_id` alive per the liveness probe? `None` probe = live.
507    fn is_live(&self, block_id: &str) -> bool {
508        self.block_liveness
509            .as_ref()
510            .is_none_or(|probe| probe(block_id))
511    }
512
513    /// Drop a registration whose block has no controller (spec §4.4.4 Q9).
514    fn sweep_dead(&mut self, block_id: &str) {
515        let display_name = self
516            .block_names
517            .get(block_id)
518            .map(|n| n.display.clone())
519            .unwrap_or_default();
520        tracing::info!(
521            block_id = %block_id,
522            name = %display_name,
523            "reactive: sweeping dead registration while resolving a contested name (identity M2)"
524        );
525        self.remove_block_bindings(block_id);
526        self.log_audit_registration("swept", &display_name, block_id, None, None);
527        crate::backend::agent_resolve::record_uid_fallback("registry.swept_dead");
528    }
529
530    /// Read-only name resolution shared by [`get_agent`] and
531    /// [`lookup_by_name`]: `Ok(Some(block))` for a UID hit or a name held
532    /// by exactly one live block, `Ok(None)` for nothing, `Err(blocks)` for
533    /// a name several live blocks hold. Liveness is consulted **only when
534    /// the name is contested** (spec §4.4.4 Q9): an uncontested registration
535    /// is never second-guessed, so a block that is momentarily between
536    /// controllers (a `resync_controller` replace, or a frontend register
537    /// that beats the resync) is not answered as "not found" — which would
538    /// forward a purely local miss to other instances. A former slug answers
539    /// only when `former` (a delivery target, never a name that acts).
540    fn read_resolve(&self, target: &str, former: bool) -> Result<Option<String>, Vec<String>> {
541        if let Some(block) = self
542            .uid_to_block
543            .get(target)
544            .or_else(|| self.uid_to_block.get(&target.to_lowercase()))
545        {
546            return Ok(Some(block.clone()));
547        }
548        let key = target.to_lowercase();
549        let blocks = self.name_to_blocks.get(&key).cloned().unwrap_or_default();
550        match blocks.len() {
551            0 => Ok(former.then(|| self.delivery_alias_block(&key)).flatten().map(|(block, _)| block)),
552            1 => Ok(Some(blocks[0].clone())),
553            _ => {
554                let live: Vec<String> = blocks.into_iter().filter(|b| self.is_live(b)).collect();
555                match live.len() {
556                    0 => Ok(None),
557                    1 => Ok(Some(live[0].clone())),
558                    _ => Err(live),
559                }
560            }
561        }
562    }
563
564    /// Resolve a delivery target (spec §4.4.3): UID first, then a name held
565    /// by exactly one live block — sweeping dead candidates only when the
566    /// name is contested (§4.4.4 Q9) — refusing an ambiguous name with its
567    /// candidates rather than guessing. Counts what it did (§9.2).
568    pub(super) fn resolve_target(&mut self, target: &str) -> TargetResolution {
569        if let Some(block) = self
570            .uid_to_block
571            .get(target)
572            .or_else(|| self.uid_to_block.get(&target.to_lowercase()))
573        {
574            return TargetResolution::Uid(block.clone());
575        }
576        let key = target.to_lowercase();
577        let blocks = self.name_to_blocks.get(&key).cloned().unwrap_or_default();
578        if blocks.is_empty() {
579            return self.former_slug_target(&key, target);
580        }
581        let live: Vec<String> = if blocks.len() == 1 {
582            blocks
583        } else {
584            let mut live = Vec::with_capacity(blocks.len());
585            for block in blocks {
586                if self.is_live(&block) {
587                    live.push(block);
588                } else {
589                    self.sweep_dead(&block);
590                }
591            }
592            live
593        };
594        match live.len() {
595            0 => TargetResolution::NotFound,
596            1 => {
597                crate::backend::agent_resolve::record_uid_fallback("delivery.resolved_by_name");
598                TargetResolution::Name(live.into_iter().next().unwrap())
599            }
600            _ => {
601                crate::backend::agent_resolve::record_uid_fallback("delivery.ambiguous");
602                let candidates = live
603                    .iter()
604                    .filter_map(|b| self.agent_info.get(b).cloned())
605                    .collect();
606                TargetResolution::Ambiguous(candidates)
607            }
608        }
609    }
610
611    /// Name lookup that tells an ambiguous name apart from an unknown one
612    /// (identity M2) — for callers that must refuse with candidates rather
613    /// than fall through to cross-instance forwarding (`GetAgentTranscript`).
614    /// No former slugs (`lookup_delivery_target` adds them).
615    pub fn lookup_by_name(&self, name: &str) -> LookupOutcome {
616        self.lookup_resolved(name, false)
617    }
618
619    pub(super) fn lookup_resolved(&self, name: &str, former: bool) -> LookupOutcome {
620        match self.read_resolve(name, former) {
621            Ok(Some(block)) => match self.agent_info.get(&block) {
622                Some(reg) => LookupOutcome::One(reg.clone()),
623                None => LookupOutcome::NotFound,
624            },
625            Ok(None) => LookupOutcome::NotFound,
626            Err(blocks) => {
627                crate::backend::agent_resolve::record_uid_fallback("lookup.ambiguous_name");
628                LookupOutcome::Ambiguous(
629                    blocks
630                        .iter()
631                        .filter_map(|b| self.agent_info.get(b).cloned())
632                        .collect(),
633                )
634            }
635        }
636    }
637
638    /// Unregister by name (identity M2, spec §4.4.4 Q7). One live block →
639    /// removed. Several → nothing is removed and the candidates are
640    /// returned; the caller must not report success. None → `NotFound`.
641    pub fn unregister_agent(&mut self, agent_id: &str) -> UnregisterOutcome {
642        let key = super::sanitize::route_name(agent_id).unwrap_or_default().to_lowercase();
643        let live = self.live_blocks_for_key(&key);
644        match live.len() {
645            0 => UnregisterOutcome::NotFound,
646            1 => {
647                let block_id = live[0].clone();
648                let names = self.unregister_block(&block_id);
649                UnregisterOutcome::Removed { block_id, names }
650            }
651            _ => {
652                crate::backend::agent_resolve::record_uid_fallback(
653                    "unregister.ambiguous_without_block",
654                );
655                let candidates = live
656                    .iter()
657                    .filter_map(|b| self.agent_info.get(b).cloned())
658                    .collect::<Vec<_>>();
659                tracing::warn!(
660                    name = %agent_id,
661                    candidates = %describe_candidates(&candidates),
662                    "reactive: refusing to unregister an ambiguous name without a block id"
663                );
664                UnregisterOutcome::Ambiguous(candidates)
665            }
666        }
667    }
668
669    /// Unregister by block ID. Returns every name the block was bound under
670    /// (empty if it was not registered) so name-keyed side state can be
671    /// torn down for each.
672    pub fn unregister_block(&mut self, block_id: &str) -> Vec<String> {
673        let Some(names) = self.block_names.get(block_id).cloned() else {
674            return Vec::new();
675        };
676        let display = names.display.clone();
677        self.remove_block_bindings(block_id);
678        self.log_audit_registration("unregister", &display, block_id, None, None);
679        let mut out = vec![display];
680        if let Some(s) = names.stable {
681            if !out.iter().any(|n| n.eq_ignore_ascii_case(&s)) {
682                out.push(s);
683            }
684        }
685        out
686    }
687
688    /// Unregister by block ID **only if** the current registration was
689    /// written by the spawn with `expected_nonce` — a
690    /// compare-and-remove for persistent-controller exit-handlers (issue
691    /// #2363: the handler's `is_current_generation` gate is read once,
692    /// while a fallback respawn re-registers on a parallel task; an
693    /// unconditional [`unregister_block`] here could wipe the NEW spawn's
694    /// registration, leaving the live agent invisible to Tier-1 delivery
695    /// with nothing left to re-register it). The nonce is process-wide
696    /// unique, so the guard also holds across controller replacement
697    /// (`resync_controller` — codex P1 on PR #2500), where a
698    /// controller-local generation would restart at 1 and collide. Runs
699    /// atomically under the handler's own lock (via the outer wrapper).
700    /// A registration with no recorded nonce (0 — HTTP/PTY paths) is
701    /// never removed by this variant: leaving a stale entry to the TTL
702    /// sweep is strictly safer than deleting a live one.
703    ///
704    /// Returns true if the registration was ours and was removed.
705    pub fn unregister_block_if_nonce(&mut self, block_id: &str, expected_nonce: u64) -> bool {
706        let Some(info) = self.agent_info.get(block_id) else {
707            return false;
708        };
709        let matches = expected_nonce != 0 && info.registration_nonce == expected_nonce;
710        if !matches {
711            tracing::info!(
712                block_id = %block_id,
713                expected_nonce = expected_nonce,
714                "reactive: registration changed hands since this spawn registered — skipping unregister"
715            );
716            return false;
717        }
718        self.unregister_block(block_id);
719        true
720    }
721
722    /// Update the last_seen timestamp for an agent.
723    #[allow(dead_code)]
724    pub fn update_last_seen(&mut self, agent_id: &str) {
725        let now = now_unix_millis();
726        for block in self.live_blocks_for_key(&agent_id.to_lowercase()) {
727            if let Some(info) = self.agent_info.get_mut(&block) {
728                info.last_seen = now;
729            }
730        }
731    }
732
733    /// Get agent registration by agent ID — a UID, or a name held by
734    /// exactly one live block. A name held by several is `None`, counted
735    /// (`lookup.ambiguous_name`): callers that authorize on it fail closed,
736    /// and callers that display on it show nothing rather than the wrong one.
737    /// Never a former slug's agent: callers authenticate and act on this.
738    pub fn get_agent(&self, agent_id: &str) -> Option<&AgentRegistration> {
739        match self.read_resolve(agent_id, false) {
740            Ok(Some(block)) => self.agent_info.get(&block),
741            Ok(None) => None,
742            Err(_) => {
743                crate::backend::agent_resolve::record_uid_fallback("lookup.ambiguous_name");
744                None
745            }
746        }
747    }
748
749    /// Whether `uid` has a live registration — a lookup with no side effect
750    /// (no counter, no rate-limit token, no audit entry), for the held-jekt
751    /// replay's presence check.
752    pub fn has_uid_registration(&self, uid: &str) -> bool {
753        self.uid_to_block.contains_key(uid)
754    }
755
756    /// The block `uid` is registered on, with no side effect — for the
757    /// held-jekt replay's quiet sign-in check.
758    pub fn block_for_uid(&self, uid: &str) -> Option<String> {
759        self.uid_to_block.get(uid).cloned()
760    }
761
762    /// Deliver a held jekt (durable jekt spec §2.3): the ordinary delivery
763    /// path, audited as `held_delivered` (or `held_retry` on failure).
764    pub fn inject_held(&mut self, req: InjectionRequest) -> InjectionResponse {
765        self.inject_message_inner(req, Some("held_delivered"), Some("held_retry"))
766    }
767
768    /// Get agent registration by block ID.
769    #[allow(dead_code)]
770    pub fn get_agent_by_block(&self, block_id: &str) -> Option<&AgentRegistration> {
771        self.agent_info.get(block_id)
772    }
773
774    /// Every name `block_id` is bound under (display first, then stable).
775    /// Production teardown gets the same list back from [`unregister_block`];
776    /// this read-only form is what registration subscribes for cloud delivery.
777    pub fn names_for_block(&self, block_id: &str) -> Vec<String> {
778        let Some(names) = self.block_names.get(block_id) else {
779            return Vec::new();
780        };
781        let mut out = vec![names.display.clone()];
782        if let Some(s) = &names.stable {
783            if !out.iter().any(|n| n.eq_ignore_ascii_case(s)) {
784                out.push(s.clone());
785            }
786        }
787        out
788    }
789
790    /// List all registered agents.
791    pub fn list_agents(&self) -> Vec<AgentRegistration> {
792        self.agent_info.values().cloned().collect()
793    }
794
795    /// Inject a message into an agent's terminal.
796    ///
797    /// Sends `message\r` as a single payload (required for text display),
798    /// then spawns 3 delayed `\r` sends at 200ms intervals as separate
799    /// PTY writes to ensure submission. See `docs/specs/jekt-inject-timing.md`.
800    pub fn inject_message(&mut self, req: InjectionRequest) -> InjectionResponse {
801        self.inject_message_inner(req, None, None)
802    }
803
804    /// Shared delivery path behind `inject_message` (ordinary jekt, no
805    /// outcome) and `inject_held` (`held_delivered` / `held_retry`). Two
806    /// separate outcome params (rather than one applied uniformly) so a
807    /// failed delivery is audited distinctly from a successful one.
808    fn inject_message_inner(
809        &mut self,
810        mut req: InjectionRequest,
811        outcome_on_success: Option<&str>,
812        outcome_on_failure: Option<&str>,
813    ) -> InjectionResponse {
814        let uid = std::mem::take(&mut req.audit_source_uid);
815        let outer = std::mem::replace(&mut self.delivery_source_uid, uid);
816        let outer_wan = std::mem::replace(&mut self.delivery_wan, super::types::WanAudit::from_request(&req));
817        let outer_lan = std::mem::replace(&mut self.delivery_lan_claimed_uid, std::mem::take(&mut req.lan_claimed_uid));
818        let outer_how = std::mem::replace(&mut self.delivery_how, Some(super::sanitize::delivery_how(&req)));
819        let resp = self.deliver_audited(req, outcome_on_success, outcome_on_failure);
820        // Restore, not clear: leave the fields as the caller had them.
821        self.delivery_source_uid = outer;
822        self.delivery_wan = outer_wan;
823        self.delivery_lan_claimed_uid = outer_lan;
824        self.delivery_how = outer_how;
825        resp
826    }
827
828    /// The body of [`Self::inject_message_inner`], with the sender's UID in
829    /// `delivery_source_uid` for every audit entry it writes.
830    fn deliver_audited(
831        &mut self,
832        mut req: InjectionRequest,
833        outcome_on_success: Option<&str>,
834        outcome_on_failure: Option<&str>,
835    ) -> InjectionResponse {
836        let now = now_unix_millis();
837
838        let request_id = self.prepare_request(&mut req);
839
840        // Rate limit check
841        if !self.rate_limiter.check() {
842            return deliver_steps::early_refusal(request_id, None, "rate limit exceeded".to_string(), now);
843        }
844
845        // Validate agent ID; a display name as the target means its route name.
846        req.target_agent = super::sanitize::route_name(&req.target_agent).unwrap_or_default();
847        if !validate_agent_id(&req.target_agent) {
848            let err = format!("invalid agent ID: {}", req.target_agent);
849            return deliver_steps::early_refusal(request_id, None, err, now);
850        }
851
852        // Sanitize message
853        let sanitized = sanitize_message(&req.message);
854
855        let (block_id, resolved_uid) =
856            match self.resolve_delivery_target(&req, &sanitized, &request_id, now, outcome_on_failure) {
857                Ok(target) => target,
858                Err(refusal) => return refusal,
859            };
860        if let Err(refusal) =
861            self.confirm_uid_identity(&req, &sanitized, &request_id, now, &block_id, resolved_uid.as_deref())
862        {
863            return refusal;
864        }
865        if let Err(refusal) =
866            self.confirm_name_identity(&req, &sanitized, &request_id, now, &block_id, resolved_uid.is_some())
867        {
868            return refusal;
869        }
870
871        let deliver_steps::TierDecision { effective_tier, requires_stop } = deliver_steps::decide_tier(&req, &sanitized);
872        let delivery_tier = req.delivery_tier.as_deref().unwrap_or("host");
873        let priority = req.priority.as_deref().unwrap_or("normal");
874
875        // Wrap in JEKT marker block (structured tag + human-readable header).
876        // Note: `req.sig_verified` (three-state) is passed through as-is for
877        // the marker's TRUST label — `is_unverified_sender` above only
878        // captures the `Some(false)` case (the one that forces SENSITIVE);
879        // the marker itself also needs to distinguish `None` ("never
880        // checked," e.g. a Slack-bridge message) from `Some(true)`
881        // ("actually verified") rather than collapsing both to the same
882        // label — see `wrap_jekt_message`'s doc comment.
883        let wrapped = wrap_jekt_message_full(
884            &super::sanitize::with_wan_pin_note(&sanitized, delivery_tier, &req),
885            req.source_agent.as_deref(),
886            req.marker_target.as_deref().unwrap_or(&req.target_agent),
887            effective_tier,
888            delivery_tier,
889            req.sig_verified,
890            req.reagent_verified,
891            req.reagent_expired,
892            req.lan_verified,
893            req.channel_verified,
894            req.wan_instance.as_ref().filter(|_| req.wan_verified == Some(true)),
895            req.wan_verified == Some(false),
896            requires_stop,
897            &request_id,
898            priority,
899            req.held_sent_at_ms,
900            req.files_delivery.as_ref(),
901            req.reply.as_deref() == Some("none"),
902            req.scheduler_fire.as_ref(),
903        );
904
905        // Legacy source-prefix format preserved for PTY controllers that don't
906        // parse the JEKT block — the wrap_jekt_message output already includes
907        // the source in the human-readable header so format_injected_message
908        // is called with include_source=false here.
909        let final_msg = format_injected_message(&wrapped, req.source_agent.as_deref(), false);
910
911        let delivery = deliver_steps::Delivery {
912            req: &req,
913            sanitized: &sanitized,
914            request_id,
915            now,
916            block_id,
917            effective_tier,
918            requires_stop,
919            delivery_tier,
920            outcome_on_success,
921            outcome_on_failure,
922        };
923        let response = self.deliver_structured(&delivery, &final_msg).unwrap_or_else(|| self.deliver_to_pty(&delivery, &final_msg));
924        // The quiet watch's record of an urgent message that names a task, made once the delivery is decided (backend::urgent_asks).
925        crate::backend::urgent_asks::note_delivery(&req, &response);
926        response
927    }
928
929    /// Deliver one of srv's own `[AgentMux]` system notes to `target_agent`
930    /// now, which starts a turn if none is running; an informational note
931    /// waits for the next one instead (`held_notes`). Not a jekt: no marker
932    /// block, tier or trust label, because nothing but srv wrote the text,
933    /// and no jekt or forwarded text can carry the marker
934    /// (`sanitize::neutralize_markers`).
935    /// Routed like a jekt: the controller's structured channel, else
936    /// keystrokes. Audited as `system_note` from `agentmux`.
937    pub fn deliver_system_note(&mut self, target_agent: &str, text: &str) -> Result<(), String> {
938        let block_id = self.note_target(target_agent)?;
939        let result = self.send_to_block(&block_id, text);
940        let request_id = uuid::Uuid::new_v4().to_string();
941        self.log_audit(
942            Some("agentmux"),
943            target_agent,
944            &block_id,
945            text,
946            result.is_ok(),
947            result.as_ref().err().map(String::as_str),
948            &request_id,
949            Some("system_note"),
950            None,
951        );
952        result
953    }
954
955    /// `text` to `block_id` the way a jekt goes: structured when the
956    /// controller takes it, else typed and submitted.
957    fn send_to_block(&self, block_id: &str, text: &str) -> Result<(), String> {
958        if let Some(deliver) = &self.message_sender {
959            match deliver(block_id, text, &[], &crate::backend::message_origin::MessageOrigin::system(), None)? {
960                SenderDelivery::Delivered | SenderDelivery::Deferred => return Ok(()),
961                SenderDelivery::Pty => {}
962            }
963        }
964        let sender = self.input_sender.clone().ok_or_else(|| "input sender not configured".to_string())?;
965        let _ = sender(block_id, b"\r");
966        sender(block_id, format!("{text}\r").as_bytes())?;
967        if tokio::runtime::Handle::try_current().is_ok() {
968            let block_id = block_id.to_string();
969            tokio::spawn(async move {
970                for _ in 0..3 {
971                    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
972                    let _ = sender(&block_id, b"\r");
973                }
974            });
975        }
976        Ok(())
977    }
978
979    /// Get audit log entries, most recent first.
980    pub fn get_audit_log(&self, limit: usize) -> Vec<AuditLogEntry> {
981        let start = if self.audit_log.len() > limit {
982            self.audit_log.len() - limit
983        } else {
984            0
985        };
986        let mut entries: Vec<_> = self.audit_log[start..].to_vec();
987        entries.reverse();
988        entries
989    }
990
991    /// Add an entry to the audit ring buffer. `outcome` labels a delivery
992    /// that isn't an ordinary jekt (`held_delivered`, `identity-mismatch`,
993    /// `system_note`, …); `reason` is a caller's free-text note
994    /// (`log_fleet_action_audit`). Both are `None` for an ordinary jekt.
995    #[allow(clippy::too_many_arguments)]
996    pub(super) fn log_audit(
997        &mut self,
998        source_agent: Option<&str>,
999        target_agent: &str,
1000        block_id: &str,
1001        message: &str,
1002        success: bool,
1003        error_message: Option<&str>,
1004        request_id: &str,
1005        outcome: Option<&str>,
1006        reason: Option<&str>,
1007    ) {
1008        self.log_audit_full(
1009            source_agent, target_agent, block_id, message, success, error_message, request_id, outcome, reason, None, None,
1010            None, None,
1011        );
1012    }
1013
1014    /// Record a registration/eviction event in the audit log — the
1015    /// counterpart to [`log_audit`] (which only ever recorded delivery
1016    /// attempts). `evicted_block`/`evicted_agent` capture whichever prior
1017    /// mapping a "register" call displaced, so a same-host identity
1018    /// collision (two panes racing to register the same agent_id) is
1019    /// reconstructable after the fact instead of leaving no trace.
1020    pub(super) fn log_audit_registration(
1021        &mut self,
1022        event_kind: &str,
1023        agent_id: &str,
1024        block_id: &str,
1025        evicted_block: Option<&str>,
1026        evicted_agent: Option<&str>,
1027    ) {
1028        let entry = AuditLogEntry {
1029            timestamp: now_unix_millis(),
1030            target_agent: agent_id.to_string(),
1031            block_id: block_id.to_string(),
1032            event_kind: event_kind.to_string(),
1033            evicted_block: evicted_block.map(|s| s.to_string()),
1034            evicted_agent: evicted_agent.map(|s| s.to_string()),
1035            ..Default::default()
1036        };
1037
1038        super::audit_store::push(&mut self.audit_log, AUDIT_LOG_MAX, entry);
1039    }
1040}
1041
1042impl Default for Handler {
1043    fn default() -> Self {
1044        Self::new()
1045    }
1046}
1047
1048// ---- Thread-safe wrapper ----
1049
1050/// Thread-safe wrapper around Handler.
1051pub struct ReactiveHandler {
1052    /// Recovers from a poisoning panic instead of passing it on: `handler_lock.rs`.
1053    pub(super) inner: super::handler_lock::HandlerLock,
1054    /// Called with the target block_id after a successful delivery whose
1055    /// marker says `ESCALATE=required` — the notification Router turns it
1056    /// into a "needs your review" OS notification (fixed text, no content).
1057    /// A list, not a slot: this handler is process-global, and each Router
1058    /// (one per broker/AppState) registers its own hook and ignores blocks
1059    /// that aren't in its own store — so a second AppState can never steal
1060    /// another's notifications (ReAgent P1 on #3654).
1061    needs_review_hooks: std::sync::RwLock<Vec<NeedsReviewHook>>,
1062}
1063
1064/// See `ReactiveHandler::add_needs_review_hook`.
1065pub type NeedsReviewHook = std::sync::Arc<dyn Fn(&str) + Send + Sync>;
1066
1067impl ReactiveHandler {
1068    pub fn new() -> Self {
1069        Self {
1070            inner: super::handler_lock::HandlerLock::new(Handler::new()),
1071            needs_review_hooks: std::sync::RwLock::new(Vec::new()),
1072        }
1073    }
1074
1075    /// Register a needs-review hook. Must not block or call back into this
1076    /// handler; hooks run after the inner lock is released.
1077    pub fn add_needs_review_hook(&self, f: NeedsReviewHook) {
1078        self.needs_review_hooks.write().unwrap_or_else(|e| e.into_inner()).push(f);
1079    }
1080
1081    fn after_delivery(&self, resp: &InjectionResponse) {
1082        if !(resp.success && resp.requires_stop == Some(true)) {
1083            return;
1084        }
1085        let Some(block_id) = resp.block_id.as_deref() else { return };
1086        let hooks = self.needs_review_hooks.read().unwrap_or_else(|e| e.into_inner()).clone();
1087        for h in hooks {
1088            h(block_id);
1089        }
1090    }
1091
1092    pub fn set_input_sender(&self, sender: InputSender) {
1093        self.inner.lock().set_input_sender(sender);
1094    }
1095
1096    pub fn set_message_sender(&self, sender: MessageSender) {
1097        self.inner.lock().set_message_sender(sender);
1098    }
1099
1100    pub fn set_agent_identity_confirmer(&self, confirmer: AgentIdentityConfirmer) {
1101        self.inner
1102            .lock()
1103            .set_agent_identity_confirmer(confirmer);
1104    }
1105
1106    /// See the inner [`Handler::set_stable_agent_identity_confirmer`].
1107    pub fn set_stable_agent_identity_confirmer(&self, confirmer: AgentIdentityConfirmer) {
1108        self.inner
1109            .lock()
1110            .set_stable_agent_identity_confirmer(confirmer);
1111    }
1112
1113    /// See the inner [`Handler::set_uid_identity_confirmer`] (identity M2).
1114    pub fn set_uid_identity_confirmer(&self, confirmer: AgentIdentityConfirmer) {
1115        self.inner
1116            .lock()
1117            .set_uid_identity_confirmer(confirmer);
1118    }
1119
1120    /// See the inner [`Handler::set_block_liveness`] (identity M2).
1121    pub fn set_block_liveness(&self, probe: BlockLivenessProbe) {
1122        self.inner.lock().set_block_liveness(probe);
1123    }
1124
1125    /// See the inner [`Handler::register_agent_full`] (identity M2).
1126    #[allow(clippy::too_many_arguments)]
1127    pub fn register_agent_full(
1128        &self,
1129        display: &str,
1130        block_id: &str,
1131        tab_id: Option<&str>,
1132        registration_nonce: u64,
1133        stable: Option<&str>,
1134        uid: Option<&str>,
1135        no_uid_counter: &'static str,
1136    ) -> Result<(), String> {
1137        self.inner.lock().register_agent_full(
1138            display,
1139            block_id,
1140            tab_id,
1141            registration_nonce,
1142            stable,
1143            uid,
1144            no_uid_counter,
1145        )
1146    }
1147
1148    /// [`try_register_agent_with_nonce`]'s full-identity form — same
1149    /// non-blocking, bounded-retry lock discipline, for the spawn path.
1150    #[allow(clippy::too_many_arguments)]
1151    pub fn try_register_agent_full(
1152        &self,
1153        display: &str,
1154        block_id: &str,
1155        tab_id: Option<&str>,
1156        registration_nonce: u64,
1157        stable: Option<&str>,
1158        uid: Option<&str>,
1159        no_uid_counter: &'static str,
1160    ) -> Result<(), String> {
1161        let mut guard = self.try_lock_bounded()?;
1162        guard.register_agent_full(
1163            display,
1164            block_id,
1165            tab_id,
1166            registration_nonce,
1167            stable,
1168            uid,
1169            no_uid_counter,
1170        )
1171    }
1172
1173    /// Every name `block_id` is bound under — see [`Handler::names_for_block`].
1174    pub fn names_for_block(&self, block_id: &str) -> Vec<String> {
1175        self.inner.lock().names_for_block(block_id)
1176    }
1177
1178    /// Bounded `try_lock`, shared by the spawn-path entry points — see
1179    /// [`try_register_agent_with_nonce`]'s doc comment for the reasoning.
1180    fn try_lock_bounded(&self) -> Result<std::sync::MutexGuard<'_, Handler>, String> {
1181        const MAX_ATTEMPTS: u32 = 5;
1182        const RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(2);
1183        for attempt in 1..=MAX_ATTEMPTS {
1184            match self.inner.try_lock() {
1185                Some(guard) => return Ok(guard),
1186                None => {
1187                    if attempt == MAX_ATTEMPTS {
1188                        return Err(
1189                            "reactive handler lock busy after retrying — skipping \
1190                             registration (either a same-thread reentrant call, \
1191                             redundant by construction on that path, or contention \
1192                             that outlasted the retry budget; see \
1193                             INCIDENT_2026_09_07_BACKEND_UPTIME_TIMER_FROZEN.md)"
1194                                .to_string(),
1195                        );
1196                    }
1197                    std::thread::sleep(RETRY_DELAY);
1198                }
1199            }
1200        }
1201        unreachable!("loop always returns on its final attempt");
1202    }
1203
1204    #[allow(dead_code)]
1205    pub fn set_include_source(&self, include: bool) {
1206        self.inner.lock().set_include_source(include);
1207    }
1208
1209    /// Test-facing name-only form — see [`Handler::register_agent`].
1210    #[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
1211    pub fn register_agent(
1212        &self,
1213        agent_id: &str,
1214        block_id: &str,
1215        tab_id: Option<&str>,
1216    ) -> Result<(), String> {
1217        self.inner
1218            .lock()
1219            .register_agent(agent_id, block_id, tab_id)
1220    }
1221
1222    /// See the inner [`Handler::register_agent_with_nonce`].
1223    #[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
1224    pub fn register_agent_with_nonce(
1225        &self,
1226        agent_id: &str,
1227        block_id: &str,
1228        tab_id: Option<&str>,
1229        registration_nonce: u64,
1230        alias: Option<&str>,
1231    ) -> Result<(), String> {
1232        self.inner
1233            .lock()
1234            .register_agent_with_nonce(agent_id, block_id, tab_id, registration_nonce, alias)
1235    }
1236
1237    /// Like [`register_agent_with_nonce`], but never blocks indefinitely: if
1238    /// the lock is still held after a short bounded retry
1239    /// (`try_lock_bounded`), this returns an error instead of
1240    /// waiting for it. Test-only; the spawn path uses the full-identity
1241    /// form, [`Self::try_register_agent_full`], which shares this
1242    /// reasoning.
1243    ///
1244    /// The case that matters is this exact call running on the same OS
1245    /// thread as an in-flight `inject_message` — the reactive-delivery spawn
1246    /// fallback (`bootstrap/delivery.rs`'s `install_agent_turn_delivery`) runs a
1247    /// respawn synchronously on the injecting thread via `block_in_place`,
1248    /// and that respawn's own auto-registration
1249    /// (`PersistentSubprocessController::spawn_process`) used to re-lock this
1250    /// same non-reentrant `Mutex<Handler>` two modules away from the
1251    /// call site `TurnRegistration::Skip` actually guards — permanently
1252    /// deadlocking the reactive handler process-wide (every persistent
1253    /// agent's first message after an idle period, or after any srv
1254    /// restart). See `docs/incident/INCIDENT_2026_09_07_BACKEND_UPTIME_TIMER_FROZEN.md`.
1255    ///
1256    /// Skipping in that case loses nothing: `inject_message` only reaches
1257    /// the spawn fallback after resolving `target_agent` through
1258    /// `resolve_target` (the `uid_to_block` / `name_to_blocks` registry),
1259    /// so this exact agent/block pair is registered BY
1260    /// CONSTRUCTION before this call is ever reached on that path — the
1261    /// same "redundant, not just deadlock-prone" reasoning documented on
1262    /// `TurnRegistration::Skip` for the sibling re-lock it guards.
1263    ///
1264    /// Genuine cross-thread contention is a real, separate risk this
1265    /// method does not get to treat as harmless: `respawn_once_for_
1266    /// leftover_queue` and other internal callers reach `spawn_process`
1267    /// directly, with no `run_agent_turn` `Register`-tail behind them to
1268    /// repair a skip — a losing race there can leave a live respawned
1269    /// agent unregistered and unreachable until a human intervenes via
1270    /// the UI (#3084). The retry loop in `try_lock_bounded`
1271    /// exists for exactly that case: a same-thread reentrant call can
1272    /// never succeed no matter how many times it retries (nothing on
1273    /// that call stack can release the lock), but ordinary cross-thread
1274    /// contention — a few HashMap reads under the same lock elsewhere,
1275    /// typically microseconds — very likely clears within the retry
1276    /// budget. See the comment in this method's body for the full reasoning.
1277    ///
1278    /// A skip's caller (`spawn_process`) is also responsible for not
1279    /// trusting `registration_nonce` as this spawn's exit-time cleanup
1280    /// key when the call returns `Err` here — the registration this
1281    /// skip left in place (if any) still belongs to whichever nonce is
1282    /// actually on record, not to this spawn's own unwritten one. See
1283    /// `spawn_process`'s handling of `try_register_agent_full`'s `Err` arm.
1284    #[cfg_attr(not(any(test, feature = "test-support")), allow(dead_code))]
1285    pub fn try_register_agent_with_nonce(
1286        &self,
1287        agent_id: &str,
1288        block_id: &str,
1289        tab_id: Option<&str>,
1290        registration_nonce: u64,
1291        alias: Option<&str>,
1292    ) -> Result<(), String> {
1293        // Bounded retry, not a single attempt (#3084): the spawn-path
1294        // registration (`PersistentSubprocessController::spawn_process`'s
1295        // auto-registration, via `try_register_agent_full`, which shares
1296        // `try_lock_bounded`) is shared by every caller that spawns a
1297        // process — including `respawn_once_for_leftover_queue`, which
1298        // calls `spawn_process` directly with no `run_agent_turn`
1299        // `Register`-tail to repair a skip. A single `try_lock` cannot
1300        // tell "the SAME thread already holds this lock" (the reentrant
1301        // deadlock this method exists to avoid — retrying never helps,
1302        // nothing on this call stack can release it) apart from "a
1303        // DIFFERENT thread holds it briefly for an unrelated op" (e.g.
1304        // `list_agents()` — a few HashMap reads, typically microseconds).
1305        // Retrying costs the reentrant case a few bounded, wasted
1306        // milliseconds and still correctly returns `Err`; it costs the
1307        // ordinary-contention case nothing in the near-universal case
1308        // where the next attempt lands after the brief holder is done —
1309        // "bounded stalling beats silent loss", the same tradeoff
1310        // `bootstrap/delivery.rs`'s `block_in_place` fallback already makes.
1311        let mut guard = self.try_lock_bounded()?;
1312        guard.register_agent_with_nonce(agent_id, block_id, tab_id, registration_nonce, alias)
1313    }
1314
1315    /// See the inner [`Handler::unregister_agent`] — by name, refusing an
1316    /// ambiguous one (identity M2).
1317    pub fn unregister_agent(&self, agent_id: &str) -> UnregisterOutcome {
1318        self.inner.lock().unregister_agent(agent_id)
1319    }
1320
1321    /// The live blocks `unregister_agent` would remove for `name`.
1322    pub fn blocks_named(&self, name: &str) -> Vec<String> {
1323        let key = super::sanitize::route_name(name).unwrap_or_default().to_lowercase();
1324        self.inner.lock().live_blocks_for_key(&key)
1325    }
1326
1327    /// See the inner [`Handler::unregister_block`]. Returns the names the
1328    /// block was bound under.
1329    pub fn unregister_block(&self, block_id: &str) -> Vec<String> {
1330        self.inner.lock().unregister_block(block_id)
1331    }
1332
1333    /// See the inner [`Handler::unregister_block_if_nonce`] — atomic
1334    /// compare-and-remove under the handler lock (issue #2363).
1335    pub fn unregister_block_if_nonce(&self, block_id: &str, expected_nonce: u64) -> bool {
1336        self.inner
1337            .lock()
1338            .unregister_block_if_nonce(block_id, expected_nonce)
1339    }
1340
1341    #[allow(dead_code)]
1342    pub fn update_last_seen(&self, agent_id: &str) {
1343        self.inner.lock().update_last_seen(agent_id);
1344    }
1345
1346    pub fn get_agent(&self, agent_id: &str) -> Option<AgentRegistration> {
1347        self.inner.lock().get_agent(agent_id).cloned()
1348    }
1349
1350    /// See the inner [`Handler::has_live_name`].
1351    pub fn has_live_name(&self, name: &str) -> bool {
1352        self.inner.lock().has_live_name(name)
1353    }
1354
1355    /// See the inner [`Handler::lookup_by_name`] (identity M2).
1356    pub fn lookup_by_name(&self, name: &str) -> LookupOutcome {
1357        self.inner.lock().lookup_by_name(name)
1358    }
1359
1360    /// Used by `server/app_api/fleet.rs`'s ordinary (non-reentrant) request
1361    /// handlers — no longer dead code, but NOT safe to call from
1362    /// `spawn_process`'s skip-arm; see [`try_get_agent_by_block`] for why.
1363    pub fn get_agent_by_block(&self, block_id: &str) -> Option<AgentRegistration> {
1364        self.inner
1365            .lock()
1366            .get_agent_by_block(block_id)
1367            .cloned()
1368    }
1369
1370    /// Non-blocking counterpart to [`get_agent_by_block`], for the one
1371    /// caller that can be running on a thread already holding this lock:
1372    /// `spawn_process`'s handling of a skipped registration
1373    /// (`try_register_agent_with_nonce` returning `Err`).
1374    ///
1375    /// reagent P0 on PR #3084 (caught twice — the fix for the P1 nonce-leak
1376    /// finding introduced this exact regression on its first attempt): that
1377    /// fix originally called the plain, blocking [`get_agent_by_block`]
1378    /// from inside the skip arm. In the routine reentrant case — the same
1379    /// thread already holds `self.inner` via an in-flight `inject_message`
1380    /// — that blocking `.lock()` reproduces INCIDENT_2026_09_07's exact
1381    /// permanent self-deadlock, on the very thread `try_register_agent_
1382    /// with_nonce`'s own retry-then-fail was designed to protect. Same
1383    /// bounded-retry reasoning as that method: a same-thread reentrant call
1384    /// can never succeed (nothing on this call stack releases the lock) and
1385    /// correctly returns `None` after exhausting the budget — the caller's
1386    /// nonce-leak mitigation simply doesn't apply in that sub-case, which is
1387    /// a strict improvement on the pre-this-PR baseline (no cleanup, but no
1388    /// deadlock either), not a regression. Ordinary cross-thread contention
1389    /// gets a real chance to succeed, same as the sibling method.
1390    pub fn try_get_agent_by_block(&self, block_id: &str) -> Option<AgentRegistration> {
1391        const MAX_ATTEMPTS: u32 = 5;
1392        const RETRY_DELAY: std::time::Duration = std::time::Duration::from_millis(2);
1393        for attempt in 1..=MAX_ATTEMPTS {
1394            match self.inner.try_lock() {
1395                Some(guard) => return guard.get_agent_by_block(block_id).cloned(),
1396                None => {
1397                    if attempt == MAX_ATTEMPTS {
1398                        return None;
1399                    }
1400                    std::thread::sleep(RETRY_DELAY);
1401                }
1402            }
1403        }
1404        unreachable!("loop always returns on its final attempt");
1405    }
1406
1407    pub fn list_agents(&self) -> Vec<AgentRegistration> {
1408        self.inner.lock().list_agents()
1409    }
1410
1411    pub fn inject_message(&self, req: InjectionRequest) -> InjectionResponse {
1412        let resp = self.inner.lock().inject_message(req);
1413        self.after_delivery(&resp);
1414        resp
1415    }
1416
1417    /// See [`Handler::deliver_system_note`].
1418    pub fn deliver_system_note(&self, target_agent: &str, text: &str) -> Result<(), String> {
1419        self.inner.lock().deliver_system_note(target_agent, &super::sanitize::with_system_note_marker(text))
1420    }
1421
1422    /// See [`Handler::inject_held`].
1423    pub fn inject_held(&self, req: InjectionRequest) -> InjectionResponse {
1424        let resp = self.inner.lock().inject_held(req);
1425        self.after_delivery(&resp);
1426        resp
1427    }
1428
1429    /// See [`Handler::has_uid_registration`].
1430    pub fn has_uid_registration(&self, uid: &str) -> bool {
1431        self.inner.lock().has_uid_registration(uid)
1432    }
1433
1434    /// See [`Handler::block_for_uid`].
1435    pub fn block_for_uid(&self, uid: &str) -> Option<String> {
1436        self.inner.lock().block_for_uid(uid)
1437    }
1438
1439    pub fn get_audit_log(&self, limit: usize) -> Vec<AuditLogEntry> {
1440        self.inner.lock().get_audit_log(limit)
1441    }
1442
1443    /// Records an action that isn't a jekt injection (fleet bulk-stop,
1444    /// pane-lifecycle close/etc., an AWS credential grant, a seat change, a rename: callers in
1445    /// `crates/srv/src/server/app_api/`) into the SAME audit ring buffer, as an action row
1446    /// (`action_audit.rs`): who did it, what (`action`, e.g. `"fleet.bulk-stop"`, `"pane.close"`),
1447    /// to what and how it went, with no byte count (`SPEC_MULTI_AGENT_FLEET_CONTROL_2026_08_20.md`
1448    /// §6); `target_agent` is the
1449    /// resolved agent name for `block_id` when known, else `block_id` itself
1450    /// (an unregistered/already-stopped block has no agent to name).
1451    ///
1452    /// `reason`: an optional caller-supplied free-text note (e.g.
1453    /// `ClosePane`'s `reason` field, SPEC_AGENT_PANE_LIFECYCLE_CONTROL_2026_09_10.md
1454    /// §5.2). `None` for every pre-existing caller (`FleetBulkStop` has no
1455    /// such field today) — purely additive, no behavior change for them.
1456    #[allow(clippy::too_many_arguments)]
1457    pub fn log_fleet_action_audit(
1458        &self,
1459        source_agent: Option<&str>,
1460        target_agent: &str,
1461        block_id: &str,
1462        action: &str,
1463        success: bool,
1464        error_message: Option<&str>,
1465        request_id: &str,
1466        reason: Option<&str>,
1467    ) {
1468        self.audit_fleet_action(source_agent, target_agent, block_id, action, success, error_message, request_id, reason);
1469    }
1470}
1471
1472impl Default for ReactiveHandler {
1473    fn default() -> Self {
1474        Self::new()
1475    }
1476}
1477
1478/// Global reactive handler singleton.
1479static GLOBAL_HANDLER: OnceLock<ReactiveHandler> = OnceLock::new();
1480
1481/// Get or initialize the global reactive handler.
1482pub fn get_global_handler() -> &'static ReactiveHandler {
1483    GLOBAL_HANDLER.get_or_init(ReactiveHandler::new)
1484}
1485
1486#[cfg(test)]
1487#[path = "handler_needs_review_tests.rs"]
1488mod needs_review_hook_tests;