Skip to main content

agentmux_srv_core/backend/
agent_admission.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! One live instance per agent — the host tier
5//! (`docs/specs/SPEC_AGENT_SINGLE_LIVE_INSTANCE_2026_09_24.md`, Phase 1).
6//!
7//! An agent identity (its UID) may be driven by at most one process on this
8//! host. Two layers:
9//!
10//! - [`acquire`] — the binding decision. A persistent pane claims the
11//!   agent's [`LeaseStore`] lease right before its CLI process is spawned
12//!   and holds it for that process's lifetime ([`HeldAgentLease`]): renewed
13//!   on its own task, released on drop, and **fenced** — a holder that loses
14//!   the lease (suspended past the TTL and reclaimed) is told through
15//!   `on_lost` so it stops driving, and [`HeldAgentLease::verify`] lets it
16//!   refuse a turn before starting one.
17//! - [`check_before_spawn`] — the early, read-only check the async spawn
18//!   paths run **before** they write anything shared on the agent's behalf
19//!   (spec I9: in the 2026-09-25 incident the second instance broke the
20//!   first by rebinding its account, before any spawn). It reads the lease
21//!   and, for instances too old to take one, asks every other live
22//!   AgentMux instance on this host whether it is running this UID.
23
24use agentmux_common::AUTH_KEY_HEADER;
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::sync::Arc;
27
28use crate::registry::{ClaimantInfo, Lease, LeaseError, LeaseHolder, LeaseStore};
29
30/// The lease store under a shared agent registry root, `None` if there is
31/// no registry or its lease directory can't be opened (logged).
32pub fn lease_store_for(registry: Option<Arc<crate::registry::Registry>>) -> Option<Arc<LeaseStore>> {
33    let registry = registry?;
34    match LeaseStore::open(registry.root()) {
35        Ok(store) => Some(Arc::new(store)),
36        Err(e) => {
37            tracing::error!(error = %e, "agent_admission: cannot open the lease store — no single-instance check");
38            None
39        }
40    }
41}
42
43/// What this instance records about itself in a lease it takes.
44pub fn claimant_info() -> ClaimantInfo {
45    ClaimantInfo {
46        channel: crate::backend::reactive::registry::local_channel_id(),
47        version: env!("CARGO_PKG_VERSION").to_string(),
48    }
49}
50
51/// The refusal a user sees when `agent` is already running elsewhere.
52pub fn denied_message(agent: &str, holder: Option<&LeaseHolder>) -> String {
53    let agent = if agent.is_empty() { "This agent" } else { agent };
54    let Some(h) = holder else {
55        return format!(
56            "{agent} is already running in another AgentMux instance on this host. \
57             Close it there, then try again — an agent can only run in one place at a time."
58        );
59    };
60    let mut place = Vec::new();
61    if !h.channel.is_empty() {
62        place.push(format!("channel {}", h.channel));
63    }
64    if !h.version.is_empty() {
65        place.push(format!("v{}", h.version));
66    }
67    if h.pid != 0 {
68        place.push(format!("pid {}", h.pid));
69    }
70    if h.acquired_at_ms > 0 {
71        let mins = (agentmux_common::time::now_ms() - h.acquired_at_ms).max(0) / 60_000;
72        place.push(format!("running for {mins} min"));
73    }
74    let place = if place.is_empty() { String::new() } else { format!(" ({})", place.join(", ")) };
75    format!(
76        "{agent} is already running in another AgentMux instance on this host{place}. \
77         Close it there, then try again — an agent can only run in one place at a time."
78    )
79}
80
81/// A lease held for the lifetime of one CLI process. Dropping it stops the
82/// renewal task and releases the lease.
83pub struct HeldAgentLease {
84    store: Arc<LeaseStore>,
85    lease: Lease,
86    agent: String,
87    /// Set once, by whichever notices first (the renewal task or a pre-turn
88    /// `verify`): the refusal every later turn repeats — so the second and
89    /// later refusals still name who took the agent over (ReAgent P2 on
90    /// #3738), not a detail-less fallback.
91    lost: Arc<LostReason>,
92    stopped: Arc<AtomicBool>,
93    /// When the lease was last confirmed ours (claim, renew or verify), in
94    /// ms. [`RecordFence`] trusts the in-memory state only while this is
95    /// within the TTL.
96    last_ok_ms: Arc<std::sync::atomic::AtomicI64>,
97}
98
99/// The first loss message, kept for every later refusal.
100#[derive(Default)]
101struct LostReason(std::sync::Mutex<Option<String>>);
102
103impl LostReason {
104    fn get(&self) -> Option<String> {
105        self.0.lock().unwrap_or_else(|e| e.into_inner()).clone()
106    }
107
108    /// Record `msg` unless a reason is already recorded; return the one kept.
109    fn set_first(&self, msg: String) -> String {
110        self.0.lock().unwrap_or_else(|e| e.into_inner()).get_or_insert(msg).clone()
111    }
112}
113
114impl HeldAgentLease {
115    /// The ownership generation this lease was granted under.
116    pub fn epoch(&self) -> u64 {
117        self.lease.epoch()
118    }
119
120    /// The agent UID this lease is for — its key.
121    pub fn agent_uid(&self) -> &str {
122        self.lease.instance_id()
123    }
124
125    /// A cheap handle the agent's output writer checks before each append
126    /// to the agent's shared record (spec §4.3, Phase 3).
127    pub fn record_fence(&self) -> RecordFence {
128        RecordFence {
129            store: Arc::clone(&self.store),
130            lease: self.lease.clone(),
131            agent: self.agent.clone(),
132            lost: Arc::clone(&self.lost),
133            last_ok_ms: Arc::clone(&self.last_ok_ms),
134        }
135    }
136
137    /// The pre-turn fence check (spec I4). `Err` means another instance now
138    /// holds this agent: do not start the turn. A transient I/O error is not
139    /// a loss — the renewal task decides that — so it does not refuse.
140    pub fn verify(&self) -> Result<(), String> {
141        if let Some(why) = self.lost.get() {
142            return Err(why);
143        }
144        match self.store.verify(&self.lease) {
145            Ok(()) => {
146                self.last_ok_ms.store(agentmux_common::time::now_ms(), Ordering::SeqCst);
147                Ok(())
148            }
149            Err(LeaseError::HeldByOther { holder, .. }) => {
150                Err(self.lost.set_first(lost_message(&self.agent, holder.as_ref(), self.lease.owner_boot_id())))
151            }
152            Err(LeaseError::Io(e)) => {
153                tracing::warn!(agent = %self.agent, error = %e, "agent lease: verify failed (io) — not treating as lost");
154                Ok(())
155            }
156        }
157    }
158}
159
160impl Drop for HeldAgentLease {
161    fn drop(&mut self) {
162        self.stopped.store(true, Ordering::SeqCst);
163        unregister_by_name(&self.agent, &self.lost);
164        if let Err(e) = self.store.release(&self.lease) {
165            tracing::warn!(
166                agent = %self.agent,
167                instance_id = %self.lease.instance_id(),
168                error = %e,
169                "agent lease: release failed (self-heals via TTL expiry)"
170            );
171        }
172    }
173}
174
175/// The block of this same process that holds the lease, when the holder is not another instance: the
176/// lease reports a held agent the same way whoever holds it, and a second pane of this AgentMux that
177/// claims an agent its first pane runs is "another pane", not "another AgentMux instance".
178fn own_process_holder<'a>(holder: Option<&'a LeaseHolder>, own_boot: &str) -> Option<&'a str> {
179    holder.filter(|h| h.owner_boot_id == own_boot && !h.block_id.is_empty()).map(|h| h.block_id.as_str())
180}
181
182fn lost_message(agent: &str, holder: Option<&LeaseHolder>, own_boot: &str) -> String {
183    let agent = if agent.is_empty() { "This agent" } else { agent };
184    if let Some(block) = own_process_holder(holder, own_boot) {
185        return crate::backend::blockcontroller::persistent::held_elsewhere_error(block, false);
186    }
187    match holder {
188        Some(_) => format!(
189            "{agent} was taken over by another AgentMux instance on this host — {}",
190            denied_message(agent, holder)
191        ),
192        None => format!("{agent} lost its single-instance lease; it will not start another turn here."),
193    }
194}
195
196/// Claim `uid` for this process's `block_id`, and keep it renewed until the
197/// returned handle is dropped. `on_lost` runs (once, off the caller's
198/// thread) if the lease is found to belong to someone else — the holder must
199/// then stop driving the agent.
200///
201/// `Err` is the user-facing refusal. The host tier fails closed (spec D2):
202/// an I/O error claiming the lease refuses rather than running unguarded,
203/// after one short retry for a transient sharing violation.
204pub fn acquire(
205    store: &Arc<LeaseStore>,
206    uid: &str,
207    agent: &str,
208    boot_id: &Arc<str>,
209    block_id: &str,
210    session_id_hint: Option<&str>,
211    on_lost: impl Fn(String) + Send + Sync + 'static,
212) -> Result<HeldAgentLease, String> {
213    if let Some(refusal) = handover_hold_refusal(uid, agent) {
214        tracing::info!(agent, uid, block_id, "agent_admission.denied: inside a handover hold");
215        return Err(refusal);
216    }
217    let info = claimant_info();
218    let mut result = store.claim_as(uid, boot_id, block_id, session_id_hint, &info);
219    if matches!(result, Err(LeaseError::Io(_))) {
220        std::thread::sleep(std::time::Duration::from_millis(100));
221        result = store.claim_as(uid, boot_id, block_id, session_id_hint, &info);
222    }
223    let lease = match result {
224        Ok(lease) => lease,
225        Err(LeaseError::HeldByOther { holder, owner_boot_id, age_ms, .. }) => {
226            let own_block = own_process_holder(holder.as_ref(), boot_id).map(str::to_string);
227            tracing::warn!(
228                agent,
229                uid,
230                block_id,
231                owner_boot_id = %owner_boot_id,
232                same_process = own_block.is_some(),
233                holder_block = holder.as_ref().map(|h| h.block_id.as_str()).unwrap_or(""),
234                holder_channel = holder.as_ref().map(|h| h.channel.as_str()).unwrap_or(""),
235                age_ms,
236                "agent_admission.denied: agent is live in another instance"
237            );
238            if let Some(block) = own_block {
239                return Err(crate::backend::blockcontroller::persistent::held_elsewhere_error(&block, false));
240            }
241            return Err(denied_message(agent, holder.as_ref()));
242        }
243        Err(LeaseError::Io(e)) => {
244            tracing::error!(agent, uid, block_id, error = %e, "agent_admission.unknown: lease claim failed (io) — refusing");
245            return Err(format!(
246                "Could not confirm that {} isn't already running elsewhere (lease file error: {e}). \
247                 Refusing to start it twice.",
248                if agent.is_empty() { "this agent" } else { agent }
249            ));
250        }
251    };
252    tracing::info!(agent, uid, block_id, epoch = lease.epoch(), "agent_admission.granted");
253    let on_lost: Arc<dyn Fn(String) + Send + Sync> = Arc::new(on_lost);
254
255    let held = HeldAgentLease {
256        store: Arc::clone(store),
257        lease: lease.clone(),
258        agent: agent.to_string(),
259        lost: Arc::new(LostReason::default()),
260        stopped: Arc::new(AtomicBool::new(false)),
261        last_ok_ms: Arc::new(std::sync::atomic::AtomicI64::new(agentmux_common::time::now_ms())),
262    };
263    spawn_renewal(
264        Arc::clone(store),
265        lease,
266        agent.to_string(),
267        Arc::clone(&held.lost),
268        Arc::clone(&held.stopped),
269        Arc::clone(&held.last_ok_ms),
270        {
271            let on_lost = Arc::clone(&on_lost);
272            move |why: String| on_lost(why)
273        },
274    );
275    register_by_name(agent, &held.lost, on_lost);
276    Ok(held)
277}
278
279fn spawn_renewal(
280    store: Arc<LeaseStore>,
281    lease: Lease,
282    agent: String,
283    lost: Arc<LostReason>,
284    stopped: Arc<AtomicBool>,
285    last_ok_ms: Arc<std::sync::atomic::AtomicI64>,
286    on_lost: impl Fn(String) + Send + Sync + 'static,
287) {
288    let Ok(handle) = tokio::runtime::Handle::try_current() else {
289        // No runtime (unit tests that spawn synchronously): the lease still
290        // guards the claim and is released on drop; it just isn't renewed.
291        return;
292    };
293    handle.spawn(async move {
294        let mut interval =
295            tokio::time::interval(std::time::Duration::from_millis(crate::registry::RENEW_INTERVAL_MS));
296        // A laptop waking from sleep fires one tick, not a burst.
297        interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
298        interval.tick().await; // the first tick is immediate; the claim just wrote the file
299        let acquired_at_ms = agentmux_common::time::now_ms();
300        let my_host = this_host_label();
301        let mut ticks: u32 = 0;
302        loop {
303            interval.tick().await;
304            if stopped.load(Ordering::SeqCst) {
305                break;
306            }
307            ticks = ticks.wrapping_add(1);
308            // LAN tier (spec §4.4): two hosts can start the same agent at the
309            // same moment, before either sees the other. Every
310            // LAN_RECHECK_TICKS renewals, ask the LAN again; the loser of the
311            // deterministic tie-break fences itself.
312            if ticks % LAN_RECHECK_TICKS == 0 {
313                if let Some(winner) = lan_holders(lease.instance_id())
314                    .await
315                    .into_iter()
316                    .find(|p| peer_wins(p.acquired_at_ms, &p.hostname, acquired_at_ms, &my_host))
317                {
318                    if stopped.load(Ordering::SeqCst) {
319                        break;
320                    }
321                    let why = lost.set_first(lan_lost_message(&agent, &winner));
322                    tracing::error!(
323                        agent = %agent,
324                        instance_id = %lease.instance_id(),
325                        peer_host = %winner.hostname,
326                        "agent_admission.fenced: another computer on the LAN runs this agent and wins the tie-break — stopping this one"
327                    );
328                    on_lost(why);
329                    break;
330                }
331            }
332            let (s, l) = (Arc::clone(&store), lease.clone());
333            let renewed = tokio::task::spawn_blocking(move || s.renew(&l)).await;
334            // Checked again after the blocking renew: a release that ran
335            // meanwhile must not be reported as a loss.
336            if stopped.load(Ordering::SeqCst) {
337                break;
338            }
339            match renewed {
340                Ok(Ok(())) => last_ok_ms.store(agentmux_common::time::now_ms(), Ordering::SeqCst),
341                Ok(Err(LeaseError::HeldByOther { holder, owner_boot_id, .. })) => {
342                    let why = lost.set_first(lost_message(&agent, holder.as_ref(), lease.owner_boot_id()));
343                    tracing::error!(
344                        agent = %agent,
345                        instance_id = %lease.instance_id(),
346                        owner_boot_id = %owner_boot_id,
347                        same_process = owner_boot_id == lease.owner_boot_id(),
348                        "agent_admission.fenced: lease lost to another claim — stopping this one"
349                    );
350                    on_lost(why);
351                    break;
352                }
353                Ok(Err(LeaseError::Io(e))) => {
354                    tracing::warn!(agent = %agent, error = %e, "agent lease: renew failed (io) — will retry");
355                }
356                Err(join) => {
357                    tracing::warn!(agent = %agent, error = %join, "agent lease: renew task panicked — will retry");
358                }
359            }
360        }
361    });
362}
363
364/// A live instance on this host that is running the same agent UID but
365/// took no lease (it predates Phase 1) — found by asking it.
366#[derive(Clone, PartialEq, Eq)]
367pub struct LegacyHolder {
368    pub channel: String,
369    pub local_url: String,
370    pub block_id: String,
371    /// That srv's full auth key, from its shared-registry entry — what a
372    /// takeover request authenticates with. Never logged.
373    pub auth_key: String,
374}
375
376/// The early, read-only admission check (see module doc). `Err` is the
377/// user-facing refusal; callers must run it before any shared write.
378pub async fn check_before_spawn(
379    store: Option<Arc<LeaseStore>>,
380    uid: &str,
381    agent: &str,
382    own_boot_id: &str,
383) -> Result<(), String> {
384    if uid.is_empty() {
385        return Ok(());
386    }
387    if let Some(refusal) = handover_hold_refusal(uid, agent) {
388        return Err(refusal);
389    }
390    if let Some(store) = store {
391        let (u, b) = (uid.to_string(), own_boot_id.to_string());
392        match tokio::task::spawn_blocking(move || store.live_holder_other_than(&u, &b)).await {
393            Ok(Ok(Some(holder))) => {
394                tracing::warn!(agent, uid, holder_channel = %holder.channel, "agent_admission.denied (early check)");
395                return Err(denied_message(agent, Some(&holder)));
396            }
397            Ok(Ok(None)) => {}
398            Ok(Err(e)) => tracing::warn!(agent, uid, error = %e, "agent_admission: early lease read failed — the spawn-time claim still decides"),
399            Err(e) => tracing::warn!(agent, uid, error = %e, "agent_admission: early lease read panicked"),
400        }
401    }
402    if let Some(where_) = crate::muxbus::wan_lease::held_elsewhere(agent) {
403        tracing::warn!(agent, uid, holder = %where_, "agent_admission.denied: the muxbus relay says another instance holds this agent");
404        return Err(wan_denied_message(agent, &where_));
405    }
406    if let Some(peer) = lan_holders(uid).await.into_iter().next() {
407        tracing::warn!(agent, uid, peer_host = %peer.hostname, "agent_admission.denied: agent is live on a LAN peer");
408        return Err(lan_denied_message(agent, &peer));
409    }
410    if let Some(legacy) = probe_other_instances(uid).await {
411        tracing::warn!(
412            agent,
413            uid,
414            holder_channel = %legacy.channel,
415            holder_url = %legacy.local_url,
416            holder_block = %legacy.block_id,
417            "agent_admission.compat_probe_hit: agent is live in an instance that takes no lease"
418        );
419        let holder = LeaseHolder {
420            owner_boot_id: String::new(),
421            block_id: legacy.block_id,
422            pid: 0,
423            channel: legacy.channel,
424            version: String::new(),
425            hostname: String::new(),
426            epoch: 0,
427            acquired_at_ms: 0,
428            renewed_at_ms: 0,
429        };
430        return Err(denied_message(agent, Some(&holder)));
431    }
432    Ok(())
433}
434
435static PROBE_CLIENT: std::sync::LazyLock<reqwest::Client> = std::sync::LazyLock::new(|| {
436    crate::http_client::client_with(|b| b.timeout(std::time::Duration::from_millis(1_500)))
437});
438
439/// Ask every other live AgentMux instance on this host (from the
440/// host-global cross-channel registry) whether it has `uid` registered.
441/// Matched by UID, never by name (display names are not unique — Codex P2
442/// on #3730). An instance too old to report UIDs, or one that doesn't
443/// answer, is not evidence either way and is skipped (logged).
444pub async fn probe_other_instances(uid: &str) -> Option<LegacyHolder> {
445    let shared = crate::registry::resolve_shared_reactive_dir()?;
446    let own_channel = crate::backend::reactive::registry::local_channel_id();
447    let own_pid = std::process::id();
448    let entries = tokio::task::spawn_blocking(move || {
449        crate::backend::reactive::registry::list_all_shared(&shared)
450    })
451    .await
452    .ok()?;
453    let mut seen = std::collections::HashSet::new();
454    let others: Vec<_> = entries
455        .into_iter()
456        .filter(|e| e.channel != own_channel && e.pid != own_pid && !e.local_url.is_empty())
457        .filter(|e| e.srv_alive())
458        .filter(|e| seen.insert(e.local_url.clone()))
459        .collect();
460    let probes = others.into_iter().map(|e| async move {
461        let found = registered_uid_blocks(&e.local_url, &e.auth_key, uid).await;
462        (e, found)
463    });
464    for (entry, found) in futures_util::future::join_all(probes).await {
465        match found {
466            Ok(Some(block_id)) => {
467                return Some(LegacyHolder {
468                    channel: entry.channel,
469                    local_url: entry.local_url,
470                    block_id,
471                    auth_key: entry.auth_key,
472                })
473            }
474            Ok(None) => {}
475            Err(why) => tracing::debug!(
476                channel = %entry.channel,
477                url = %entry.local_url,
478                why,
479                "agent_admission: other instance not probeable — skipped"
480            ),
481        }
482    }
483    None
484}
485
486/// `GET <local_url>/agentmux/reactive/agents` and return the block of the
487/// first registration whose `uid` equals `uid`.
488async fn registered_uid_blocks(local_url: &str, auth_key: &str, uid: &str) -> Result<Option<String>, String> {
489    let mut req = PROBE_CLIENT.get(format!("{local_url}/agentmux/reactive/agents"));
490    if !auth_key.is_empty() {
491        req = req.header(AUTH_KEY_HEADER, auth_key);
492    }
493    let resp = req.send().await.map_err(|e| e.to_string())?;
494    if !resp.status().is_success() {
495        return Err(format!("HTTP {}", resp.status()));
496    }
497    let regs: Vec<serde_json::Value> = resp.json().await.map_err(|e| e.to_string())?;
498    Ok(find_uid_block(&regs, uid))
499}
500
501/// The block of the first registration in `regs` carrying `uid`.
502fn find_uid_block(regs: &[serde_json::Value], uid: &str) -> Option<String> {
503    regs.iter().find_map(|r| {
504        let r_uid = r.get("uid").and_then(|v| v.as_str())?;
505        (r_uid.trim().eq_ignore_ascii_case(uid.trim())).then(|| {
506            r.get("block_id").and_then(|v| v.as_str()).unwrap_or_default().to_string()
507        })
508    })
509}
510
511// ── Phase 5: WAN tier — the relay decides (spec §4.5) ──────────────────
512
513type LostCallback = Arc<dyn Fn(String) + Send + Sync>;
514
515/// The held leases of this process by agent **name** (lower-cased) — the key
516/// the muxbus relay and its pending queue use — so the WAN side can fence the
517/// local holder when the relay says another instance holds the agent.
518static HELD_BY_NAME: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<String, (Arc<LostReason>, LostCallback)>>> =
519    std::sync::LazyLock::new(Default::default);
520
521fn register_by_name(agent: &str, lost: &Arc<LostReason>, on_lost: LostCallback) {
522    if agent.trim().is_empty() {
523        return;
524    }
525    HELD_BY_NAME
526        .lock()
527        .unwrap_or_else(|e| e.into_inner())
528        .insert(agent.trim().to_lowercase(), (Arc::clone(lost), on_lost));
529}
530
531fn unregister_by_name(agent: &str, lost: &Arc<LostReason>) {
532    let mut map = HELD_BY_NAME.lock().unwrap_or_else(|e| e.into_inner());
533    let key = agent.trim().to_lowercase();
534    // Only our own entry: a newer lease for the same name may have replaced it.
535    if map.get(&key).is_some_and(|(l, _)| Arc::ptr_eq(l, lost)) {
536        map.remove(&key);
537    }
538}
539
540/// The relay says another instance holds `agent_name` (WAN tier): fence this
541/// process's holder of that agent, if any — record the loss (the pre-turn
542/// fence refuses its next turn) and stop its CLI process. `true` when a
543/// local holder was fenced.
544pub fn fence_agent_named(agent_name: &str, where_: &str) -> bool {
545    let entry = HELD_BY_NAME
546        .lock()
547        .unwrap_or_else(|e| e.into_inner())
548        .get(&agent_name.trim().to_lowercase())
549        .cloned();
550    let Some((lost, on_lost)) = entry else { return false };
551    if lost.get().is_some() {
552        return false;
553    }
554    let why = lost.set_first(wan_lost_message(agent_name, where_));
555    tracing::error!(agent = agent_name, holder = where_, "agent_admission.fenced: the muxbus relay says another instance holds this agent — stopping this one");
556    on_lost(why);
557    true
558}
559
560/// Where the relay says the holder is: "on another computer (computer X, …)",
561/// or "on this computer (channel Y, vZ)" for another instance on this host
562/// (charlie, 2026-09-26: a same-host holder was called "another computer").
563fn wan_place(where_: &str) -> String {
564    if crate::muxbus::wan_lease::holder_on_this_computer(where_) {
565        let rest = where_.trim_start_matches("this computer").trim_start_matches(", ");
566        return if rest.is_empty() { "on this computer".to_string() } else { format!("on this computer ({rest})") };
567    }
568    if where_.is_empty() { "on another computer".to_string() } else { format!("on another computer ({where_})") }
569}
570
571/// The refusal when the relay says another instance runs the agent. Carries
572/// the host refusal's marker, so it classifies as `LiveElsewhere`.
573pub fn wan_denied_message(agent: &str, where_: &str) -> String {
574    let agent = if agent.is_empty() { "This agent" } else { agent };
575    format!(
576        "{agent} is already running in another AgentMux instance {}, according to AgentMux Cloud. \
577         Close it there, then try again — an agent can only run in one place at a time.",
578        wan_place(where_)
579    )
580}
581
582fn wan_lost_message(agent: &str, where_: &str) -> String {
583    let agent = if agent.is_empty() { "This agent" } else { agent };
584    format!(
585        "{agent} was taken over by another AgentMux instance {}, according to AgentMux Cloud, which \
586         had it first. It will not start another turn here.",
587        wan_place(where_)
588    )
589}
590
591// ── Phase 4: LAN tier — detect and yield (spec §4.4) ───────────────────
592
593/// Renewals between LAN re-checks: 6 × RENEW_INTERVAL_MS = 30 s.
594const LAN_RECHECK_TICKS: u32 = 6;
595
596/// Start times closer than this are "simultaneous": clocks on two hosts are
597/// not compared finer than this; the hostname decides instead (§4.4).
598pub const LAN_SKEW_BUDGET_MS: i64 = 10_000;
599
600/// How long one LAN peer gets to answer.
601const LAN_QUERY_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(1_500);
602
603static LAN_DISCOVERY: std::sync::OnceLock<Arc<crate::backend::lan::discovery::LanDiscoveryController>> =
604    std::sync::OnceLock::new();
605
606/// Called once at bootstrap: gives admission the LAN peer list. Without it
607/// (tests, LAN discovery off) the LAN tier is skipped.
608pub fn set_lan_discovery(lan: Arc<crate::backend::lan::discovery::LanDiscoveryController>) {
609    let _ = LAN_DISCOVERY.set(lan);
610}
611
612/// A LAN peer's answer to `GET /agentmux/agent/holding?uid=…`.
613#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
614pub struct PeerHolding {
615    pub held: bool,
616    #[serde(default)]
617    pub hostname: String,
618    #[serde(default)]
619    pub channel: String,
620    #[serde(default)]
621    pub version: String,
622    #[serde(default)]
623    pub acquired_at_ms: i64,
624}
625
626/// This host's label, as a LAN peer reports it and as the tie-break compares.
627fn this_host_label() -> String {
628    crate::backend::reactive::registry::local_host_label()
629}
630
631/// What this host answers to a LAN peer asking about `uid`: held when any
632/// instance on this host holds a live lease for it.
633pub fn local_holding(store: Option<&Arc<LeaseStore>>, uid: &str) -> PeerHolding {
634    let holder = store.and_then(|s| s.live_holder_other_than(uid, "").ok().flatten());
635    match holder {
636        Some(h) => PeerHolding {
637            held: true,
638            hostname: this_host_label(),
639            channel: h.channel,
640            version: h.version,
641            acquired_at_ms: h.acquired_at_ms,
642        },
643        None => PeerHolding { hostname: this_host_label(), ..Default::default() },
644    }
645}
646
647/// Every reachable LAN peer **on another host** that says it holds `uid`.
648/// Unreachable or older peers (no route) are skipped: not evidence either
649/// way (D2, fail open). Answers from this host are dropped: another AgentMux
650/// instance here also shows up as a LAN peer, but it reads this host's own
651/// lease store, so it would report this process's own lease back — the
652/// host tier already governs this host.
653pub async fn lan_holders(uid: &str) -> Vec<PeerHolding> {
654    let Some(lan) = LAN_DISCOVERY.get() else { return Vec::new() };
655    let peers = lan.get_all_instances();
656    if peers.is_empty() || uid.is_empty() {
657        return Vec::new();
658    }
659    let queries = peers.into_iter().map(|p| async move {
660        let url = format!("{}/agentmux/agent/holding", super::lan::discovery::peer_base_url(&p.address, p.port));
661        let req = PROBE_CLIENT
662            .get(url)
663            .query(&[("uid", uid)])
664            .header(AUTH_KEY_HEADER, p.auth_key.as_str())
665            .timeout(LAN_QUERY_TIMEOUT);
666        match req.send().await {
667            Ok(r) if r.status().is_success() => r.json::<PeerHolding>().await.ok(),
668            _ => None,
669        }
670    });
671    futures_util::future::join_all(queries)
672        .await
673        .into_iter()
674        .flatten()
675        .filter(|h| h.held && !is_this_host(&h.hostname))
676        .collect()
677}
678
679fn is_this_host(hostname: &str) -> bool {
680    hostname.trim().eq_ignore_ascii_case(&this_host_label())
681}
682
683/// The LAN tie-break (§4.4): does a peer that started the agent at
684/// `peer_at` on `peer_host` win over this host's claim at `mine_at`? The
685/// earlier start wins; starts within the skew budget are simultaneous and
686/// the lower hostname wins. Deterministic and symmetric: exactly one side
687/// wins for any pair of distinct hosts.
688pub fn peer_wins(peer_at: i64, peer_host: &str, mine_at: i64, my_host: &str) -> bool {
689    if (peer_at - mine_at).abs() < LAN_SKEW_BUDGET_MS {
690        peer_host < my_host
691    } else {
692        peer_at < mine_at
693    }
694}
695
696fn lan_place(peer: &PeerHolding) -> String {
697    let mut place = Vec::new();
698    if !peer.hostname.is_empty() {
699        place.push(format!("computer {}", peer.hostname));
700    }
701    if !peer.channel.is_empty() {
702        place.push(format!("channel {}", peer.channel));
703    }
704    if !peer.version.is_empty() {
705        place.push(format!("v{}", peer.version));
706    }
707    if place.is_empty() { String::new() } else { format!(" ({})", place.join(", ")) }
708}
709
710/// The refusal when a LAN peer runs the agent. Carries the same marker as
711/// the host refusal, so it classifies as `LiveElsewhere`.
712pub fn lan_denied_message(agent: &str, peer: &PeerHolding) -> String {
713    let agent = if agent.is_empty() { "This agent" } else { agent };
714    format!(
715        "{agent} is already running in another AgentMux instance on another computer on your network{}. \
716         Close it there, then try again — an agent can only run in one place at a time.",
717        lan_place(peer)
718    )
719}
720
721fn lan_lost_message(agent: &str, peer: &PeerHolding) -> String {
722    let agent = if agent.is_empty() { "This agent" } else { agent };
723    format!(
724        "{agent} was taken over by another AgentMux instance on another computer on your network{}, which started it \
725         first. It will not start another turn here.",
726        lan_place(peer)
727    )
728}
729
730// ── Phase 2: takeover (spec §4.6) ────────────────────────────────────────
731
732/// Wording every single-live-instance refusal contains (lower-cased), so
733/// the failure classifier and callers can recognise one without a type.
734///
735/// Only refusals that mean *another instance holds the agent*. `acquire`'s
736/// lease-file I/O failure ("… Refusing to start it twice.") is deliberately
737/// not one: it is a local, possibly transient error, and classifying it as
738/// "running in another instance" would offer Take over instead of Retry
739/// (ReAgent P1 on #3742).
740pub const REFUSAL_MARKERS: [&str; 3] = [
741    "is already running in another agentmux instance",
742    "was taken over by another agentmux instance",
743    "lost its single-instance lease",
744];
745
746/// Is `message` a single-live-instance refusal (any of this module's
747/// user-facing refusal texts)?
748pub fn is_admission_refusal(message: &str) -> bool {
749    let m = message.to_ascii_lowercase();
750    REFUSAL_MARKERS.iter().any(|k| m.contains(k))
751}
752
753/// How long, after this srv hands an agent over to another instance, it
754/// refuses to claim that agent again on its own. Covers the gap between the
755/// holder's process exiting and the requester claiming, in which a jekt
756/// delivered here would otherwise respawn the agent and win it straight
757/// back. A takeover the user starts from this srv clears it.
758pub const HANDOVER_HOLD: std::time::Duration = std::time::Duration::from_secs(30);
759
760/// One entry per agent this srv handed over: until when, and to whom (for
761/// the refusal text). A single map, so an expired hold goes away whole
762/// (ReAgent P2 on #3742).
763static HANDOVER_HOLDS: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<String, (std::time::Instant, String)>>> =
764    std::sync::LazyLock::new(Default::default);
765
766/// Record that this srv just handed `uid` over (see [`HANDOVER_HOLD`]).
767pub fn hold_after_handover(uid: &str, to: &str) {
768    HANDOVER_HOLDS
769        .lock()
770        .unwrap_or_else(|e| e.into_inner())
771        .insert(uid.to_string(), (std::time::Instant::now() + HANDOVER_HOLD, to.to_string()));
772}
773
774/// The refusal for an agent whose shared record says it was handed to another computer (spec: move an agent): it names
775/// where it went and the way back. It is persistent, unlike [`hold_after_handover`]'s short hold, and it holds on every
776/// instance that shares the record.
777pub fn handed_over_refusal(agent: &str, mark: &crate::registry::Handover) -> String {
778    let agent = if agent.is_empty() { "This agent" } else { agent };
779    let to = if mark.to.is_empty() { "another computer".to_string() } else { mark.to.clone() };
780    if mark.state == crate::registry::Handover::MOVED {
781        format!("{agent} moved to {to} and lives there now. It does not start here. To start it here instead, Agents bring_back with force: true, which is safe only when it is not running on {to}.")
782    } else {
783        format!("{agent} is being moved to {to} and is stopped here until that finishes. To cancel the move and start it here, use Agents bring_back.")
784    }
785}
786
787/// The refusal to start agent `uid` while its shared definition record carries a hand-over mark, read fresh from the
788/// record so an edit by another instance on this host takes effect at once. `None`: no mark. Fails closed: a record that
789/// cannot be read refuses, since the agent cannot be shown not to be handed over. Every controller's start path asks it.
790pub fn handed_over_check(store: &crate::backend::storage::store::Store, uid: &str, agent: &str) -> Option<String> {
791    if uid.is_empty() {
792        return None;
793    }
794    match store.agent_handover_get(uid) {
795        Ok(mark) => Some(handed_over_refusal(agent, &mark?)),
796        Err(e) => {
797            tracing::warn!(agent, uid, error = %e, "agent_admission.denied: the hand-over mark could not be read");
798            Some(format!("{} does not start: it cannot be checked that it was not handed to another computer ({e}).", if agent.is_empty() { "This agent" } else { agent }))
799        }
800    }
801}
802/// Drop any handover hold on `uid` — the user is taking it back.
803pub fn clear_handover_hold(uid: &str) {
804    HANDOVER_HOLDS.lock().unwrap_or_else(|e| e.into_inner()).remove(uid);
805}
806
807/// `Some(refusal)` while `uid` is inside a handover hold on this srv. An
808/// expired hold is removed here.
809fn handover_hold_refusal(uid: &str, agent: &str) -> Option<String> {
810    let mut holds = HANDOVER_HOLDS.lock().unwrap_or_else(|e| e.into_inner());
811    let (until, to) = holds.get(uid)?.clone();
812    if until <= std::time::Instant::now() {
813        holds.remove(uid);
814        return None;
815    }
816    let agent = if agent.is_empty() { "This agent" } else { agent };
817    Some(format!(
818        "{agent} was taken over by another AgentMux instance on this host{}. \
819         Use Take over to bring it back here.",
820        if to.is_empty() { String::new() } else { format!(" ({to})") }
821    ))
822}
823
824/// The writer-side fence on the agent's shared record (spec §4.3, Phase 3).
825///
826/// Cheap in the common case: while the lease was confirmed ours within the
827/// TTL, nobody can have reclaimed it, so appends go ahead on in-memory state
828/// alone. After a longer gap — the holder was suspended, and its CLI and
829/// output reader resume together with the renewal task — the first append
830/// checks the lease file before writing, so output a reclaimed holder
831/// flushes on waking never reaches the record the new holder is writing.
832#[derive(Clone)]
833pub struct RecordFence {
834    store: Arc<LeaseStore>,
835    lease: Lease,
836    agent: String,
837    lost: Arc<LostReason>,
838    last_ok_ms: Arc<std::sync::atomic::AtomicI64>,
839}
840
841impl RecordFence {
842    /// May this process append to the agent's shared record now?
843    pub fn may_write(&self) -> bool {
844        if self.lost.get().is_some() {
845            return false;
846        }
847        let now = agentmux_common::time::now_ms();
848        let age = now - self.last_ok_ms.load(Ordering::SeqCst);
849        if age >= 0 && (age as u64) <= crate::registry::LEASE_TTL_MS {
850            return true;
851        }
852        match self.store.verify(&self.lease) {
853            Ok(()) => {
854                self.last_ok_ms.store(now, Ordering::SeqCst);
855                true
856            }
857            Err(LeaseError::HeldByOther { holder, .. }) => {
858                self.lost.set_first(lost_message(&self.agent, holder.as_ref(), self.lease.owner_boot_id()));
859                tracing::error!(
860                    agent = %self.agent,
861                    instance_id = %self.lease.instance_id(),
862                    "agent_admission.fenced: output from a process that lost its lease kept out of the shared record"
863                );
864                false
865            }
866            // An I/O hiccup is not a loss (same rule as `verify`).
867            Err(LeaseError::Io(_)) => true,
868        }
869    }
870}
871
872/// `zone` unless `fence` says this process may no longer write the agent's
873/// shared record.
874pub fn fenced_zone<'a>(zone: Option<&'a str>, fence: &Option<RecordFence>) -> Option<&'a str> {
875    match fence {
876        Some(f) if zone.is_some() && !f.may_write() => None,
877        _ => zone,
878    }
879}
880
881/// Where the instance currently running an agent can be reached.
882#[derive(Clone, PartialEq, Eq)]
883pub struct HolderEndpoint {
884    pub channel: String,
885    pub local_url: String,
886    /// Never logged.
887    pub auth_key: String,
888}
889
890impl std::fmt::Debug for HolderEndpoint {
891    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
892        f.debug_struct("HolderEndpoint")
893            .field("channel", &self.channel)
894            .field("local_url", &self.local_url)
895            .finish_non_exhaustive()
896    }
897}
898
899/// Find the other instance on this host that runs `uid`: the lease holder
900/// (its channel's live srv, from the shared registry) or — for an instance
901/// that takes no lease — the compat probe's hit. `None` when nobody else
902/// runs it, or the holder's srv can't be found.
903pub async fn locate_holder(store: Option<Arc<LeaseStore>>, uid: &str, own_boot_id: &str) -> Option<HolderEndpoint> {
904    if let Some(store) = store {
905        let (u, b) = (uid.to_string(), own_boot_id.to_string());
906        let holder = tokio::task::spawn_blocking(move || store.live_holder_other_than(&u, &b))
907            .await
908            .ok()
909            .and_then(|r| r.ok())
910            .flatten();
911        if let Some(holder) = holder.filter(|h| !h.channel.is_empty()) {
912            if let Some(endpoint) = endpoint_for_channel(&holder.channel).await {
913                return Some(endpoint);
914            }
915        }
916    }
917    probe_other_instances(uid).await.map(|l| HolderEndpoint {
918        channel: l.channel,
919        local_url: l.local_url,
920        auth_key: l.auth_key,
921    })
922}
923
924/// The running instance on this computer in `channel`, from the host-global
925/// shared registry — how Take over reaches a holder it knows by channel
926/// (from the local lease file, or from the relay's holder record).
927pub async fn endpoint_for_channel(channel: &str) -> Option<HolderEndpoint> {
928    let shared = crate::registry::resolve_shared_reactive_dir()?;
929    let channel = channel.to_string();
930    let entries = tokio::task::spawn_blocking(move || crate::backend::reactive::registry::list_all_shared(&shared))
931        .await
932        .ok()?;
933    entries
934        .into_iter()
935        .find(|e| e.channel == channel && !e.local_url.is_empty() && e.srv_alive())
936        .map(|e| HolderEndpoint { channel: e.channel, local_url: e.local_url, auth_key: e.auth_key })
937}
938
939/// How long a release request may take to be answered (see
940/// [`request_release`]): the holder's user has 30 s to keep the agent running
941/// before it lets go.
942const RELEASE_REQUEST_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
943
944/// Ask the holder's srv to stop running `uid` so this instance can take it
945/// (`POST /agentmux/agent/release`). `Err` is user-facing.
946pub async fn request_release(holder: &HolderEndpoint, uid: &str, agent: &str) -> Result<(), String> {
947    let me = claimant_info();
948    let mut req = PROBE_CLIENT
949        .post(format!("{}/agentmux/agent/release", holder.local_url))
950        // Not the probe's 1.5 s: the holder answers only after its user's override
951        // window ran out, then stopping its panes (up to its 10 s grace) and letting go of the relay lease (a
952        // token refresh plus a relay call with its own 10 s timeout) —
953        // ReAgent P1 on #3899.
954        .timeout(RELEASE_REQUEST_TIMEOUT)
955        .json(&serde_json::json!({
956            "uid": uid,
957            // Lets the holder drop a relay subscription that outlived the
958            // agent's panes (it knows the agent by name there). Older holders
959            // ignore it.
960            "agent": agent,
961            "requested_by_channel": me.channel,
962            "requested_by_version": me.version,
963        }));
964    if !holder.auth_key.is_empty() {
965        req = req.header(AUTH_KEY_HEADER, &holder.auth_key);
966    }
967    let agent = if agent.is_empty() { "this agent" } else { agent };
968    let resp = req.send().await.map_err(|e| {
969        format!("Could not reach the AgentMux instance running {agent} (channel {}): {e}", holder.channel)
970    })?;
971    match resp.status() {
972        s if s.is_success() => Ok(()),
973        reqwest::StatusCode::NOT_FOUND | reqwest::StatusCode::METHOD_NOT_ALLOWED => Err(format!(
974            "The AgentMux instance running {agent} (channel {}) is too old to hand it over: update it to AgentMux {} or newer, \
975             or close {agent} there, then try again.",
976            holder.channel,
977            crate::backend::remote_panes::host::own_version()
978        )),
979        s => {
980            let body = resp.text().await.unwrap_or_default();
981            Err(format!("The instance running {agent} refused to hand it over ({s}): {body}"))
982        }
983    }
984}
985
986/// Wait until no other instance holds `uid` (lease and compat probe both
987/// clear), polling. `Err` after `timeout`.
988pub async fn wait_until_free(
989    store: Option<Arc<LeaseStore>>,
990    uid: &str,
991    own_boot_id: &str,
992    timeout: std::time::Duration,
993) -> Result<(), String> {
994    let deadline = std::time::Instant::now() + timeout;
995    loop {
996        if locate_holder(store.clone(), uid, own_boot_id).await.is_none()
997            && check_before_spawn(store.clone(), uid, "", own_boot_id).await.is_ok()
998        {
999            return Ok(());
1000        }
1001        if std::time::Instant::now() >= deadline {
1002            return Err(format!(
1003                "The other instance did not let go within {}s. Try again in a moment.",
1004                timeout.as_secs()
1005            ));
1006        }
1007        tokio::time::sleep(std::time::Duration::from_millis(250)).await;
1008    }
1009}
1010
1011#[cfg(test)]
1012mod tests {
1013    use super::*;
1014
1015    fn store(ttl_ms: u64) -> (tempfile::TempDir, Arc<LeaseStore>) {
1016        let tmp = tempfile::tempdir().unwrap();
1017        let s = LeaseStore::open_with_ttl(tmp.path(), ttl_ms).unwrap();
1018        (tmp, Arc::new(s))
1019    }
1020
1021    fn boot(id: &str) -> Arc<str> {
1022        Arc::from(id)
1023    }
1024
1025    #[test]
1026    fn a_second_instance_is_refused_with_the_holder_named() {
1027        let (_tmp, s) = store(60_000);
1028        let _held = acquire(&s, "uid-1", "Agent3", &boot("boot-a"), "block-a", None, |_| {}).unwrap();
1029        let err = acquire(&s, "uid-1", "Agent3", &boot("boot-b"), "block-b", None, |_| {})
1030            .err()
1031            .expect("second instance must be refused");
1032        assert!(err.starts_with("Agent3 is already running in another AgentMux instance"), "{err}");
1033        assert!(err.contains(&format!("pid {}", std::process::id())), "{err}");
1034        assert!(err.contains(&format!("v{}", env!("CARGO_PKG_VERSION"))), "{err}");
1035    }
1036
1037    #[test]
1038    fn dropping_the_handle_releases_the_agent() {
1039        let (_tmp, s) = store(60_000);
1040        let held = acquire(&s, "uid-1", "Agent3", &boot("boot-a"), "block-a", None, |_| {}).unwrap();
1041        drop(held);
1042        assert!(acquire(&s, "uid-1", "Agent3", &boot("boot-b"), "block-b", None, |_| {}).is_ok());
1043    }
1044
1045    #[test]
1046    fn verify_refuses_the_next_turn_once_the_lease_is_taken_over() {
1047        let (_tmp, s) = store(50);
1048        let held = acquire(&s, "uid-1", "Agent3", &boot("boot-a"), "block-a", None, |_| {}).unwrap();
1049        assert!(held.verify().is_ok());
1050        // Holder "suspended" past the TTL; another instance takes over.
1051        std::thread::sleep(std::time::Duration::from_millis(1_000));
1052        let _new = acquire(&s, "uid-1", "Agent3", &boot("boot-b"), "block-b", None, |_| {}).unwrap();
1053        let err = held.verify().unwrap_err();
1054        assert!(err.contains("taken over"), "{err}");
1055        // And it stays refused, with the same detail, without re-reading
1056        // (ReAgent P2 on #3738: later refusals used to drop the holder).
1057        assert_eq!(held.verify().unwrap_err(), err);
1058        assert!(err.contains(&format!("pid {}", std::process::id())), "{err}");
1059    }
1060
1061    /// The old holder's drop must not release the new holder's lease.
1062    #[test]
1063    fn a_fenced_holder_dropping_does_not_free_the_new_holder() {
1064        let (_tmp, s) = store(50);
1065        let held = acquire(&s, "uid-1", "Agent3", &boot("boot-a"), "block-a", None, |_| {}).unwrap();
1066        std::thread::sleep(std::time::Duration::from_millis(1_000));
1067        let new = acquire(&s, "uid-1", "Agent3", &boot("boot-b"), "block-b", None, |_| {}).unwrap();
1068        drop(held);
1069        assert!(new.verify().is_ok());
1070    }
1071
1072    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
1073    async fn the_renewal_task_reports_a_takeover_through_on_lost() {
1074        let (tmp, s) = store(60_000);
1075        let (tx, rx) = std::sync::mpsc::channel::<String>();
1076        let tx = std::sync::Mutex::new(tx);
1077        let held = acquire(&s, "uid-1", "Agent3", &boot("boot-a"), "block-a", None, move |msg| {
1078            let _ = tx.lock().unwrap().send(msg);
1079        })
1080        .unwrap();
1081        // Simulate a takeover: another owner's lease file replaces ours.
1082        let other = LeaseStore::open_with_ttl(tmp.path(), 60_000).unwrap();
1083        let path = tmp.path().join("leases").join("uid-1.lease.json");
1084        std::fs::remove_file(&path).unwrap();
1085        other.claim("uid-1", &boot("boot-b"), "block-b", None).unwrap();
1086        let msg = tokio::task::spawn_blocking(move || {
1087            rx.recv_timeout(std::time::Duration::from_millis(crate::registry::RENEW_INTERVAL_MS * 3))
1088        })
1089        .await
1090        .unwrap()
1091        .expect("on_lost must fire within a couple of renew intervals");
1092        assert!(msg.contains("taken over"), "{msg}");
1093        assert!(held.verify().is_err());
1094    }
1095
1096    #[tokio::test]
1097    async fn the_early_check_refuses_while_another_instance_holds_the_lease() {
1098        let (_tmp, s) = store(60_000);
1099        let _held = acquire(&s, "uid-1", "Agent3", &boot("boot-a"), "block-a", None, |_| {}).unwrap();
1100        let err = check_before_spawn(Some(Arc::clone(&s)), "uid-1", "Agent3", "boot-b")
1101            .await
1102            .unwrap_err();
1103        assert!(err.contains("already running"), "{err}");
1104        // The holder itself passes.
1105        assert!(check_before_spawn(Some(s), "uid-1", "Agent3", "boot-a").await.is_ok());
1106    }
1107
1108    #[test]
1109    fn the_probe_matches_by_uid_never_by_name() {
1110        let regs = vec![
1111            serde_json::json!({"agent_id": "Agent3", "block_id": "b-other", "uid": "someone-else"}),
1112            serde_json::json!({"agent_id": "Agent3", "block_id": "b-legacy", "uid": null}),
1113            serde_json::json!({"agent_id": "Renamed", "block_id": "b-mine", "uid": "UID-1"}),
1114        ];
1115        assert_eq!(find_uid_block(&regs, "uid-1").as_deref(), Some("b-mine"));
1116        assert_eq!(find_uid_block(&regs[..2], "uid-1"), None, "a same-named agent with another or no UID is not a holder");
1117    }
1118
1119    /// Phase 3: the writer trusts in-memory state within the TTL…
1120    #[test]
1121    fn the_record_fence_passes_a_recently_confirmed_lease_without_io() {
1122        let (_tmp, s) = store(60_000);
1123        let held = acquire(&s, "uid-1", "Agent3", &boot("boot-a"), "block-a", None, |_| {}).unwrap();
1124        let fence = held.record_fence();
1125        assert!(fence.may_write());
1126        assert_eq!(fenced_zone(Some("agent:uid-1:current"), &Some(fence)), Some("agent:uid-1:current"));
1127        assert_eq!(fenced_zone(Some("z"), &None), Some("z"), "no lease, no fence");
1128    }
1129
1130    /// …and after a gap longer than the TTL (a suspended holder) it checks
1131    /// the lease file before writing: a reclaimed holder's output is kept
1132    /// out of the shared record.
1133    #[test]
1134    fn the_record_fence_keeps_a_reclaimed_holders_output_out_after_a_gap() {
1135        let (tmp, s) = store(60_000);
1136        let held = acquire(&s, "uid-1", "Agent3", &boot("boot-a"), "block-a", None, |_| {}).unwrap();
1137        let fence = held.record_fence();
1138        // Suspended past the TTL…
1139        held.last_ok_ms.store(agentmux_common::time::now_ms() - crate::registry::LEASE_TTL_MS as i64 - 1_000, Ordering::SeqCst);
1140        // …while another instance took the agent over.
1141        std::fs::remove_file(tmp.path().join("leases").join("uid-1.lease.json")).unwrap();
1142        let _new = acquire(&s, "uid-1", "Agent3", &boot("boot-b"), "block-b", None, |_| {}).unwrap();
1143        assert!(!fence.may_write());
1144        assert_eq!(fenced_zone(Some("agent:uid-1:current"), &Some(fence.clone())), None);
1145        assert!(held.verify().unwrap_err().contains("taken over"), "the loss is recorded for the pre-turn fence too");
1146    }
1147
1148    #[test]
1149    fn the_record_fence_confirms_and_resumes_when_the_lease_is_still_ours_after_a_gap() {
1150        let (_tmp, s) = store(60_000);
1151        let held = acquire(&s, "uid-1", "Agent3", &boot("boot-a"), "block-a", None, |_| {}).unwrap();
1152        let fence = held.record_fence();
1153        let stale = agentmux_common::time::now_ms() - crate::registry::LEASE_TTL_MS as i64 - 1_000;
1154        held.last_ok_ms.store(stale, Ordering::SeqCst);
1155        assert!(fence.may_write(), "nobody reclaimed it: still ours");
1156        assert!(held.last_ok_ms.load(Ordering::SeqCst) > stale, "confirmed again");
1157    }
1158
1159    /// Phase 4 (§4.4): exactly one of two hosts wins, whatever the order
1160    /// the check runs in, and near-simultaneous starts fall to the hostname.
1161    #[test]
1162    fn the_lan_tie_break_has_exactly_one_winner() {
1163        let cases = [
1164            (1_000_000, "alpha", 1_050_000, "beta"), // alpha 50 s earlier
1165            (1_050_000, "alpha", 1_000_000, "beta"), // beta 50 s earlier
1166            (1_000_000, "beta", 1_003_000, "alpha"), // within the skew budget
1167            (1_000_000, "alpha", 1_000_000, "beta"), // identical
1168        ];
1169        for (a_at, a_host, b_at, b_host) in cases {
1170            let a_wins = peer_wins(a_at, a_host, b_at, b_host); // b asks: does a win?
1171            let b_wins = peer_wins(b_at, b_host, a_at, a_host); // a asks: does b win?
1172            assert!(a_wins ^ b_wins, "exactly one winner for {a_host}@{a_at} vs {b_host}@{b_at}");
1173        }
1174        assert!(peer_wins(1_000_000, "alpha", 1_050_000, "beta"), "the earlier start wins");
1175        assert!(peer_wins(1_003_000, "alpha", 1_000_000, "beta"), "within the budget the lower hostname wins");
1176    }
1177
1178    #[test]
1179    fn a_lan_refusal_is_recognised_and_names_the_computer() {
1180        let peer = PeerHolding {
1181            held: true,
1182            hostname: "narko".into(),
1183            channel: "stable".into(),
1184            version: "0.58.0".into(),
1185            acquired_at_ms: 1,
1186        };
1187        let m = lan_denied_message("Agent3", &peer);
1188        assert!(m.contains("another computer on your network") && m.contains("computer narko"), "{m}");
1189        assert!(is_admission_refusal(&m));
1190        assert!(is_admission_refusal(&lan_lost_message("Agent3", &peer)));
1191        assert_eq!(
1192            crate::agents::failure::classify(None, None, &m, None).code,
1193            crate::agents::failure::FailureClass::LiveElsewhere
1194        );
1195    }
1196
1197    #[test]
1198    fn this_host_reports_holding_only_a_live_lease() {
1199        let (_tmp, s) = store(60_000);
1200        assert!(!local_holding(Some(&s), "uid-1").held);
1201        let held = acquire(&s, "uid-1", "Agent3", &boot("boot-a"), "block-a", None, |_| {}).unwrap();
1202        let h = local_holding(Some(&s), "uid-1");
1203        assert!(h.held);
1204        assert_eq!(h.version, env!("CARGO_PKG_VERSION"));
1205        assert!(h.acquired_at_ms > 0);
1206        drop(held);
1207        assert!(!local_holding(Some(&s), "uid-1").held);
1208        assert!(!local_holding(None, "uid-1").held, "no lease store, nothing held");
1209    }
1210
1211    /// A second AgentMux instance on this same host is also a LAN peer, and
1212    /// reports this host's leases — including this process's own. The LAN
1213    /// tier must not refuse on that.
1214    #[test]
1215    fn an_answer_from_this_host_is_not_a_lan_holder() {
1216        assert!(is_this_host(&this_host_label()));
1217        assert!(is_this_host(&this_host_label().to_uppercase()));
1218        assert!(!is_this_host("some-other-computer"));
1219    }
1220
1221    #[tokio::test]
1222    async fn without_lan_discovery_the_lan_tier_is_skipped() {
1223        // LAN_DISCOVERY is never set in unit tests.
1224        assert!(lan_holders("uid-1").await.is_empty());
1225    }
1226
1227    /// Phase 5: the WAN side fences the local holder by agent name, only its
1228    /// own entry, and only once.
1229    #[test]
1230    fn the_relay_can_fence_the_local_holder_by_agent_name() {
1231        let (_tmp, s) = store(60_000);
1232        let name = format!("Agent-{}", uuid::Uuid::new_v4());
1233        let (tx, rx) = std::sync::mpsc::channel::<String>();
1234        let tx = std::sync::Mutex::new(tx);
1235        let held = acquire(&s, "uid-w", &name, &boot("boot-a"), "block-a", None, move |m| {
1236            let _ = tx.lock().unwrap().send(m);
1237        })
1238        .unwrap();
1239        assert!(fence_agent_named(&name.to_lowercase(), "computer desk, channel stable"));
1240        let why = rx.try_recv().expect("on_lost ran");
1241        assert!(why.contains("taken over") && why.contains("computer desk"), "{why}");
1242        assert!(is_admission_refusal(&why));
1243        assert_eq!(held.verify().unwrap_err(), why, "the next turn is refused with the same reason");
1244        assert!(!fence_agent_named(&name, "again"), "fenced once");
1245        drop(held);
1246        assert!(!fence_agent_named(&name, "after release"), "no holder left to fence");
1247    }
1248
1249    #[test]
1250    fn a_wan_refusal_is_recognised() {
1251        let m = wan_denied_message("Agent3", "computer desk, channel stable, v0.58.0");
1252        assert!(is_admission_refusal(&m), "{m}");
1253        assert_eq!(
1254            crate::agents::failure::classify(None, None, &m, None).code,
1255            crate::agents::failure::FailureClass::LiveElsewhere
1256        );
1257    }
1258
1259    // ReAgent P1 on #3899: the holder now answers a release only after
1260    // letting go of its relay lease (a token refresh and a relay round
1261    // trip). The request used the 1.5 s probe client, so a slower relay
1262    // made a successful release read as "could not reach".
1263    #[tokio::test]
1264    async fn a_release_request_waits_for_a_holder_that_is_slower_than_a_probe() {
1265        let app = axum::Router::new().route(
1266            "/agentmux/agent/release",
1267            axum::routing::post(|| async {
1268                tokio::time::sleep(std::time::Duration::from_millis(2_000)).await;
1269                axum::Json(serde_json::json!({ "ok": true, "released": 1 }))
1270            }),
1271        );
1272        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1273        let addr = listener.local_addr().unwrap();
1274        tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
1275        let holder = HolderEndpoint {
1276            channel: "local-main-x".into(),
1277            local_url: format!("http://{addr}"),
1278            auth_key: String::new(),
1279        };
1280        assert_eq!(request_release(&holder, "uid-1", "Opaz").await, Ok(()));
1281    }
1282
1283    #[test]
1284    fn a_wan_refusal_from_this_computer_says_so() {
1285        let where_ = "this computer, channel local-main-x, v0.57.6";
1286        let m = wan_denied_message("Opaz", where_);
1287        assert!(m.contains("on this computer (channel local-main-x, v0.57.6)"), "{m}");
1288        assert!(!m.contains("another computer"), "{m}");
1289        assert!(is_admission_refusal(&m), "{m}");
1290        let lost = wan_lost_message("Opaz", where_);
1291        assert!(lost.contains("on this computer (channel local-main-x, v0.57.6)"), "{lost}");
1292        assert!(!lost.contains("another computer"), "{lost}");
1293        assert!(is_admission_refusal(&lost), "{lost}");
1294    }
1295
1296    #[test]
1297    fn every_refusal_text_is_recognised_as_one() {
1298        let holder = LeaseHolder {
1299            owner_boot_id: "b".into(), block_id: "x".into(), pid: 1, channel: "c".into(), version: "v".into(),
1300            hostname: String::new(), epoch: 1, acquired_at_ms: 0, renewed_at_ms: 0,
1301        };
1302        for m in [
1303            denied_message("Agent3", Some(&holder)),
1304            denied_message("", None),
1305            lost_message("Agent3", Some(&holder), "other-boot"),
1306            lost_message("Agent3", None, "other-boot"),
1307        ] {
1308            assert!(is_admission_refusal(&m), "not recognised: {m}");
1309        }
1310        assert!(!is_admission_refusal("failed to spawn persistent process: not found"));
1311    }
1312
1313    /// 2026-10-29: a second claim by the same process was reported as "another AgentMux instance
1314    /// ... pid <own pid>". The holder being this process, the text names the other pane instead, in the
1315    /// wording the pane refusal already has (so the failure card offers the same Move here).
1316    #[test]
1317    fn a_holder_in_this_process_is_another_pane_and_not_another_instance() {
1318        let holder = LeaseHolder {
1319            owner_boot_id: "this-boot".into(), block_id: "96a441d2".into(), pid: 1, channel: "c".into(), version: "v".into(),
1320            hostname: String::new(), epoch: 1, acquired_at_ms: 0, renewed_at_ms: 0,
1321        };
1322        let lost = lost_message("Agent3", Some(&holder), "this-boot");
1323        assert!(lost.contains("is already open in another pane (block 96a441d2)"), "{lost}");
1324        assert!(!lost.contains("another AgentMux instance"), "{lost}");
1325        assert!(crate::backend::blockcontroller::persistent::is_held_elsewhere_error(&lost), "{lost}");
1326        let elsewhere = lost_message("Agent3", Some(&holder), "other-boot");
1327        assert!(elsewhere.contains("taken over by another AgentMux instance"), "{elsewhere}");
1328        let no_block = LeaseHolder { block_id: String::new(), ..holder };
1329        assert!(lost_message("Agent3", Some(&no_block), "this-boot").contains("another AgentMux instance"));
1330    }
1331
1332    /// ReAgent P1 on #3742: a local lease-file I/O error is not "running in
1333    /// another instance" — it must keep a Retry, not get Take over.
1334    #[test]
1335    fn a_lease_file_io_error_is_not_classified_as_live_elsewhere() {
1336        let io = "Could not confirm that Agent3 isn't already running elsewhere (lease file error: access denied). \
1337                  Refusing to start it twice.";
1338        assert!(!is_admission_refusal(io));
1339        let f = crate::agents::failure::classify(None, None, io, None);
1340        assert_ne!(f.code, crate::agents::failure::FailureClass::LiveElsewhere);
1341    }
1342
1343    /// ReAgent P2 on #3742: an expired hold is removed whole.
1344    #[test]
1345    fn an_expired_handover_hold_is_removed() {
1346        let uid = format!("uid-{}", uuid::Uuid::new_v4());
1347        HANDOVER_HOLDS
1348            .lock()
1349            .unwrap()
1350            .insert(uid.clone(), (std::time::Instant::now() - std::time::Duration::from_secs(1), "to".into()));
1351        assert!(handover_hold_refusal(&uid, "Agent3").is_none());
1352        assert!(!HANDOVER_HOLDS.lock().unwrap().contains_key(&uid));
1353    }
1354
1355    #[test]
1356    fn a_handover_hold_refuses_this_srv_until_cleared() {
1357        let (_tmp, s) = store(60_000);
1358        let uid = format!("uid-{}", uuid::Uuid::new_v4());
1359        hold_after_handover(&uid, "channel other, v9");
1360        let err = acquire(&s, &uid, "Agent3", &boot("boot-a"), "block-a", None, |_| {})
1361            .err()
1362            .expect("a handed-over agent is not re-claimed on its own");
1363        assert!(err.contains("was taken over") && err.contains("channel other"), "{err}");
1364        assert!(is_admission_refusal(&err));
1365        clear_handover_hold(&uid);
1366        assert!(acquire(&s, &uid, "Agent3", &boot("boot-a"), "block-a", None, |_| {}).is_ok());
1367    }
1368
1369    #[test]
1370    fn holder_endpoint_debug_never_prints_the_auth_key() {
1371        let ep = HolderEndpoint { channel: "c".into(), local_url: "http://x".into(), auth_key: "sekrit".into() };
1372        assert!(!format!("{ep:?}").contains("sekrit"));
1373    }
1374
1375    #[test]
1376    fn denied_message_without_details_still_says_what_to_do() {
1377        let m = denied_message("", None);
1378        assert!(m.starts_with("This agent is already running"), "{m}");
1379        assert!(m.contains("Close it there"), "{m}");
1380    }
1381}