Skip to main content

agentmux_srv/server/
registry_reconcile.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Puts a running agent back in the reactive registry when it has fallen out of it (task #2093).
5//!
6//! An agent is addressable (a message reaches it, `Agents conversations` and `Agents transcript` find it)
7//! only while the registry holds it, and the registry is written when its process spawns. If the entry
8//! goes while the process lives (a closing tool shell once removed the pane's own entry, #6931), nothing
9//! wrote it back until the next spawn, so a working agent answered "not found".
10//!
11//! Every [`LOOK_EVERY`] this looks at the agents that have a pane and registers each one that is missing,
12//! the way a start does (`jekt_start::make_addressable`). It only adds, and only for an agent whose
13//! controller holds a live process and carries that agent's own uid, so a stopped, parked or
14//! look-alike pane is never registered. An agent registered twice is the same registration.
15//!
16//! The process's own exit removes only the entry it wrote (compare-and-remove on its spawn nonce), so
17//! each entry made here carries a nonce of its own, kept in [`Reconciled`], and the next look removes it
18//! once the process has ended. A respawn that registered meanwhile has another nonce and is left alone.
19
20use std::collections::HashMap;
21use std::sync::atomic::{AtomicU64, Ordering};
22use std::time::Duration;
23
24use crate::backend::blockcontroller::{self, STATUS_RUNNING};
25use crate::backend::obj::Block;
26
27use super::AppState;
28
29/// How often the registry is checked against the panes.
30const LOOK_EVERY: Duration = Duration::from_secs(60);
31
32/// The entries this module made: block id to the nonce it registered under.
33type Reconciled = HashMap<String, u64>;
34
35/// A nonce for an entry made here. Counted down from the top, so it never meets a controller's, which
36/// count up from 1.
37fn next_nonce() -> u64 {
38    static NEXT: AtomicU64 = AtomicU64::new(u64::MAX);
39    NEXT.fetch_sub(1, Ordering::Relaxed)
40}
41
42/// Whether an agent that is missing from the registry should be put back: its controller holds a live
43/// process and was spawned as this uid, and its block is not parked (a parked block is on its way out).
44fn should_register(uid: &str, parked: bool, controller_uid: Option<&str>, process_status: &str) -> bool {
45    !parked && controller_uid == Some(uid) && process_status == STATUS_RUNNING
46}
47
48/// Whether the block's controller holds a live process.
49fn process_running(block_id: &str) -> bool {
50    blockcontroller::get_controller(block_id).is_some_and(|c| c.get_runtime_status().shellprocstatus == STATUS_RUNNING)
51}
52
53/// Removes the entries made here whose process has ended. Returns the blocks it cleared.
54fn drop_ended(state: &AppState, made: &mut Reconciled, running: impl Fn(&str) -> bool) -> Vec<String> {
55    let ended: Vec<String> = made.keys().filter(|b| !running(b)).cloned().collect();
56    for block_id in &ended {
57        if let Some(nonce) = made.remove(block_id) {
58            state.reactive_handler.unregister_block_if_nonce(block_id, nonce);
59        }
60    }
61    ended
62}
63
64/// Registers every agent with a live process that the registry does not hold, and clears the entries made
65/// here for a process that has ended. Returns the uids it put back. Blocking: reads the store.
66fn reconcile(state: &AppState, made: &mut Reconciled) -> Vec<String> {
67    drop_ended(state, made, process_running);
68    let mut registered = Vec::new();
69    for (uid, block_id) in super::agent_runtime::pane_blocks_by_agent(&state.mstore) {
70        if state.reactive_handler.has_uid_registration(&uid) {
71            continue;
72        }
73        let Some(controller) = blockcontroller::get_controller(&block_id) else {
74            continue;
75        };
76        let parked = state
77            .mstore
78            .get::<Block>(&block_id)
79            .ok()
80            .flatten()
81            .is_some_and(|b| crate::backend::obj::meta_get_bool(&b.meta, crate::persist_subscriber::parked::PARKED_META_KEY, false));
82        let status = controller.get_runtime_status().shellprocstatus;
83        if !should_register(&uid, parked, controller.stable_agent_uid().as_deref(), &status) {
84            continue;
85        }
86        let nonce = next_nonce();
87        if super::jekt_start::make_addressable(state, &uid, &block_id, nonce) {
88            tracing::warn!(agent_uid = %uid, block_id = %block_id, "registry: a running agent was missing from it — registered again");
89            made.insert(block_id, nonce);
90            registered.push(uid);
91        }
92    }
93    registered
94}
95
96/// Runs [`reconcile`] on an interval for the life of the server.
97pub(crate) fn spawn(state: AppState) {
98    tokio::spawn(async move {
99        let mut made = Reconciled::new();
100        loop {
101            tokio::time::sleep(LOOK_EVERY).await;
102            let looked = state.clone();
103            match tokio::task::spawn_blocking(move || {
104                reconcile(&looked, &mut made);
105                made
106            })
107            .await
108            {
109                Ok(kept) => made = kept,
110                Err(e) => {
111                    tracing::warn!("registry reconcile: {e}");
112                    made = Reconciled::new();
113                }
114            }
115        }
116    });
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn a_running_agent_whose_controller_carries_its_uid_is_put_back() {
125        assert!(should_register("u1", false, Some("u1"), STATUS_RUNNING));
126    }
127
128    #[test]
129    fn a_parked_stopped_or_look_alike_pane_is_left_alone() {
130        assert!(!should_register("u1", true, Some("u1"), STATUS_RUNNING), "parked");
131        assert!(!should_register("u1", false, Some("u1"), "done"), "its process ended");
132        assert!(!should_register("u1", false, Some("u1"), ""), "no process yet");
133        assert!(!should_register("u1", false, Some("u2"), STATUS_RUNNING), "another agent's controller");
134        assert!(!should_register("u1", false, None, STATUS_RUNNING), "a controller with no agent uid");
135    }
136
137    #[tokio::test]
138    async fn an_agent_with_no_pane_is_not_registered() {
139        let state = super::super::tests::test_state();
140        assert!(reconcile(&state, &mut Reconciled::new()).is_empty());
141    }
142
143    #[tokio::test]
144    async fn an_entry_made_here_goes_when_its_process_ends_but_a_respawns_stays() {
145        let state = super::super::tests::test_state();
146        let tag = uuid::Uuid::new_v4();
147        let (gone, kept) = (format!("blk-gone-{tag}"), format!("blk-kept-{tag}"));
148        let (gone_uid, kept_uid) = (format!("rc-{tag}-a"), format!("rc-{tag}-b"));
149        let (gone_nonce, kept_nonce) = (next_nonce(), next_nonce());
150        let h = &state.reactive_handler;
151        h.register_agent_full("reconcile-a", &gone, None, gone_nonce, None, Some(&gone_uid), "t").unwrap();
152        h.register_agent_full("reconcile-b", &kept, None, kept_nonce - 1, None, Some(&kept_uid), "t").unwrap(); // a respawn's own nonce
153        let mut made = Reconciled::from([(gone.clone(), gone_nonce), (kept.clone(), kept_nonce)]);
154
155        let cleared = drop_ended(&state, &mut made, |_| false);
156
157        assert_eq!(cleared.len(), 2);
158        assert!(!h.has_uid_registration(&gone_uid), "the entry made here goes with its process");
159        assert!(h.has_uid_registration(&kept_uid), "an entry that changed hands is not ours to remove");
160        assert!(made.is_empty());
161    }
162}