Skip to main content

agentmux_srv_core/muxbus/cloud_subscriber/
live_names.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The names the relay subscription holds: every name a live pane answers to.
5//!
6//! A pane is bound in the reactive registry by a display and a stable name,
7//! but its agent also answers to its definition's slug and its display name's
8//! route name, and a re-registration can leave one of those unbound while the
9//! pane keeps running: a fork whose stored slug is chained (`loap-loap-2-loap-3`)
10//! is registered as `Loap-3` by the pane, then rebound by its spawn under the
11//! slug, which no path subscribed. Its subscription `loap-3` then looked
12//! orphaned and was dropped, and the slug was never subscribed, so nothing
13//! from the relay reached it. Here a subscription is matched against every
14//! name of a live agent before it is dropped, every such name is subscribed,
15//! and a message pulled for one is delivered to the pane that runs its agent.
16//!
17//! That includes, for [`FORMER_SLUG_GRACE`] after a rename, each slug the
18//! agent was renamed from (`SPEC_FORK_SLUG_MIGRATION_2026_10_22.md` Phase 1):
19//! review notices for PRs opened under the old id still arrive. Receive-only:
20//! nothing is sent as a former slug, which can't sign (`actor::uid_owns_name`).
21//! A display name the agent was renamed from is held the same way, by its
22//! route, while it still resolves to that agent alone
23//! (`Store::agent_former_display_names_routable`).
24
25use std::collections::{HashMap, HashSet};
26use std::sync::{Arc, Mutex};
27use std::time::{Duration, Instant};
28
29use crate::backend::reactive::handler::ReactiveHandler;
30
31use super::CloudSubscriber;
32
33/// One live registration: its lowercased names, in the registry's order
34/// (display first), and its agent's UID when the registry has one.
35#[derive(Debug, Clone, Default, PartialEq, Eq)]
36pub(super) struct LiveAgent {
37    pub(super) names: Vec<String>,
38    pub(super) uid: Option<String>,
39}
40
41/// Lowercased name → the UID of the one agent definition that answers to it.
42#[derive(Debug, Default)]
43pub(super) struct NameDirectory {
44    by_name: HashMap<String, String>,
45}
46
47impl NameDirectory {
48    /// From `(uid, slug, display name)` rows. A slug outranks a display
49    /// name's route name, as `Store::agent_defs_for_target` resolves a
50    /// target, and a name several definitions answer to at its best rank
51    /// names none of them: an agent is never kept under a name that isn't
52    /// only its own.
53    pub(super) fn from_defs<'a>(defs: impl IntoIterator<Item = (&'a str, &'a str, &'a str)>) -> Self {
54        Self::from_defs_and_former(defs, std::iter::empty())
55    }
56
57    /// [`Self::from_defs`], plus `(uid, former slug)` pairs ranked below
58    /// both, as `agent_defs_for_target` tries them last. Only slugs still in
59    /// their grace period belong here ([`in_grace`]): holding a former name
60    /// renews its WAN lease, so it is held for a bounded time, never for good.
61    pub(super) fn from_defs_and_former<'a>(
62        defs: impl IntoIterator<Item = (&'a str, &'a str, &'a str)>,
63        former: impl IntoIterator<Item = (&'a str, &'a str)>,
64    ) -> Self {
65        let mut ranked: HashMap<String, (u8, HashSet<&'a str>)> = HashMap::new();
66        let defs = defs.into_iter().map(|(uid, slug, name)| {
67            let slug = Some(slug.trim().to_string()).filter(|s| agentmux_common::slug::is_agent_id(s));
68            (uid, vec![(0u8, slug), (1, crate::backend::reactive::sanitize::registrable_id(name))])
69        });
70        let former = former.into_iter().map(|(uid, slug)| {
71            let slug = Some(slug.trim().to_string()).filter(|s| agentmux_common::slug::is_agent_id(s));
72            (uid, vec![(2u8, slug)])
73        });
74        for (uid, keys) in defs.chain(former) {
75            if uid.is_empty() {
76                continue;
77            }
78            for (rank, key) in keys {
79                let Some(key) = key.map(|k| k.to_lowercase()) else { continue };
80                let entry = ranked.entry(key).or_insert((rank, HashSet::new()));
81                if rank < entry.0 {
82                    *entry = (rank, HashSet::new());
83                }
84                if rank == entry.0 {
85                    entry.1.insert(uid);
86                }
87            }
88        }
89        let by_name = ranked
90            .into_iter()
91            .filter_map(|(name, (_, uids))| {
92                let mut uids = uids.into_iter();
93                match (uids.next(), uids.next()) {
94                    (Some(uid), None) => Some((name, uid.to_string())),
95                    _ => None,
96                }
97            })
98            .collect();
99        Self { by_name }
100    }
101
102    fn uid_of(&self, name: &str) -> Option<&str> {
103        self.by_name.get(&name.to_lowercase()).map(String::as_str)
104    }
105}
106
107/// Every name the subscription should hold for `live`: each registration's
108/// own names and every name the directory gives its agent. Lowercased, sorted.
109pub(super) fn wanted(live: &[LiveAgent], dir: &NameDirectory) -> Vec<String> {
110    let uids: HashSet<&str> = live.iter().filter_map(|a| a.uid.as_deref()).collect();
111    let mut names: Vec<String> = live.iter().flat_map(|a| a.names.iter().cloned()).collect();
112    names.extend(
113        dir.by_name
114            .iter()
115            .filter(|(_, uid)| uids.contains(uid.as_str()))
116            .map(|(name, _)| name.clone()),
117    );
118    names.sort();
119    names.dedup();
120    names
121}
122
123/// The live registration `name` belongs to: one bound by it, else the one
124/// running the agent the directory says it names.
125fn holder<'a>(name: &str, live: &'a [LiveAgent], dir: &NameDirectory) -> Option<&'a LiveAgent> {
126    let key = name.to_lowercase();
127    live.iter().find(|a| a.names.contains(&key)).or_else(|| {
128        let uid = dir.uid_of(&key)?;
129        live.iter().find(|a| a.uid.as_deref() == Some(uid))
130    })
131}
132
133/// Does a live pane answer to `name`, by binding or through its agent?
134pub(super) fn is_held(name: &str, live: &[LiveAgent], dir: &NameDirectory) -> bool {
135    holder(name, live, dir).is_some()
136}
137
138/// Subscribed names no live pane answers to. Every way into the subscription
139/// runs with a live registration, so one without is a leak from a teardown
140/// that missed it; renewing its WAN lease would fence the agent everywhere
141/// else for as long as this srv runs.
142pub(super) fn orphaned_subscriptions(subscribed: &[String], live: &[LiveAgent], dir: &NameDirectory) -> Vec<String> {
143    subscribed.iter().filter(|a| !is_held(a, live, dir)).cloned().collect()
144}
145
146/// The name to deliver a message pulled for `name` to: `name` when a live
147/// pane is bound by it (or none answers to it), else the holder's name that
148/// the directory gives the same agent (its slug), which the registry resolves
149/// to that pane and the transcript-request rules resolve to its definition.
150pub(super) fn delivery_name(name: &str, live: &[LiveAgent], dir: &NameDirectory) -> String {
151    let key = name.to_lowercase();
152    match holder(name, live, dir) {
153        Some(agent) if !agent.names.contains(&key) => agent
154            .names
155            .iter()
156            .find(|n| agent.uid.is_some() && dir.uid_of(n) == agent.uid.as_deref())
157            .or_else(|| agent.names.first())
158            .cloned()
159            .unwrap_or_else(|| name.to_string()),
160        _ => name.to_string(),
161    }
162}
163
164/// Subscribe each wanted name `sub` doesn't hold yet (`add_agent`, which
165/// tells the WS loop). Returns the names added; a second call with nothing
166/// changed adds none.
167pub(super) fn subscribe_missing(sub: &CloudSubscriber, live: &[LiveAgent], dir: &NameDirectory) -> Vec<String> {
168    let held: HashSet<String> = sub.agents.lock().unwrap().clone();
169    let added: Vec<String> = wanted(live, dir).into_iter().filter(|n| !held.contains(n)).collect();
170    for name in &added {
171        sub.add_agent(name);
172    }
173    log_added(&added);
174    added
175}
176
177/// Put every wanted name in `agents` directly, before a session's first
178/// `subscribe` (which carries the whole set).
179pub(super) fn seed(agents: &Mutex<HashSet<String>>, live: &[LiveAgent], dir: &NameDirectory) -> Vec<String> {
180    let mut agents = agents.lock().unwrap();
181    let added: Vec<String> = wanted(live, dir).into_iter().filter(|n| agents.insert(n.clone())).collect();
182    drop(agents);
183    log_added(&added);
184    added
185}
186
187fn log_added(added: &[String]) {
188    if !added.is_empty() {
189        tracing::info!(names = ?added, "cloud_subscriber: subscribed names a live pane answers to");
190    }
191}
192
193/// The registry's live registrations now, by the same liveness the lease
194/// tick has always used (`has_live_name`). Takes the handler's lock once per
195/// call, never while holding the subscriber's.
196pub(super) fn live_agents(handler: &ReactiveHandler) -> Vec<LiveAgent> {
197    handler
198        .list_agents()
199        .into_iter()
200        .filter_map(|reg| {
201            let names: Vec<String> = handler
202                .names_for_block(&reg.block_id)
203                .iter()
204                .map(|n| n.to_lowercase())
205                .collect();
206            names
207                .iter()
208                .any(|n| handler.has_live_name(n))
209                .then_some(LiveAgent { names, uid: reg.uid })
210        })
211        .collect()
212}
213
214/// How long a loaded directory is reused. Names change only on a rename or a
215/// new agent; the lease tick and every registration consult it.
216const DIRECTORY_TTL: Duration = Duration::from_secs(60);
217
218/// How long after a rename a former slug stays subscribed (the spec's §9.1).
219/// After it, the next directory leaves the name out and the lease tick drops
220/// it as orphaned; it stays reserved locally.
221pub(super) const FORMER_SLUG_GRACE: Duration = Duration::from_secs(30 * 24 * 60 * 60);
222
223/// Whether a slug retired at `retired_at` (epoch ms) is still in its grace
224/// period at `now` (epoch ms). An unknown time (0) is not.
225pub(super) fn in_grace(retired_at: i64, now: i64) -> bool {
226    retired_at > 0 && now.saturating_sub(retired_at) < FORMER_SLUG_GRACE.as_millis() as i64
227}
228
229static DIRECTORY: Mutex<Option<(Instant, Arc<NameDirectory>)>> = Mutex::new(None);
230
231/// The definitions' names, from this channel's object store, cached for
232/// [`DIRECTORY_TTL`]. A failed read reuses the last directory, uncached, so a
233/// store hiccup doesn't drop every alias at once.
234pub(super) async fn directory() -> Arc<NameDirectory> {
235    let cached = DIRECTORY.lock().unwrap().clone();
236    if let Some((at, dir)) = &cached {
237        if at.elapsed() < DIRECTORY_TTL {
238            return Arc::clone(dir);
239        }
240    }
241    match tokio::task::spawn_blocking(load_directory).await {
242        Ok(Some(dir)) => {
243            let dir = Arc::new(dir);
244            *DIRECTORY.lock().unwrap() = Some((Instant::now(), Arc::clone(&dir)));
245            dir
246        }
247        _ => cached.map(|(_, dir)| dir).unwrap_or_default(),
248    }
249}
250
251/// A rename changed which names are current: the next lookup reads the
252/// directory again rather than wait out [`DIRECTORY_TTL`].
253pub(crate) fn names_changed() {
254    *DIRECTORY.lock().unwrap() = None;
255}
256
257fn load_directory() -> Option<NameDirectory> {
258    directory_from(crate::backend::identity_spawn::row_store()?, agentmux_common::time::now_ms())
259}
260
261/// The directory `store` gives at `now` (epoch ms): every definition's names,
262/// and the former slugs and former display names still in their grace period.
263pub(super) fn directory_from(store: &crate::backend::storage::store::Store, now: i64) -> Option<NameDirectory> {
264    let former = store.agent_former_slugs_all().unwrap_or_else(|e| {
265        tracing::warn!(error = %e, "cloud_subscriber: former slugs not read; none held");
266        Vec::new()
267    });
268    let display = store.agent_former_display_names_routable().unwrap_or_else(|e| {
269        tracing::warn!(error = %e, "cloud_subscriber: former display names not read; none held");
270        Vec::new()
271    });
272    let former = former
273        .iter()
274        .filter(|(_, f)| in_grace(f.retired_at, now))
275        .map(|(uid, f)| (uid.as_str(), f.slug.as_str()))
276        .chain(display.iter().filter(|(_, _, at)| in_grace(*at, now)).map(|(uid, key, _)| (uid.as_str(), key.as_str())));
277    match store.agent_def_list() {
278        Ok(defs) => Some(NameDirectory::from_defs_and_former(
279            defs.iter().map(|d| (d.id.as_str(), d.slug.as_str(), d.name.as_str())),
280            former,
281        )),
282        Err(e) => {
283            tracing::warn!(error = %e, "cloud_subscriber: agent names not read; keeping the last ones");
284            None
285        }
286    }
287}
288
289/// Wakes a session to subscribe a pane that just registered
290/// ([`registration_changed`]).
291static REGISTERED: std::sync::LazyLock<tokio::sync::Notify> = std::sync::LazyLock::new(tokio::sync::Notify::new);
292
293/// A pane registered: a session subscribes its names now rather than at the
294/// next lease tick. No locks taken, so safe under the handler's.
295pub(crate) fn registration_changed() {
296    REGISTERED.notify_one();
297}
298
299pub(super) async fn registrations_changed() {
300    REGISTERED.notified().await;
301}
302
303/// [`subscribe_missing`] against the global subscriber, the registry and
304/// the directory, for a session's registration wake and its lease tick.
305/// Returns the snapshot it used, for the tick's orphan check.
306pub(super) async fn subscribe_live(handler: &ReactiveHandler) -> (Vec<LiveAgent>, Arc<NameDirectory>) {
307    let live = live_agents(handler);
308    let dir = directory().await;
309    if let Some(sub) = super::get_global_subscriber() {
310        subscribe_missing(sub, &live, &dir);
311    }
312    (live, dir)
313}
314
315/// [`delivery_name`] for a message pulled for `name`; reads the store only
316/// when no live pane is bound by `name`.
317pub(super) async fn delivery_target(handler: &ReactiveHandler, name: &str) -> String {
318    if handler.has_live_name(name) {
319        return name.to_string();
320    }
321    let live = live_agents(handler);
322    delivery_name(name, &live, &*directory().await)
323}
324
325#[cfg(test)]
326#[path = "live_names_tests.rs"]
327mod tests;