Skip to main content

lean_ctx/core/agents/
registry.rs

1use lean_ctx_time::UtcDateTime;
2use std::collections::HashSet;
3use std::path::Path;
4
5#[cfg(test)]
6use super::diary::{AgentDiary, DiaryEntryType};
7use super::persistence::{
8    FileLock, ProcessIdentityIndex, agents_dir, create_agents_dir, generate_short_id,
9    load_registry_file, mutate_persistent, save_registry_file,
10};
11use super::{
12    AgentEntry, AgentRegistry, AgentStatus, LogicalSessionPresence, REQUEST_DIGEST_METADATA_KEY,
13    REQUEST_ID_METADATA_KEY, RoleSource, ScratchpadEntry, TransportClient,
14};
15use crate::core::a2a::message::{MessagePriority, PrivacyLevel};
16
17/// Role an MCP transport holds until `initialize` resolves the session role.
18const PLACEHOLDER_ROLE: &str = "context-engine";
19const WORKER_LEASE_EXPIRED: &str = "worker lease expired; register again before continuing";
20/// A live MCP connection without a recent tool call is idle, not gone: the
21/// worker lease governs collaboration slots, never transport presence.
22const TRANSPORT_IDLE: &str = "connected; no tool call within the worker lease";
23
24/// Registration metadata beyond the legacy `register` arguments.
25#[derive(Default)]
26struct RegistrationMeta {
27    role_source: Option<RoleSource>,
28    transport: Option<TransportClient>,
29}
30
31/// Explicit callers (`ctx_agent register`) declare their role; only the
32/// transport placeholder is assumed.
33fn explicit_role_source(role: Option<&str>) -> Option<RoleSource> {
34    match role {
35        None => None,
36        Some(PLACEHOLDER_ROLE) => Some(RoleSource::Assumed),
37        Some(_) => Some(RoleSource::Declared),
38    }
39}
40
41/// Agents of this process whose expired registration a heartbeat renewed,
42/// not yet reported by `ctx_agent read`/`wait`.
43static RENEWED: std::sync::Mutex<std::collections::BTreeSet<String>> =
44    std::sync::Mutex::new(std::collections::BTreeSet::new());
45
46fn note_renewed(agent_id: &str) {
47    if let Ok(mut renewed) = RENEWED.lock() {
48        renewed.insert(agent_id.to_string());
49    }
50    crate::core::agents::friction::record_for(
51        crate::core::agents::friction::REGISTRATION_RENEWED,
52        Some(agent_id),
53        None,
54    );
55}
56
57/// Whether `agent_id`'s registration had expired and was renewed since the
58/// last call (each renewal is reported once).
59pub fn take_renewed(agent_id: &str) -> bool {
60    RENEWED
61        .lock()
62        .is_ok_and(|mut renewed| renewed.remove(agent_id))
63}
64
65/// How often `wait` looks at the registry file's modification time.
66const WAIT_POLL: std::time::Duration = std::time::Duration::from_millis(500);
67/// How often `wait` keeps the waiting agent's lease alive.
68const WAIT_KEEPALIVE: std::time::Duration = std::time::Duration::from_secs(30);
69/// A registry whose modification time is this recent may be replaced again
70/// within the same timestamp tick (coarse kernel clocks, 1–2 s on HFS+/FAT),
71/// so an unchanged mtime does not yet prove an unchanged file.
72const WAIT_RACY_MTIME: std::time::Duration = std::time::Duration::from_secs(3);
73
74/// How far before its registration an agent still receives broadcasts: the
75/// seconds a reconnect leaves between the old session's last read and the new
76/// one, with room to spare.
77const BROADCAST_GRACE: lean_ctx_time::Duration = lean_ctx_time::Duration::minutes(10);
78
79/// A message `agent_id` has not read: addressed to it, or a broadcast posted
80/// after `floor` (the agent's registration less [`BROADCAST_GRACE`]), not its
81/// own, in `project_root` (any when `None`), not expired. Without the floor a
82/// reconnected session (a new id) got hours of old broadcasts as unread
83/// (25.10.: 123 after the MCP reconnect).
84fn unread_for(
85    e: &ScratchpadEntry,
86    agent_id: &str,
87    project_root: Option<&str>,
88    now: lean_ctx_time::UtcDateTime,
89    floor: Option<lean_ctx_time::UtcDateTime>,
90) -> bool {
91    !e.read_by.iter().any(|reader| reader == agent_id)
92        && e.from_agent != agent_id
93        && (e.to_agent.as_deref() == Some(agent_id)
94            || (e.to_agent.is_none() && floor.is_none_or(|floor| e.timestamp >= floor)))
95        && project_root.is_none_or(|root| {
96            e.project_root
97                .as_deref()
98                .is_some_and(|own| crate::core::pathutil::same_project(own, root))
99        })
100        && e.expires_at.is_none_or(|exp| exp > now)
101}
102
103/// True when `agent` is owned by this exact process (PID and start marker).
104fn owned_by_current_process(agent: &AgentEntry) -> bool {
105    let pid = std::process::id();
106    agent.pid == pid
107        && agent.process_identity.is_some()
108        && crate::ipc::process::identity(pid).as_ref() == agent.process_identity.as_ref()
109}
110
111const LOGICAL_SESSION_SOURCE_MAX_BYTES: usize = 64;
112const LOGICAL_SESSION_WORKSPACE_MAX_BYTES: usize = 4096;
113const LOGICAL_SESSION_ID_MAX_BYTES: usize = 256;
114const MAX_RETAINED_FINISHED_AGENTS: usize = 32;
115/// Active collaboration slots are leases, not process guesses: MCP workers can
116/// share the daemon PID, so process identity alone cannot distinguish sessions.
117/// Workers renew via `read` or `status=active`; expiry releases abandoned slots.
118const DEFAULT_ACTIVE_WORKER_LEASE_SECONDS: i64 = 120;
119
120fn active_worker_lease_seconds() -> i64 {
121    let configured = crate::core::config::Config::load()
122        .agents
123        .active_worker_lease_seconds;
124    i64::try_from(configured)
125        .unwrap_or(DEFAULT_ACTIVE_WORKER_LEASE_SECONDS)
126        .max(1)
127}
128
129fn presence_ttl() -> u64 {
130    crate::core::config::Config::load()
131        .agents
132        .presence_ttl_hours
133}
134
135fn max_scratchpad() -> usize {
136    crate::core::config::Config::load()
137        .agents
138        .max_scratchpad_entries
139}
140
141pub(crate) fn process_identity_matches(
142    agent: &AgentEntry,
143    compatibility_identities: &ProcessIdentityIndex,
144) -> bool {
145    agent
146        .process_identity
147        .as_ref()
148        .or_else(|| compatibility_identities.get(&agent.agent_id))
149        .is_some_and(|identity| crate::ipc::process::matches_identity(agent.pid, identity))
150}
151
152fn safe_legacy_identity(agent: &AgentEntry) -> Option<crate::ipc::process::ProcessIdentity> {
153    if agent.process_identity.is_some() {
154        return None;
155    }
156    let identity = crate::ipc::process::identity(agent.pid)?;
157    legacy_identity_matches_registration(agent, &identity).then_some(identity)
158}
159
160fn legacy_identity_matches_registration(
161    agent: &AgentEntry,
162    identity: &crate::ipc::process::ProcessIdentity,
163) -> bool {
164    if Path::new(&identity.executable)
165        .file_name()
166        .and_then(|name| name.to_str())
167        != Some("lean-ctx")
168    {
169        return false;
170    }
171    let started_at = agent.started_at.timestamp_micros();
172    let Ok(process_started_at) = i64::try_from(identity.start_marker) else {
173        return false;
174    };
175    const REGISTRATION_GRACE_MICROS: i64 = 5 * 60 * 1_000_000;
176    process_started_at <= started_at
177        && started_at.saturating_sub(process_started_at) <= REGISTRATION_GRACE_MICROS
178}
179
180fn is_recoverable_legacy_finished(agent: &AgentEntry) -> bool {
181    agent.process_identity.is_none()
182        && agent.status == AgentStatus::Finished
183        && agent.status_message.as_deref() == Some("process identity no longer matches")
184}
185
186impl AgentRegistry {
187    pub fn new() -> Self {
188        Self {
189            agents: Vec::new(),
190            scratchpad: Vec::new(),
191            logical_sessions: Vec::new(),
192            logical_session_telemetry_seen: false,
193            updated_at: UtcDateTime::now(),
194        }
195    }
196
197    pub fn register(
198        &mut self,
199        agent_type: &str,
200        role: Option<&str>,
201        project_root: &str,
202        durable_identity_id: Option<&str>,
203    ) -> Result<String, String> {
204        self.register_process(
205            agent_type,
206            role,
207            project_root,
208            durable_identity_id,
209            std::process::id(),
210        )
211    }
212
213    fn register_process(
214        &mut self,
215        agent_type: &str,
216        role: Option<&str>,
217        project_root: &str,
218        durable_identity_id: Option<&str>,
219        pid: u32,
220    ) -> Result<String, String> {
221        self.register_process_with(
222            agent_type,
223            role,
224            project_root,
225            durable_identity_id,
226            pid,
227            RegistrationMeta {
228                role_source: explicit_role_source(role),
229                transport: None,
230            },
231        )
232    }
233
234    /// Registers (or refreshes) `role` as its own presence next to
235    /// `parent_id`, which this process holds: a subagent shares its parent's
236    /// MCP connection, and under the parent's id its reads consumed the
237    /// messages directed to the parent (WEB-2 read the lead's, 25.10.).
238    pub fn register_child(
239        &mut self,
240        agent_type: &str,
241        role: &str,
242        project_root: &str,
243        parent_id: &str,
244    ) -> Result<String, String> {
245        let pid = std::process::id();
246        let identity = crate::ipc::process::identity(pid)
247            .ok_or_else(|| format!("cannot establish immutable process identity for PID {pid}"))?;
248        if !self.held_by_this_process(parent_id) {
249            return Err(format!(
250                "agent {parent_id} is not registered by this process"
251            ));
252        }
253        let now = UtcDateTime::now();
254        if let Some(child) = self.agents.iter_mut().find(|a| {
255            a.parent.as_deref() == Some(parent_id)
256                && a.role.as_deref() == Some(role)
257                && a.status != AgentStatus::Finished
258        }) {
259            child.last_active = now;
260            child.status = AgentStatus::Active;
261            child.project_root = project_root.to_string();
262            return Ok(child.agent_id.clone());
263        }
264        let agent_id = format!("{}-{}-{}", agent_type, pid, generate_short_id());
265        self.agents.push(AgentEntry {
266            agent_id: agent_id.clone(),
267            agent_type: agent_type.to_string(),
268            role: Some(role.to_string()),
269            project_root: project_root.to_string(),
270            started_at: now,
271            last_active: now,
272            pid,
273            process_identity: Some(identity),
274            durable_identity_id: None,
275            status: AgentStatus::Active,
276            status_message: None,
277            agent_status_message: None,
278            transport: None,
279            role_source: Some(RoleSource::Declared),
280            parent: Some(parent_id.to_string()),
281            app_session_id: crate::core::activity::session_id_from_env(),
282            display_name: crate::core::activity::session_name_from_env(),
283        });
284        self.updated_at = now;
285        crate::core::events::emit_agent_action(&agent_id, "register", None);
286        Ok(agent_id)
287    }
288
289    /// The oldest broadcast `agent_id` still receives: its registration less
290    /// [`BROADCAST_GRACE`]; `None` (all) for an id the registry doesn't know.
291    fn broadcast_floor(&self, agent_id: &str) -> Option<lean_ctx_time::UtcDateTime> {
292        self.agents
293            .iter()
294            .find(|a| a.agent_id == agent_id)
295            .map(|a| a.started_at - BROADCAST_GRACE)
296    }
297
298    /// Whether `agent_id` is a live presence this very process registered
299    /// (its own or a child): only those may be named as `agent_id` on a call.
300    pub fn held_by_this_process(&self, agent_id: &str) -> bool {
301        let pid = std::process::id();
302        let identity = crate::ipc::process::identity(pid);
303        self.agents.iter().any(|a| {
304            a.agent_id == agent_id
305                && a.pid == pid
306                && a.status != AgentStatus::Finished
307                && a.process_identity.is_some()
308                && a.process_identity == identity
309        })
310    }
311
312    /// Set the display name of `agent_id` (a re-register takes over the new
313    /// one); `false` when no such agent is known.
314    pub fn set_display_name(&mut self, agent_id: &str, name: &str) -> bool {
315        match self.agents.iter_mut().find(|a| a.agent_id == agent_id) {
316            Some(agent) => {
317                agent.display_name = Some(name.to_owned());
318                true
319            }
320            None => false,
321        }
322    }
323
324    /// The declared role of `agent_id`, if it has one.
325    pub fn declared_role(&self, agent_id: &str) -> Option<String> {
326        self.agents
327            .iter()
328            .find(|a| a.agent_id == agent_id && a.role_source == Some(RoleSource::Declared))
329            .and_then(|a| a.role.clone())
330    }
331
332    /// Registers (or refreshes) the presence of this process's own MCP
333    /// connection, attributed to its host and with the role's provenance.
334    pub fn register_transport(
335        &mut self,
336        role: &str,
337        role_source: RoleSource,
338        project_root: &str,
339        durable_identity_id: Option<&str>,
340        transport: TransportClient,
341    ) -> Result<String, String> {
342        self.register_process_with(
343            "mcp",
344            Some(role),
345            project_root,
346            durable_identity_id,
347            std::process::id(),
348            RegistrationMeta {
349                role_source: Some(role_source),
350                transport: Some(transport),
351            },
352        )
353    }
354
355    fn register_process_with(
356        &mut self,
357        agent_type: &str,
358        role: Option<&str>,
359        project_root: &str,
360        durable_identity_id: Option<&str>,
361        pid: u32,
362        meta: RegistrationMeta,
363    ) -> Result<String, String> {
364        if let Some(identity_id) = durable_identity_id {
365            crate::core::agent_registry::require_active(identity_id)?;
366        }
367        let identity = crate::ipc::process::identity(pid)
368            .ok_or_else(|| format!("cannot establish immutable process identity for PID {pid}"))?;
369        let agent_id = format!("{}-{}-{}", agent_type, pid, generate_short_id());
370
371        if let Some(existing_index) = self.agents.iter().position(|a| {
372            a.pid == pid
373                && a.parent.is_none()
374                && a.status != AgentStatus::Finished
375                && a.process_identity.as_ref() == Some(&identity)
376        }) {
377            let existing_binding = self.agents[existing_index].durable_identity_id.clone();
378            if let (Some(existing_id), Some(requested_id)) =
379                (existing_binding.as_deref(), durable_identity_id)
380                && existing_id != requested_id
381            {
382                return Err(format!(
383                    "agent presence '{}' is already bound to durable identity '{}'; refusing rebind to '{}'",
384                    self.agents[existing_index].agent_id, existing_id, requested_id
385                ));
386            }
387            if existing_binding.is_some() {
388                self.require_active_for_presence(
389                    &self.agents[existing_index].agent_id,
390                    "registration",
391                )?;
392            }
393            let existing = &mut self.agents[existing_index];
394            existing.last_active = UtcDateTime::now();
395            existing.status = AgentStatus::Active;
396            if existing.status_message.as_deref() == Some(TRANSPORT_IDLE) {
397                existing.status_message = None;
398            }
399            // A transport refresh keeps the type an agent declared through
400            // `ctx_agent register` on the same process.
401            if meta.transport.is_none() || existing.agent_type == "mcp" {
402                existing.agent_type = agent_type.to_string();
403            }
404            existing.project_root = project_root.to_string();
405            // #1766: the presence retry registers as the `context-engine`
406            // placeholder. It never replaces a role the process already holds
407            // (a `reviewer` silently became a context engine); an explicit role
408            // still replaces the placeholder — the `initialize` upgrade. An
409            // assumed role (heuristic/default) never replaces a declared one.
410            match role {
411                Some(PLACEHOLDER_ROLE) if existing.role.is_some() => {}
412                Some(_)
413                    if meta.role_source == Some(RoleSource::Assumed)
414                        && existing.role_source == Some(RoleSource::Declared) => {}
415                Some(r) => {
416                    existing.role = Some(r.to_string());
417                    existing.role_source = meta.role_source;
418                }
419                None => {}
420            }
421            // Never downgrade a host the handshake identified to `unknown`.
422            if let Some(transport) = meta.transport
423                && (transport.is_identified() || existing.transport.is_none())
424            {
425                existing.transport = Some(transport);
426            }
427            if existing.durable_identity_id.is_none() {
428                existing.durable_identity_id = durable_identity_id.map(str::to_string);
429            }
430            if existing.app_session_id.is_none() {
431                existing.app_session_id = crate::core::activity::session_id_from_env();
432            }
433            if let Some(name) = crate::core::activity::session_name_from_env() {
434                existing.display_name = Some(name);
435            }
436            return Ok(self.adopt_app_session_identity(existing_index));
437        }
438
439        // A legacy record or a PID-reused record can share this numeric PID.
440        // Retire it before admitting the new owner; a bare PID is never enough
441        // to keep a presence alive.
442        for existing in self
443            .agents
444            .iter_mut()
445            .filter(|agent| agent.pid == pid && agent.status != AgentStatus::Finished)
446        {
447            existing.status = AgentStatus::Finished;
448            existing.status_message =
449                Some("superseded by a different process identity".to_string());
450        }
451
452        // Registration is identity/presence bookkeeping, not resource admission.
453        // Any number of agents may join the bus; scarce work (builds, tests and
454        // process resources) is bounded where it is actually consumed.
455
456        self.agents.push(AgentEntry {
457            agent_id: agent_id.clone(),
458            agent_type: agent_type.to_string(),
459            role: role.map(std::string::ToString::to_string),
460            project_root: project_root.to_string(),
461            started_at: UtcDateTime::now(),
462            last_active: UtcDateTime::now(),
463            pid,
464            process_identity: Some(identity),
465            durable_identity_id: durable_identity_id.map(str::to_string),
466            status: AgentStatus::Active,
467            status_message: None,
468            agent_status_message: None,
469            transport: meta.transport,
470            role_source: meta.role_source,
471            parent: None,
472            app_session_id: crate::core::activity::session_id_from_env(),
473            display_name: crate::core::activity::session_name_from_env(),
474        });
475        let agent_id = self.adopt_app_session_identity(self.agents.len() - 1);
476
477        self.updated_at = UtcDateTime::now();
478        crate::core::events::emit_agent_action(&agent_id, "register", None);
479        Ok(agent_id)
480    }
481
482    /// One app session keeps one bus identity per role across MCP restarts:
483    /// when the presence at `index` (this process, top level) holds a role
484    /// under an app session id, and an earlier presence of the same app
485    /// session held that role in a process that is gone (or finished), the
486    /// presence at `index` takes over that id (and its start), so messages
487    /// and leases addressed to it keep reaching the session. A presence of
488    /// another live process, a child presence, or one bound to another
489    /// durable identity is never taken. Returns the id the presence holds.
490    fn adopt_app_session_identity(&mut self, index: usize) -> String {
491        let current = &self.agents[index];
492        let (Some(app), Some(role)) = (current.app_session_id.clone(), current.role.clone()) else {
493            return current.agent_id.clone();
494        };
495        if role == PLACEHOLDER_ROLE || current.parent.is_some() {
496            return current.agent_id.clone();
497        }
498        let binding = current.durable_identity_id.clone();
499        let earlier = self.agents.iter().enumerate().position(|(i, a)| {
500            i != index
501                && a.parent.is_none()
502                && a.app_session_id.as_deref() == Some(app.as_str())
503                && a.role.as_deref() == Some(role.as_str())
504                && (a.durable_identity_id.is_none() || a.durable_identity_id == binding)
505                && (a.status == AgentStatus::Finished
506                    || a.process_identity.as_ref().is_some_and(|identity| {
507                        !crate::ipc::process::matches_identity(a.pid, identity)
508                    }))
509        });
510        let Some(earlier) = earlier else {
511            return self.agents[index].agent_id.clone();
512        };
513        let old = self.agents.remove(earlier);
514        let index = if earlier < index { index - 1 } else { index };
515        let current = &mut self.agents[index];
516        current.agent_id = old.agent_id;
517        current.started_at = old.started_at;
518        if current.durable_identity_id.is_none() {
519            current.durable_identity_id = old.durable_identity_id;
520        }
521        current.agent_id.clone()
522    }
523
524    /// Atomically registers this MCP process in the shared on-disk registry.
525    pub fn register_mcp_process(
526        project_root: &str,
527        durable_identity_id: Option<&str>,
528    ) -> Result<String, String> {
529        Self::register_mcp_process_as(
530            project_root,
531            PLACEHOLDER_ROLE,
532            RoleSource::Assumed,
533            durable_identity_id,
534        )
535    }
536
537    /// Registers this MCP process with the role the session resolved at
538    /// `initialize` (#1766), so the presence retry does not fall back to the
539    /// `context-engine` placeholder. The host comes from this process's
540    /// recorded MCP handshake.
541    pub fn register_mcp_process_as(
542        project_root: &str,
543        role: &str,
544        role_source: RoleSource,
545        durable_identity_id: Option<&str>,
546    ) -> Result<String, String> {
547        let transport = TransportClient::current();
548        mutate_persistent(|registry| {
549            registry.cleanup_stale(presence_ttl());
550            registry.register_transport(
551                role,
552                role_source,
553                project_root,
554                durable_identity_id,
555                transport,
556            )
557        })
558        .and_then(|result| result)
559    }
560
561    /// Attributes this process's live transport presences to the host from
562    /// its MCP handshake. Covers sessions whose `initialize` registers no
563    /// project-scoped presence (no resolvable root).
564    pub fn record_transport_client_persistent(
565        transport: &TransportClient,
566    ) -> Result<usize, String> {
567        mutate_persistent(|registry| registry.record_transport_client(transport))
568    }
569
570    pub(crate) fn record_transport_client(&mut self, transport: &TransportClient) -> usize {
571        let mut updated = 0;
572        for agent in self.agents.iter_mut().filter(|agent| {
573            agent.transport.is_some()
574                && agent.status != AgentStatus::Finished
575                && owned_by_current_process(agent)
576        }) {
577            agent.transport = Some(transport.clone());
578            updated += 1;
579        }
580        if updated > 0 {
581            self.updated_at = UtcDateTime::now();
582        }
583        updated
584    }
585
586    /// Whether `agent_id` is still a listed presence owned by this process.
587    /// Read-only: used by the MCP server to notice a presence that another
588    /// process retired (for example an older binary's lease expiry) or pruned.
589    pub fn transport_presence_is_live(agent_id: &str) -> bool {
590        Self::load().is_some_and(|registry| {
591            registry.agents.iter().any(|agent| {
592                agent.agent_id == agent_id
593                    && agent.status != AgentStatus::Finished
594                    && owned_by_current_process(agent)
595            })
596        })
597    }
598
599    /// Whether any LeanCTX MCP server runs on this machine: a transport
600    /// presence that is not finished and whose recorded process is still the
601    /// one that registered it. Every MCP connection registers one, the stdio
602    /// server a host starts as well as the daemon's sessions. Read-only; the
603    /// deny hook uses it to tell "no daemon" from "no MCP server at all".
604    pub fn any_live_mcp_transport() -> bool {
605        let Some(registry) = Self::load() else {
606            return false;
607        };
608        let identities = ProcessIdentityIndex::load();
609        registry.agents.iter().any(|agent| {
610            agent.transport.is_some()
611                && agent.status != AgentStatus::Finished
612                && process_identity_matches(agent, &identities)
613        })
614    }
615
616    /// Atomically refreshes a registered MCP process heartbeat. The caller is
617    /// the transport itself, so a presence that only lost its worker lease is
618    /// revived rather than rejected (an older binary in another process still
619    /// finishes quiet transports).
620    pub fn heartbeat_persistent(agent_id: &str) -> Result<(), String> {
621        mutate_persistent(|registry| registry.update_transport_heartbeat(agent_id))?
622    }
623
624    pub(crate) fn update_transport_heartbeat(&mut self, agent_id: &str) -> Result<(), String> {
625        if self.revive_lease_expired(agent_id) {
626            note_renewed(agent_id);
627        }
628        self.update_heartbeat(agent_id)
629    }
630
631    /// Revive `agent_id` when only its worker lease ran out: an unbound
632    /// presence of this very process that `cleanup_stale` finished for
633    /// being quiet. `true` when it was revived.
634    fn revive_lease_expired(&mut self, agent_id: &str) -> bool {
635        let Some(agent) = self
636            .agents
637            .iter_mut()
638            .find(|agent| agent.agent_id == agent_id)
639        else {
640            return false;
641        };
642        if agent.status == AgentStatus::Finished
643            && agent.status_message.as_deref() == Some(WORKER_LEASE_EXPIRED)
644            && agent.durable_identity_id.is_none()
645            && owned_by_current_process(agent)
646        {
647            agent.status = AgentStatus::Active;
648            agent.status_message = None;
649            return true;
650        }
651        false
652    }
653
654    /// The heartbeat of an agent this process registered (`ctx_agent
655    /// register`), sent on every tool call of its session: renews its worker
656    /// lease, and revives it when the lease had already run out. `Ok(true)`
657    /// when it was revived; [`take_renewed`] then says so once.
658    pub fn renew_worker(&mut self, agent_id: &str) -> Result<bool, String> {
659        let revived = self.revive_lease_expired(agent_id);
660        self.update_heartbeat(agent_id)?;
661        if revived {
662            note_renewed(agent_id);
663            request_announce();
664        }
665        Ok(revived)
666    }
667
668    /// [`Self::renew_worker`] under the registry lock.
669    pub fn renew_worker_persistent(agent_id: &str) -> Result<bool, String> {
670        mutate_persistent(|registry| registry.renew_worker(agent_id))?
671    }
672
673    /// Atomically marks a registered MCP process as finished.
674    pub fn finish_persistent(agent_id: &str) -> Result<(), String> {
675        mutate_persistent(|registry| {
676            registry.set_status(agent_id, AgentStatus::Finished, Some("connection closed"))
677        })?
678    }
679
680    pub fn update_heartbeat(&mut self, agent_id: &str) -> Result<(), String> {
681        let index = self
682            .agents
683            .iter()
684            .position(|agent| agent.agent_id == agent_id)
685            .ok_or_else(|| format!("agent presence '{agent_id}' was not found"))?;
686        if self.agents[index].status == AgentStatus::Finished {
687            return Err(format!(
688                "agent presence '{agent_id}' is finished; register a new process presence"
689            ));
690        }
691        self.require_active_for_presence(agent_id, "heartbeat")?;
692        let agent = &mut self.agents[index];
693        let pid = std::process::id();
694        if agent.pid != pid {
695            return Err(format!(
696                "agent presence '{agent_id}' belongs to PID {}; heartbeat came from PID {pid}",
697                agent.pid
698            ));
699        }
700        let identity = crate::ipc::process::identity(pid)
701            .ok_or_else(|| format!("cannot establish immutable process identity for PID {pid}"))?;
702        if let Some(expected) = &agent.process_identity
703            && expected != &identity
704        {
705            return Err(format!(
706                "agent presence '{agent_id}' process identity no longer matches"
707            ));
708        }
709        // Upgrade legacy records only from their owning process. This avoids a
710        // migration gap while still rejecting a PID reused by unrelated work.
711        agent.process_identity = Some(identity);
712        agent.status = AgentStatus::Active;
713        if agent.status_message.as_deref() == Some(TRANSPORT_IDLE) {
714            agent.status_message = None;
715        }
716        agent.last_active = UtcDateTime::now();
717        Ok(())
718    }
719
720    pub fn set_status(
721        &mut self,
722        agent_id: &str,
723        status: AgentStatus,
724        message: Option<&str>,
725    ) -> Result<(), String> {
726        let index = self
727            .agents
728            .iter()
729            .position(|agent| agent.agent_id == agent_id)
730            .ok_or_else(|| format!("agent presence '{agent_id}' was not found"))?;
731        // Finished is the safe cleanup path: reapers and shutdown must be
732        // able to release a presence after its durable identity is revoked.
733        if status != AgentStatus::Finished {
734            self.require_active_for_presence(agent_id, "status transition")?;
735        }
736        let agent = &mut self.agents[index];
737        agent.status = status;
738        agent.status_message = message.map(std::string::ToString::to_string);
739        agent.last_active = UtcDateTime::now();
740        self.updated_at = UtcDateTime::now();
741        Ok(())
742    }
743
744    /// [`Self::set_status`] for a status line the agent writes itself
745    /// (`ctx_agent action=status`): it is also kept as the agent's own
746    /// line, so readers that share it (team presence) can leave out
747    /// LeanCTX's lifecycle notes, which go through [`Self::set_status`] or
748    /// straight to `status_message` and never touch the agent's own line.
749    pub fn set_status_by_agent(
750        &mut self,
751        agent_id: &str,
752        status: AgentStatus,
753        message: Option<&str>,
754    ) -> Result<(), String> {
755        self.set_status(agent_id, status, message)?;
756        if let Some(agent) = self.agents.iter_mut().find(|a| a.agent_id == agent_id) {
757            agent.agent_status_message = message.map(std::string::ToString::to_string);
758        }
759        Ok(())
760    }
761    /// Records explicit logical-session presence supplied by an owning editor
762    /// integration. Tool activity is deliberately never treated as a session.
763    pub(crate) fn open_or_heartbeat_logical_session(
764        &mut self,
765        source: &str,
766        workspace: &str,
767        session_id: &str,
768    ) {
769        let now = UtcDateTime::now();
770        self.logical_session_telemetry_seen = true;
771        if let Some(session) = self.logical_sessions.iter_mut().find(|session| {
772            session.source == source
773                && session.workspace == workspace
774                && session.session_id == session_id
775        }) {
776            session.last_heartbeat = now;
777        } else {
778            self.logical_sessions.push(LogicalSessionPresence {
779                source: source.to_string(),
780                workspace: workspace.to_string(),
781                session_id: session_id.to_string(),
782                opened_at: now,
783                last_heartbeat: now,
784            });
785        }
786        self.updated_at = now;
787    }
788
789    pub(crate) fn close_logical_session(
790        &mut self,
791        source: &str,
792        workspace: &str,
793        session_id: &str,
794    ) -> bool {
795        self.logical_session_telemetry_seen = true;
796        let previous_len = self.logical_sessions.len();
797        self.logical_sessions.retain(|session| {
798            session.source != source
799                || session.workspace != workspace
800                || session.session_id != session_id
801        });
802        let removed = self.logical_sessions.len() != previous_len;
803        self.updated_at = UtcDateTime::now();
804        removed
805    }
806
807    pub fn cleanup_stale_logical_sessions(&mut self, max_age_seconds: u64) {
808        let seconds = i64::try_from(max_age_seconds).unwrap_or(i64::MAX);
809        let cutoff = UtcDateTime::now() - lean_ctx_time::Duration::seconds(seconds);
810        self.logical_sessions
811            .retain(|session| session.last_heartbeat >= cutoff);
812        self.updated_at = UtcDateTime::now();
813    }
814
815    pub fn record_logical_session_presence(
816        event: &str,
817        source: &str,
818        workspace: &str,
819        session_id: &str,
820    ) -> Result<(), String> {
821        let valid_field = |value: &str, max_bytes: usize| {
822            !value.is_empty() && value.len() <= max_bytes && !value.chars().any(char::is_control)
823        };
824        if !valid_field(source, LOGICAL_SESSION_SOURCE_MAX_BYTES)
825            || !valid_field(workspace, LOGICAL_SESSION_WORKSPACE_MAX_BYTES)
826            || !valid_field(session_id, LOGICAL_SESSION_ID_MAX_BYTES)
827        {
828            return Err(
829                "presence fields are empty, too long, or contain control characters".to_string(),
830            );
831        }
832        if !matches!(event, "open" | "heartbeat" | "close") {
833            return Err("event must be open, heartbeat, or close".to_string());
834        }
835
836        let ttl = crate::core::config::Config::load()
837            .agents
838            .logical_session_ttl_seconds;
839        mutate_persistent(|registry| {
840            registry.cleanup_stale_logical_sessions(ttl);
841            match event {
842                "open" | "heartbeat" => {
843                    registry.open_or_heartbeat_logical_session(source, workspace, session_id);
844                }
845                "close" => {
846                    registry.close_logical_session(source, workspace, session_id);
847                }
848                _ => unreachable!("event validated above"),
849            }
850        })
851    }
852
853    /// Gate operations for an explicitly bound presence. Legacy unbound
854    /// entries retain their prior behavior until a migration enables a
855    /// mandatory-binding mode.
856    pub fn require_active_for_presence(
857        &self,
858        agent_id: &str,
859        operation: &str,
860    ) -> Result<(), String> {
861        let Some(agent) = self.agents.iter().find(|agent| agent.agent_id == agent_id) else {
862            return Ok(());
863        };
864        let Some(durable_id) = agent.durable_identity_id.as_deref() else {
865            return Ok(());
866        };
867        if agent.status == AgentStatus::Finished {
868            return Err(format!(
869                "agent presence '{agent_id}' is finished; cannot {operation}"
870            ));
871        }
872        crate::core::agent_registry::require_active(durable_id).map_err(|error| {
873            format!("agent presence '{agent_id}' is not authorized for {operation}: {error}")
874        })
875    }
876
877    pub fn list_active(&self, project_root: Option<&str>) -> Vec<&AgentEntry> {
878        let compatibility_identities = ProcessIdentityIndex::load();
879        self.agents
880            .iter()
881            .filter(|a| {
882                if let Some(root) = project_root {
883                    crate::core::pathutil::same_project(&a.project_root, root)
884                        && a.status != AgentStatus::Finished
885                        && process_identity_matches(a, &compatibility_identities)
886                        && self
887                            .require_active_for_presence(&a.agent_id, "listing")
888                            .is_ok()
889                } else {
890                    a.status != AgentStatus::Finished
891                        && process_identity_matches(a, &compatibility_identities)
892                        && self
893                            .require_active_for_presence(&a.agent_id, "listing")
894                            .is_ok()
895                }
896            })
897            .collect()
898    }
899
900    pub fn list_all(&self) -> &[AgentEntry] {
901        &self.agents
902    }
903
904    pub(crate) fn post_message(
905        &mut self,
906        from_agent: &str,
907        to_agent: Option<&str>,
908        category: &str,
909        message: &str,
910    ) -> Result<String, String> {
911        self.post_message_full(
912            from_agent,
913            to_agent,
914            category,
915            message,
916            PrivacyLevel::default(),
917            MessagePriority::default(),
918            None,
919        )
920    }
921
922    pub(crate) fn post_message_full(
923        &mut self,
924        from_agent: &str,
925        to_agent: Option<&str>,
926        category: &str,
927        message: &str,
928        privacy: PrivacyLevel,
929        priority: MessagePriority,
930        ttl_hours: Option<u64>,
931    ) -> Result<String, String> {
932        self.post_message_scoped(
933            None, from_agent, to_agent, category, message, privacy, priority, ttl_hours,
934        )
935    }
936
937    #[allow(clippy::too_many_arguments)]
938    pub fn post_message_scoped(
939        &mut self,
940        project_root: Option<&str>,
941        from_agent: &str,
942        to_agent: Option<&str>,
943        category: &str,
944        message: &str,
945        privacy: PrivacyLevel,
946        priority: MessagePriority,
947        ttl_hours: Option<u64>,
948    ) -> Result<String, String> {
949        self.post_message_keyed(
950            project_root,
951            from_agent,
952            to_agent,
953            category,
954            message,
955            privacy,
956            priority,
957            ttl_hours,
958            None,
959        )
960    }
961
962    /// The live entry `from_agent` posted in `project_root` under the
963    /// idempotency key `key`, if any: the one a keyed post would answer with.
964    fn keyed_post(
965        &self,
966        project_root: Option<&str>,
967        from_agent: &str,
968        key: &str,
969    ) -> Option<&ScratchpadEntry> {
970        let now = UtcDateTime::now();
971        self.scratchpad.iter().find(|entry| {
972            entry.from_agent == from_agent
973                && entry.project_root.as_deref() == project_root
974                && entry.expires_at.is_none_or(|expires| expires > now)
975                && entry
976                    .metadata
977                    .get(REQUEST_ID_METADATA_KEY)
978                    .map(String::as_str)
979                    == Some(key)
980        })
981    }
982
983    /// True when `from_agent` holds a live post in `project_root` under the
984    /// idempotency key `key` (whatever its request).
985    pub fn holds_request_id(
986        &self,
987        project_root: Option<&str>,
988        from_agent: &str,
989        key: &str,
990    ) -> bool {
991        self.keyed_post(project_root, from_agent, key).is_some()
992    }
993
994    /// [`Self::post_message_scoped`] with an optional idempotency key
995    /// (AP07-G9). A key is scoped to the sender and project: a retry with the
996    /// same key and the same request returns the id of the message it first
997    /// posted and writes nothing; the same key with another request is
998    /// refused. A key lives as long as its message — the scratchpad's entry
999    /// cap and TTL bound both — and an expired message frees its key.
1000    #[allow(clippy::too_many_arguments)]
1001    pub fn post_message_keyed(
1002        &mut self,
1003        project_root: Option<&str>,
1004        from_agent: &str,
1005        to_agent: Option<&str>,
1006        category: &str,
1007        message: &str,
1008        privacy: PrivacyLevel,
1009        priority: MessagePriority,
1010        ttl_hours: Option<u64>,
1011        request_id: Option<&str>,
1012    ) -> Result<String, String> {
1013        self.require_active_for_presence(from_agent, "posting a message")?;
1014        if let Some(target) = to_agent {
1015            self.require_active_for_presence(target, "receiving a message")?;
1016        }
1017        let request = match request_id {
1018            Some(key) => {
1019                super::check_request_id(key)?;
1020                let digest = super::request_digest(
1021                    "leanctx/agent-post/v1",
1022                    &serde_json::json!([
1023                        project_root,
1024                        to_agent,
1025                        category,
1026                        message,
1027                        privacy,
1028                        priority,
1029                        ttl_hours
1030                    ]),
1031                );
1032                if let Some(entry) = self.keyed_post(project_root, from_agent, key) {
1033                    return if entry.metadata.get(REQUEST_DIGEST_METADATA_KEY) == Some(&digest) {
1034                        Ok(entry.id.clone())
1035                    } else {
1036                        Err(super::request_id_conflict())
1037                    };
1038                }
1039                Some((key, digest))
1040            }
1041            None => None,
1042        };
1043        // Admission precedes persistence: only admitted text is stored, with
1044        // the binding a later read re-authorizes. A withheld message is refused
1045        // with a typed, content-free reason and nothing is written.
1046        let (message, mut metadata) =
1047            ScratchpadEntry::admit_message(from_agent, project_root, message)?;
1048        if let Some((key, digest)) = request {
1049            metadata.insert(REQUEST_ID_METADATA_KEY.to_owned(), key.to_owned());
1050            metadata.insert(REQUEST_DIGEST_METADATA_KEY.to_owned(), digest);
1051        }
1052        let id = generate_short_id();
1053        let default_ttl_hours = crate::core::config::Config::load()
1054            .agents
1055            .scratchpad_default_ttl_hours;
1056        let expires_at = Some(match ttl_hours {
1057            Some(hours) => UtcDateTime::now() + lean_ctx_time::Duration::hours(hours as i64),
1058            None => UtcDateTime::now() + lean_ctx_time::Duration::hours(default_ttl_hours as i64),
1059        });
1060        self.scratchpad.push(ScratchpadEntry {
1061            id: id.clone(),
1062            from_agent: from_agent.to_string(),
1063            to_agent: to_agent.map(std::string::ToString::to_string),
1064            task_id: None,
1065            category: category.to_string(),
1066            priority,
1067            privacy,
1068            message,
1069            metadata,
1070            project_root: project_root.map(std::string::ToString::to_string),
1071            timestamp: UtcDateTime::now(),
1072            read_by: vec![from_agent.to_string()],
1073            expires_at,
1074        });
1075
1076        let max_scratchpad_entries = max_scratchpad();
1077        if self.scratchpad.len() > max_scratchpad_entries {
1078            self.scratchpad
1079                .drain(0..self.scratchpad.len() - max_scratchpad_entries);
1080        }
1081
1082        self.updated_at = UtcDateTime::now();
1083        Ok(id)
1084    }
1085
1086    #[cfg(test)]
1087    pub(crate) fn read_unread(&mut self, agent_id: &str) -> Result<Vec<&ScratchpadEntry>, String> {
1088        self.read_unread_for_project(agent_id, None)
1089    }
1090
1091    #[cfg(test)]
1092    pub(crate) fn read_unread_scoped(
1093        &mut self,
1094        agent_id: &str,
1095        project_root: &str,
1096    ) -> Result<Vec<&ScratchpadEntry>, String> {
1097        self.read_unread_for_project(agent_id, Some(project_root))
1098    }
1099
1100    /// The unread messages of `agent_id` in `project_root`, oldest first, as
1101    /// `render` shows them, up to `budget` bytes (at least one); only those
1102    /// are marked read. Returns them and how many stay unread for the next
1103    /// read: a host that cuts a long answer used to lose the rest, already
1104    /// marked read (WEB saw 14 of 55, 25.10.).
1105    pub fn read_unread_page(
1106        &mut self,
1107        agent_id: &str,
1108        project_root: &str,
1109        budget: usize,
1110        render: impl Fn(&ScratchpadEntry) -> String,
1111    ) -> Result<(Vec<String>, usize), String> {
1112        self.require_active_for_presence(agent_id, "reading messages")?;
1113        let now = UtcDateTime::now();
1114        let floor = self.broadcast_floor(agent_id);
1115        let unread: Vec<usize> = self
1116            .scratchpad
1117            .iter()
1118            .enumerate()
1119            .filter(|(_, e)| unread_for(e, agent_id, Some(project_root), now, floor))
1120            .map(|(i, _)| i)
1121            .collect();
1122        let (mut shown, mut used) = (Vec::new(), 0_usize);
1123        for &index in &unread {
1124            let line = render(&self.scratchpad[index]);
1125            if !shown.is_empty() && used + line.len() > budget {
1126                break;
1127            }
1128            used += line.len();
1129            shown.push(line);
1130            self.scratchpad[index].read_by.push(agent_id.to_string());
1131        }
1132        if !shown.is_empty() {
1133            self.updated_at = now;
1134        }
1135        let left = unread.len() - shown.len();
1136        Ok((shown, left))
1137    }
1138
1139    /// Whether `agent_id` has a message waiting in `project_root` (what
1140    /// [`Self::read_unread_scoped`] would return), without marking it read.
1141    pub(crate) fn has_unread_scoped(&self, agent_id: &str, project_root: &str) -> bool {
1142        let now = UtcDateTime::now();
1143        let floor = self.broadcast_floor(agent_id);
1144        self.scratchpad
1145            .iter()
1146            .any(|e| unread_for(e, agent_id, Some(project_root), now, floor))
1147    }
1148
1149    /// The unread messages of `agent_id` in `project_root` in scratchpad
1150    /// order (oldest first), without marking them read.
1151    pub fn unread_scoped(&self, agent_id: &str, project_root: &str) -> Vec<&ScratchpadEntry> {
1152        let now = UtcDateTime::now();
1153        let floor = self.broadcast_floor(agent_id);
1154        self.scratchpad
1155            .iter()
1156            .filter(|e| unread_for(e, agent_id, Some(project_root), now, floor))
1157            .collect()
1158    }
1159
1160    /// Record `agent_id` as a reader of the messages `ids`; returns how many
1161    /// were not read by it yet.
1162    pub fn mark_read(&mut self, agent_id: &str, ids: &[String]) -> usize {
1163        let mut marked = 0;
1164        for entry in self.scratchpad.iter_mut().filter(|e| ids.contains(&e.id)) {
1165            if !entry.read_by.iter().any(|reader| reader == agent_id) {
1166                entry.read_by.push(agent_id.to_owned());
1167                marked += 1;
1168            }
1169        }
1170        if marked > 0 {
1171            self.updated_at = UtcDateTime::now();
1172        }
1173        marked
1174    }
1175
1176    /// Block until `agent_id` has a message waiting in `project_root`
1177    /// (`true`) or `timeout` passed (`false`). Looks at the registry only when
1178    /// its file changed (polled every `WAIT_POLL`); `on_poll` runs about every
1179    /// 30 s meanwhile (the caller keeps the agent's lease alive there).
1180    pub fn wait_for_unread(
1181        agent_id: &str,
1182        project_root: &str,
1183        timeout: std::time::Duration,
1184        mut on_poll: impl FnMut(),
1185    ) -> bool {
1186        let path = agents_dir().ok().map(|dir| dir.join("registry.json"));
1187        let modified = || {
1188            path.as_ref()
1189                .and_then(|p| std::fs::metadata(p).ok())
1190                .and_then(|m| m.modified().ok())
1191        };
1192        let deadline = std::time::Instant::now() + timeout;
1193        let mut last_poll = std::time::Instant::now();
1194        let mut seen = None;
1195        loop {
1196            let now_modified = modified();
1197            if seen.is_none() || now_modified != seen.flatten() {
1198                seen = Some(now_modified);
1199                if Self::load().is_some_and(|r| r.has_unread_scoped(agent_id, project_root)) {
1200                    return true;
1201                }
1202                // A post replacing the file in the same timestamp tick as the
1203                // version just read leaves the mtime unchanged; without this
1204                // the wait slept through it until the next keepalive (30 s).
1205                let racy = now_modified.is_some_and(|mtime| {
1206                    !std::time::SystemTime::now()
1207                        .duration_since(mtime)
1208                        .is_ok_and(|age| age >= WAIT_RACY_MTIME)
1209                });
1210                if racy {
1211                    seen = None;
1212                }
1213            }
1214            let now = std::time::Instant::now();
1215            if now >= deadline {
1216                return false;
1217            }
1218            if now.duration_since(last_poll) >= WAIT_KEEPALIVE {
1219                on_poll();
1220                last_poll = now;
1221                // Look again even without a visible change (coarse mtimes).
1222                seen = None;
1223            }
1224            std::thread::sleep(WAIT_POLL.min(deadline - now));
1225        }
1226    }
1227
1228    #[cfg(test)]
1229    fn read_unread_for_project(
1230        &mut self,
1231        agent_id: &str,
1232        project_root: Option<&str>,
1233    ) -> Result<Vec<&ScratchpadEntry>, String> {
1234        self.require_active_for_presence(agent_id, "reading messages")?;
1235        let now = UtcDateTime::now();
1236        let floor = self.broadcast_floor(agent_id);
1237        let unread_indices: Vec<usize> = self
1238            .scratchpad
1239            .iter()
1240            .enumerate()
1241            .filter(|(_, e)| unread_for(e, agent_id, project_root, now, floor))
1242            .map(|(i, _)| i)
1243            .collect();
1244
1245        for i in &unread_indices {
1246            self.scratchpad[*i].read_by.push(agent_id.to_string());
1247        }
1248
1249        self.updated_at = UtcDateTime::now();
1250
1251        Ok(unread_indices
1252            .into_iter()
1253            .map(|index| &self.scratchpad[index])
1254            .collect())
1255    }
1256
1257    pub fn cleanup_stale(&mut self, max_age_hours: u64) {
1258        let now = UtcDateTime::now();
1259        let cutoff = now - lean_ctx_time::Duration::hours(max_age_hours as i64);
1260        let worker_cutoff = now - lean_ctx_time::Duration::seconds(active_worker_lease_seconds());
1261        let mut compatibility_identities = ProcessIdentityIndex::load();
1262        let mut identities_changed = false;
1263        let mut newly_certified = Vec::new();
1264
1265        for agent in &mut self.agents {
1266            if agent.status == AgentStatus::Finished {
1267                if is_recoverable_legacy_finished(agent) {
1268                    if let Some(identity) = safe_legacy_identity(agent) {
1269                        identities_changed |=
1270                            compatibility_identities.insert(&agent.agent_id, &identity);
1271                        newly_certified.push(agent.agent_id.clone());
1272                        agent.status = AgentStatus::Active;
1273                        agent.status_message =
1274                            Some("legacy process identity recovered".to_string());
1275                    }
1276                }
1277                continue;
1278            }
1279            if let Some(identity) = &agent.process_identity {
1280                identities_changed |= compatibility_identities.insert(&agent.agent_id, identity);
1281            }
1282            if process_identity_matches(agent, &compatibility_identities) {
1283                // A live MCP process is not proof that its worker is still
1284                // participating.  The worker lease is renewed by `read` or
1285                // `status=active`; expire quiet Active presences even when the
1286                // hosting daemon itself remains alive.  This prevents stale
1287                // sessions from occupying capacity or appearing as peers.
1288                // The MCP server's own transport presence is the exception:
1289                // its process is the connection, so it idles instead of
1290                // vanishing while the editor keeps it open.
1291                if agent.status == AgentStatus::Active && agent.last_active < worker_cutoff {
1292                    if agent.transport.is_some() {
1293                        agent.status = AgentStatus::Idle;
1294                        agent.status_message = Some(TRANSPORT_IDLE.to_string());
1295                    } else {
1296                        agent.status = AgentStatus::Finished;
1297                        agent.status_message = Some(WORKER_LEASE_EXPIRED.to_string());
1298                    }
1299                }
1300                continue;
1301            }
1302            if let Some(identity) = safe_legacy_identity(agent) {
1303                identities_changed |= compatibility_identities.insert(&agent.agent_id, &identity);
1304                newly_certified.push(agent.agent_id.clone());
1305                continue;
1306            }
1307            {
1308                agent.status = AgentStatus::Finished;
1309                agent.status_message = Some("process identity no longer matches".to_string());
1310            }
1311        }
1312
1313        // Presence is operational state, not an audit log. Keep the newest
1314        // completed sessions for diagnostics but bound their in-memory/on-disk
1315        // history so a burst of short-lived agents cannot slow later checks.
1316        let mut finished_by_recency: Vec<_> = self
1317            .agents
1318            .iter()
1319            .filter(|agent| agent.status == AgentStatus::Finished && agent.last_active >= cutoff)
1320            .collect();
1321        finished_by_recency.sort_unstable_by(|left, right| {
1322            right
1323                .last_active
1324                .cmp(&left.last_active)
1325                .then_with(|| left.agent_id.cmp(&right.agent_id))
1326        });
1327        let retained_finished_ids: HashSet<String> = finished_by_recency
1328            .into_iter()
1329            .take(MAX_RETAINED_FINISHED_AGENTS)
1330            .map(|agent| agent.agent_id.clone())
1331            .collect();
1332
1333        // Drop each retired agent's budget entry too — a finished/dead agent can't read
1334        // again, so removing its budget loses no live enforcement and bounds BUDGETS.
1335        self.agents.retain(|a| {
1336            let retire = a.status == AgentStatus::Finished
1337                && (a.last_active < cutoff || !retained_finished_ids.contains(&a.agent_id));
1338            if retire {
1339                crate::core::agent_budget::remove(&a.agent_id);
1340            }
1341            !retire
1342        });
1343        identities_changed |= compatibility_identities.retain_agents(self);
1344        if identities_changed && compatibility_identities.save().is_err() {
1345            for agent in &mut self.agents {
1346                if newly_certified.contains(&agent.agent_id) {
1347                    agent.status = AgentStatus::Finished;
1348                    agent.status_message =
1349                        Some("legacy process identity could not be persisted".to_string());
1350                }
1351            }
1352        }
1353
1354        // Remove expired scratchpad entries.
1355        let now = UtcDateTime::now();
1356        self.scratchpad
1357            .retain(|entry| entry.expires_at.is_none_or(|exp| exp > now));
1358
1359        self.updated_at = UtcDateTime::now();
1360    }
1361
1362    #[cfg(any(test, feature = "test-support"))]
1363    pub fn save(&self) -> Result<(), String> {
1364        let dir = agents_dir()?;
1365        create_agents_dir(&dir)?;
1366
1367        let lock_path = dir.join("registry.lock");
1368        let _lock = FileLock::acquire(&lock_path)?;
1369
1370        self.save_locked(&dir)
1371    }
1372
1373    pub(super) fn save_locked(&self, dir: &std::path::Path) -> Result<(), String> {
1374        let path = dir.join("registry.json");
1375        save_registry_file(&path, self)
1376    }
1377
1378    pub fn load() -> Option<Self> {
1379        let dir = agents_dir().ok()?;
1380        let path = dir.join("registry.json");
1381        load_registry_file(&path).ok().flatten()
1382    }
1383
1384    pub fn load_or_create() -> Self {
1385        Self::load().unwrap_or_default()
1386    }
1387
1388    /// The registry, read strictly: no file yet is an empty registry, but a
1389    /// file that cannot be read or parsed is an error rather than "no
1390    /// agents" (for callers that must fail closed, e.g. a worker sweep that
1391    /// would otherwise take every live session's worker for idle).
1392    pub fn load_checked() -> Result<Self, String> {
1393        let dir = agents_dir()?;
1394        Ok(load_registry_file(&dir.join("registry.json"))?.unwrap_or_default())
1395    }
1396
1397    /// Atomically load, mutate, and persist the registry under a single file
1398    /// lock. `load_or_create()` + mutate + `save()` is a read-modify-write
1399    /// race: `save()` only locks the final write, so two concurrent callers
1400    /// (two MCP sessions registering, or the dashboard's own poll-triggered
1401    /// `cleanup_stale` + save) can each load a stale snapshot and the last
1402    /// writer silently drops the other's changes — e.g. a second session's
1403    /// registration vanishing from the dashboard. Holding the lock across
1404    /// the re-read closes that window: the read inside always sees the
1405    /// latest on-disk state.
1406    pub fn mutate_locked<T>(f: impl FnOnce(&mut Self) -> T) -> Result<(Self, T), String> {
1407        let dir = agents_dir()?;
1408        create_agents_dir(&dir)?;
1409
1410        let lock_path = dir.join("registry.lock");
1411        let _lock = FileLock::acquire(&lock_path)?;
1412
1413        let path = dir.join("registry.json");
1414        let mut registry = load_registry_file(&path)?.unwrap_or_default();
1415        let out = f(&mut registry);
1416        registry.save_locked(&dir)?;
1417        Ok((registry, out))
1418    }
1419}
1420
1421impl Default for AgentRegistry {
1422    fn default() -> Self {
1423        Self::new()
1424    }
1425}
1426
1427/// "Announce this machine's agents now", from the Cloud connector when it is
1428/// linked in (`core::cloud::register_hooks`): a revived worker is on the bus
1429/// again before its next claim. Bookkeeping only; without it nothing waits.
1430static ANNOUNCE: std::sync::OnceLock<fn()> = std::sync::OnceLock::new();
1431
1432/// Register the announce request; the first registration wins.
1433pub fn register_announce(request: fn()) {
1434    let _ = ANNOUNCE.set(request);
1435}
1436
1437fn request_announce() {
1438    if let Some(request) = ANNOUNCE.get() {
1439        request();
1440    }
1441}
1442
1443#[cfg(test)]
1444#[path = "registry_tests.rs"]
1445mod tests;
1446
1447#[cfg(test)]
1448#[path = "registry_logical_session_tests.rs"]
1449mod logical_session_tests;
1450// SPDX-License-Identifier: Apache-2.0
1451#[cfg(test)]
1452#[path = "registry_presence_tests.rs"]
1453mod presence_tests;