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
17const PLACEHOLDER_ROLE: &str = super::types::ENGINE_PLACEHOLDER_ROLE;
19const WORKER_LEASE_EXPIRED: &str = "worker lease expired; register again before continuing";
20const TRANSPORT_IDLE: &str = "connected; no tool call within the worker lease";
23
24#[derive(Default)]
26struct RegistrationMeta {
27 role_source: Option<RoleSource>,
28 transport: Option<TransportClient>,
29}
30
31fn 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
41static 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
57pub fn take_renewed(agent_id: &str) -> bool {
60 RENEWED
61 .lock()
62 .is_ok_and(|mut renewed| renewed.remove(agent_id))
63}
64
65const WAIT_POLL: std::time::Duration = std::time::Duration::from_millis(500);
67const WAIT_KEEPALIVE: std::time::Duration = std::time::Duration::from_secs(30);
69const WAIT_RACY_MTIME: std::time::Duration = std::time::Duration::from_secs(3);
73
74const BROADCAST_GRACE: lean_ctx_time::Duration = lean_ctx_time::Duration::minutes(10);
78
79fn 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
103fn 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;
115const 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 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 let parent_client = self
255 .agents
256 .iter()
257 .find(|a| a.agent_id == parent_id)
258 .and_then(|parent| parent.transport.clone().or(parent.parent_client.clone()));
259 if let Some(child) = self.agents.iter_mut().find(|a| {
260 a.parent.as_deref() == Some(parent_id)
261 && a.role.as_deref() == Some(role)
262 && a.status != AgentStatus::Finished
263 }) {
264 child.last_active = now;
265 child.status = AgentStatus::Active;
266 child.project_root = project_root.to_string();
267 if parent_client.is_some() {
268 child.parent_client = parent_client;
269 }
270 return Ok(child.agent_id.clone());
271 }
272 let agent_id = format!("{}-{}-{}", agent_type, pid, generate_short_id());
273 let agent_type = self.child_agent_type(agent_type, parent_id);
274 self.agents.push(AgentEntry {
275 agent_id: agent_id.clone(),
276 agent_type,
277 role: Some(role.to_string()),
278 project_root: project_root.to_string(),
279 started_at: now,
280 last_active: now,
281 pid,
282 process_identity: Some(identity),
283 durable_identity_id: None,
284 status: AgentStatus::Active,
285 status_message: None,
286 agent_status_message: None,
287 transport: None,
288 role_source: Some(RoleSource::Declared),
289 parent: Some(parent_id.to_string()),
290 parent_client,
291 app_session_id: crate::core::activity::session_id_from_env(),
292 display_name: crate::core::activity::session_name_from_env(),
293 });
294 self.updated_at = now;
295 crate::core::events::emit_agent_action(&agent_id, "register", None);
296 Ok(agent_id)
297 }
298
299 pub(crate) fn child_agent_type(&self, agent_type: &str, parent_id: &str) -> String {
305 let vague = |t: &str| {
306 let t = t.trim();
307 t.is_empty()
308 || ["subagent", "unknown", "mcp"]
309 .iter()
310 .any(|v| t.eq_ignore_ascii_case(v))
311 };
312 if !vague(agent_type) {
313 return agent_type.to_string();
314 }
315 self.agents
316 .iter()
317 .find(|a| a.agent_id == parent_id)
318 .and_then(|parent| {
319 parent
320 .transport
321 .as_ref()
322 .map(|t| t.host.as_str())
323 .filter(|host| !vague(host))
324 .or_else(|| Some(parent.agent_type.as_str()).filter(|t| !vague(t)))
325 })
326 .map_or_else(|| agent_type.to_string(), str::to_string)
327 }
328
329 fn broadcast_floor(&self, agent_id: &str) -> Option<lean_ctx_time::UtcDateTime> {
332 self.agents
333 .iter()
334 .find(|a| a.agent_id == agent_id)
335 .map(|a| a.started_at - BROADCAST_GRACE)
336 }
337
338 pub fn held_by_this_process(&self, agent_id: &str) -> bool {
341 let pid = std::process::id();
342 let identity = crate::ipc::process::identity(pid);
343 self.agents.iter().any(|a| {
344 a.agent_id == agent_id
345 && a.pid == pid
346 && a.status != AgentStatus::Finished
347 && a.process_identity.is_some()
348 && a.process_identity == identity
349 })
350 }
351
352 pub fn set_display_name(&mut self, agent_id: &str, name: &str) -> bool {
355 match self.agents.iter_mut().find(|a| a.agent_id == agent_id) {
356 Some(agent) => {
357 agent.display_name = Some(name.to_owned());
358 true
359 }
360 None => false,
361 }
362 }
363
364 pub fn declared_role(&self, agent_id: &str) -> Option<String> {
366 self.agents
367 .iter()
368 .find(|a| a.agent_id == agent_id && a.role_source == Some(RoleSource::Declared))
369 .and_then(|a| a.role.clone())
370 }
371
372 pub fn register_transport(
375 &mut self,
376 role: &str,
377 role_source: RoleSource,
378 project_root: &str,
379 durable_identity_id: Option<&str>,
380 transport: TransportClient,
381 ) -> Result<String, String> {
382 self.register_process_with(
383 "mcp",
384 Some(role),
385 project_root,
386 durable_identity_id,
387 std::process::id(),
388 RegistrationMeta {
389 role_source: Some(role_source),
390 transport: Some(transport),
391 },
392 )
393 }
394
395 fn register_process_with(
396 &mut self,
397 agent_type: &str,
398 role: Option<&str>,
399 project_root: &str,
400 durable_identity_id: Option<&str>,
401 pid: u32,
402 meta: RegistrationMeta,
403 ) -> Result<String, String> {
404 if let Some(identity_id) = durable_identity_id {
405 crate::core::agent_registry::require_active(identity_id)?;
406 }
407 let identity = crate::ipc::process::identity(pid)
408 .ok_or_else(|| format!("cannot establish immutable process identity for PID {pid}"))?;
409 let agent_id = format!("{}-{}-{}", agent_type, pid, generate_short_id());
410
411 if let Some(existing_index) = self.agents.iter().position(|a| {
412 a.pid == pid
413 && a.parent.is_none()
414 && a.status != AgentStatus::Finished
415 && a.process_identity.as_ref() == Some(&identity)
416 }) {
417 let existing_binding = self.agents[existing_index].durable_identity_id.clone();
418 if let (Some(existing_id), Some(requested_id)) =
419 (existing_binding.as_deref(), durable_identity_id)
420 && existing_id != requested_id
421 {
422 return Err(format!(
423 "agent presence '{}' is already bound to durable identity '{}'; refusing rebind to '{}'",
424 self.agents[existing_index].agent_id, existing_id, requested_id
425 ));
426 }
427 if existing_binding.is_some() {
428 self.require_active_for_presence(
429 &self.agents[existing_index].agent_id,
430 "registration",
431 )?;
432 }
433 let existing = &mut self.agents[existing_index];
434 existing.last_active = UtcDateTime::now();
435 existing.status = AgentStatus::Active;
436 if existing.status_message.as_deref() == Some(TRANSPORT_IDLE) {
437 existing.status_message = None;
438 }
439 if meta.transport.is_none() || existing.agent_type == "mcp" {
442 existing.agent_type = agent_type.to_string();
443 }
444 existing.project_root = project_root.to_string();
445 match role {
451 Some(PLACEHOLDER_ROLE) if existing.role.is_some() => {}
452 Some(_)
453 if meta.role_source == Some(RoleSource::Assumed)
454 && existing.role_source == Some(RoleSource::Declared) => {}
455 Some(r) => {
456 existing.role = Some(r.to_string());
457 existing.role_source = meta.role_source;
458 }
459 None => {}
460 }
461 if let Some(transport) = meta.transport
463 && (transport.is_identified() || existing.transport.is_none())
464 {
465 existing.transport = Some(transport);
466 }
467 if existing.durable_identity_id.is_none() {
468 existing.durable_identity_id = durable_identity_id.map(str::to_string);
469 }
470 if existing.app_session_id.is_none() {
471 existing.app_session_id = crate::core::activity::session_id_from_env();
472 }
473 if let Some(name) = crate::core::activity::session_name_from_env() {
474 existing.display_name = Some(name);
475 }
476 return Ok(self.adopt_app_session_identity(existing_index));
477 }
478
479 for existing in self
483 .agents
484 .iter_mut()
485 .filter(|agent| agent.pid == pid && agent.status != AgentStatus::Finished)
486 {
487 existing.status = AgentStatus::Finished;
488 existing.status_message =
489 Some("superseded by a different process identity".to_string());
490 }
491
492 self.agents.push(AgentEntry {
497 agent_id: agent_id.clone(),
498 agent_type: agent_type.to_string(),
499 role: role.map(std::string::ToString::to_string),
500 project_root: project_root.to_string(),
501 started_at: UtcDateTime::now(),
502 last_active: UtcDateTime::now(),
503 pid,
504 process_identity: Some(identity),
505 durable_identity_id: durable_identity_id.map(str::to_string),
506 status: AgentStatus::Active,
507 status_message: None,
508 agent_status_message: None,
509 transport: meta.transport,
510 role_source: meta.role_source,
511 parent: None,
512 parent_client: None,
513 app_session_id: crate::core::activity::session_id_from_env(),
514 display_name: crate::core::activity::session_name_from_env(),
515 });
516 let agent_id = self.adopt_app_session_identity(self.agents.len() - 1);
517
518 self.updated_at = UtcDateTime::now();
519 crate::core::events::emit_agent_action(&agent_id, "register", None);
520 Ok(agent_id)
521 }
522
523 fn adopt_app_session_identity(&mut self, index: usize) -> String {
532 let current = &self.agents[index];
533 let (Some(app), Some(role)) = (current.app_session_id.clone(), current.role.clone()) else {
534 return current.agent_id.clone();
535 };
536 if role == PLACEHOLDER_ROLE || current.parent.is_some() {
537 return current.agent_id.clone();
538 }
539 let binding = current.durable_identity_id.clone();
540 let earlier = self.agents.iter().enumerate().position(|(i, a)| {
541 i != index
542 && a.parent.is_none()
543 && a.app_session_id.as_deref() == Some(app.as_str())
544 && a.role.as_deref() == Some(role.as_str())
545 && (a.durable_identity_id.is_none() || a.durable_identity_id == binding)
546 && (a.status == AgentStatus::Finished
547 || a.process_identity.as_ref().is_some_and(|identity| {
548 !crate::ipc::process::matches_identity(a.pid, identity)
549 }))
550 });
551 let Some(earlier) = earlier else {
552 return self.agents[index].agent_id.clone();
553 };
554 let old = self.agents.remove(earlier);
555 let index = if earlier < index { index - 1 } else { index };
556 let current = &mut self.agents[index];
557 current.agent_id = old.agent_id;
558 current.started_at = old.started_at;
559 if current.durable_identity_id.is_none() {
560 current.durable_identity_id = old.durable_identity_id;
561 }
562 current.agent_id.clone()
563 }
564
565 pub fn register_mcp_process(
567 project_root: &str,
568 durable_identity_id: Option<&str>,
569 ) -> Result<String, String> {
570 Self::register_mcp_process_as(
571 project_root,
572 PLACEHOLDER_ROLE,
573 RoleSource::Assumed,
574 durable_identity_id,
575 )
576 }
577
578 pub fn register_mcp_process_as(
583 project_root: &str,
584 role: &str,
585 role_source: RoleSource,
586 durable_identity_id: Option<&str>,
587 ) -> Result<String, String> {
588 let transport = TransportClient::current();
589 mutate_persistent(|registry| {
590 registry.cleanup_stale(presence_ttl());
591 registry.register_transport(
592 role,
593 role_source,
594 project_root,
595 durable_identity_id,
596 transport,
597 )
598 })
599 .and_then(|result| result)
600 }
601
602 pub fn record_transport_client_persistent(
606 transport: &TransportClient,
607 ) -> Result<usize, String> {
608 mutate_persistent(|registry| registry.record_transport_client(transport))
609 }
610
611 pub(crate) fn record_transport_client(&mut self, transport: &TransportClient) -> usize {
612 let mut updated = 0;
613 for agent in self.agents.iter_mut().filter(|agent| {
614 agent.transport.is_some()
615 && agent.status != AgentStatus::Finished
616 && owned_by_current_process(agent)
617 }) {
618 agent.transport = Some(transport.clone());
619 updated += 1;
620 }
621 let mut children = 0;
624 for agent in self.agents.iter_mut().filter(|agent| {
625 agent.parent.is_some()
626 && agent.transport.is_none()
627 && agent.status != AgentStatus::Finished
628 && owned_by_current_process(agent)
629 }) {
630 agent.parent_client = Some(transport.clone());
631 children += 1;
632 }
633 if updated + children > 0 {
634 self.updated_at = UtcDateTime::now();
635 }
636 updated
637 }
638
639 pub fn transport_presence_is_live(agent_id: &str) -> bool {
643 Self::load().is_some_and(|registry| {
644 registry.agents.iter().any(|agent| {
645 agent.agent_id == agent_id
646 && agent.status != AgentStatus::Finished
647 && owned_by_current_process(agent)
648 })
649 })
650 }
651
652 pub fn any_live_mcp_transport() -> bool {
658 let Some(registry) = Self::load() else {
659 return false;
660 };
661 let identities = ProcessIdentityIndex::load();
662 registry.agents.iter().any(|agent| {
663 agent.transport.is_some()
664 && agent.status != AgentStatus::Finished
665 && process_identity_matches(agent, &identities)
666 })
667 }
668
669 pub fn heartbeat_persistent(agent_id: &str) -> Result<(), String> {
674 mutate_persistent(|registry| registry.update_transport_heartbeat(agent_id))?
675 }
676
677 pub(crate) fn update_transport_heartbeat(&mut self, agent_id: &str) -> Result<(), String> {
678 if self.revive_lease_expired(agent_id) {
679 note_renewed(agent_id);
680 }
681 self.update_heartbeat(agent_id)
682 }
683
684 fn revive_lease_expired(&mut self, agent_id: &str) -> bool {
688 let Some(agent) = self
689 .agents
690 .iter_mut()
691 .find(|agent| agent.agent_id == agent_id)
692 else {
693 return false;
694 };
695 if agent.status == AgentStatus::Finished
696 && agent.status_message.as_deref() == Some(WORKER_LEASE_EXPIRED)
697 && agent.durable_identity_id.is_none()
698 && owned_by_current_process(agent)
699 {
700 agent.status = AgentStatus::Active;
701 agent.status_message = None;
702 return true;
703 }
704 false
705 }
706
707 pub fn renew_worker(&mut self, agent_id: &str) -> Result<bool, String> {
712 let revived = self.revive_lease_expired(agent_id);
713 self.update_heartbeat(agent_id)?;
714 if revived {
715 note_renewed(agent_id);
716 request_announce();
717 }
718 Ok(revived)
719 }
720
721 pub fn renew_worker_persistent(agent_id: &str) -> Result<bool, String> {
723 mutate_persistent(|registry| registry.renew_worker(agent_id))?
724 }
725
726 pub fn finish_persistent(agent_id: &str) -> Result<(), String> {
728 mutate_persistent(|registry| {
729 registry.set_status(agent_id, AgentStatus::Finished, Some("connection closed"))
730 })?
731 }
732
733 pub fn update_heartbeat(&mut self, agent_id: &str) -> Result<(), String> {
734 let index = self
735 .agents
736 .iter()
737 .position(|agent| agent.agent_id == agent_id)
738 .ok_or_else(|| format!("agent presence '{agent_id}' was not found"))?;
739 if self.agents[index].status == AgentStatus::Finished {
740 return Err(format!(
741 "agent presence '{agent_id}' is finished; register a new process presence"
742 ));
743 }
744 self.require_active_for_presence(agent_id, "heartbeat")?;
745 let agent = &mut self.agents[index];
746 let pid = std::process::id();
747 if agent.pid != pid {
748 return Err(format!(
749 "agent presence '{agent_id}' belongs to PID {}; heartbeat came from PID {pid}",
750 agent.pid
751 ));
752 }
753 let identity = crate::ipc::process::identity(pid)
754 .ok_or_else(|| format!("cannot establish immutable process identity for PID {pid}"))?;
755 if let Some(expected) = &agent.process_identity
756 && expected != &identity
757 {
758 return Err(format!(
759 "agent presence '{agent_id}' process identity no longer matches"
760 ));
761 }
762 agent.process_identity = Some(identity);
765 agent.status = AgentStatus::Active;
766 if agent.status_message.as_deref() == Some(TRANSPORT_IDLE) {
767 agent.status_message = None;
768 }
769 agent.last_active = UtcDateTime::now();
770 Ok(())
771 }
772
773 pub fn set_status(
774 &mut self,
775 agent_id: &str,
776 status: AgentStatus,
777 message: Option<&str>,
778 ) -> Result<(), String> {
779 let index = self
780 .agents
781 .iter()
782 .position(|agent| agent.agent_id == agent_id)
783 .ok_or_else(|| format!("agent presence '{agent_id}' was not found"))?;
784 if status != AgentStatus::Finished {
787 self.require_active_for_presence(agent_id, "status transition")?;
788 }
789 let agent = &mut self.agents[index];
790 agent.status = status;
791 agent.status_message = message.map(std::string::ToString::to_string);
792 agent.last_active = UtcDateTime::now();
793 self.updated_at = UtcDateTime::now();
794 Ok(())
795 }
796
797 pub fn set_status_by_agent(
803 &mut self,
804 agent_id: &str,
805 status: AgentStatus,
806 message: Option<&str>,
807 ) -> Result<(), String> {
808 self.set_status(agent_id, status, message)?;
809 if let Some(agent) = self.agents.iter_mut().find(|a| a.agent_id == agent_id) {
810 agent.agent_status_message = message.map(std::string::ToString::to_string);
811 }
812 Ok(())
813 }
814
815 pub fn list_active(&self, project_root: Option<&str>) -> Vec<&AgentEntry> {
816 let compatibility_identities = ProcessIdentityIndex::load();
817 self.agents
818 .iter()
819 .filter(|a| {
820 if let Some(root) = project_root {
821 crate::core::pathutil::same_project(&a.project_root, root)
822 && a.status != AgentStatus::Finished
823 && process_identity_matches(a, &compatibility_identities)
824 && self
825 .require_active_for_presence(&a.agent_id, "listing")
826 .is_ok()
827 } else {
828 a.status != AgentStatus::Finished
829 && process_identity_matches(a, &compatibility_identities)
830 && self
831 .require_active_for_presence(&a.agent_id, "listing")
832 .is_ok()
833 }
834 })
835 .collect()
836 }
837
838 pub fn list_all(&self) -> &[AgentEntry] {
839 &self.agents
840 }
841
842 pub(crate) fn post_message(
843 &mut self,
844 from_agent: &str,
845 to_agent: Option<&str>,
846 category: &str,
847 message: &str,
848 ) -> Result<String, String> {
849 self.post_message_full(
850 from_agent,
851 to_agent,
852 category,
853 message,
854 PrivacyLevel::default(),
855 MessagePriority::default(),
856 None,
857 )
858 }
859
860 pub(crate) fn post_message_full(
861 &mut self,
862 from_agent: &str,
863 to_agent: Option<&str>,
864 category: &str,
865 message: &str,
866 privacy: PrivacyLevel,
867 priority: MessagePriority,
868 ttl_hours: Option<u64>,
869 ) -> Result<String, String> {
870 self.post_message_scoped(
871 None, from_agent, to_agent, category, message, privacy, priority, ttl_hours,
872 )
873 }
874
875 #[allow(clippy::too_many_arguments)]
876 pub fn post_message_scoped(
877 &mut self,
878 project_root: Option<&str>,
879 from_agent: &str,
880 to_agent: Option<&str>,
881 category: &str,
882 message: &str,
883 privacy: PrivacyLevel,
884 priority: MessagePriority,
885 ttl_hours: Option<u64>,
886 ) -> Result<String, String> {
887 self.post_message_keyed(
888 project_root,
889 from_agent,
890 to_agent,
891 category,
892 message,
893 privacy,
894 priority,
895 ttl_hours,
896 None,
897 )
898 }
899
900 fn keyed_post(
903 &self,
904 project_root: Option<&str>,
905 from_agent: &str,
906 key: &str,
907 ) -> Option<&ScratchpadEntry> {
908 let now = UtcDateTime::now();
909 self.scratchpad.iter().find(|entry| {
910 entry.from_agent == from_agent
911 && entry.project_root.as_deref() == project_root
912 && entry.expires_at.is_none_or(|expires| expires > now)
913 && entry
914 .metadata
915 .get(REQUEST_ID_METADATA_KEY)
916 .map(String::as_str)
917 == Some(key)
918 })
919 }
920
921 pub fn holds_request_id(
924 &self,
925 project_root: Option<&str>,
926 from_agent: &str,
927 key: &str,
928 ) -> bool {
929 self.keyed_post(project_root, from_agent, key).is_some()
930 }
931
932 #[allow(clippy::too_many_arguments)]
939 pub fn post_message_keyed(
940 &mut self,
941 project_root: Option<&str>,
942 from_agent: &str,
943 to_agent: Option<&str>,
944 category: &str,
945 message: &str,
946 privacy: PrivacyLevel,
947 priority: MessagePriority,
948 ttl_hours: Option<u64>,
949 request_id: Option<&str>,
950 ) -> Result<String, String> {
951 self.require_active_for_presence(from_agent, "posting a message")?;
952 if let Some(target) = to_agent {
953 self.require_active_for_presence(target, "receiving a message")?;
954 }
955 let request = match request_id {
956 Some(key) => {
957 super::check_request_id(key)?;
958 let digest = super::request_digest(
959 "leanctx/agent-post/v1",
960 &serde_json::json!([
961 project_root,
962 to_agent,
963 category,
964 message,
965 privacy,
966 priority,
967 ttl_hours
968 ]),
969 );
970 if let Some(entry) = self.keyed_post(project_root, from_agent, key) {
971 return if entry.metadata.get(REQUEST_DIGEST_METADATA_KEY) == Some(&digest) {
972 Ok(entry.id.clone())
973 } else {
974 Err(super::request_id_conflict())
975 };
976 }
977 Some((key, digest))
978 }
979 None => None,
980 };
981 let (message, mut metadata) =
985 ScratchpadEntry::admit_message(from_agent, project_root, message)?;
986 if let Some((key, digest)) = request {
987 metadata.insert(REQUEST_ID_METADATA_KEY.to_owned(), key.to_owned());
988 metadata.insert(REQUEST_DIGEST_METADATA_KEY.to_owned(), digest);
989 }
990 let id = generate_short_id();
991 let default_ttl_hours = crate::core::config::Config::load()
992 .agents
993 .scratchpad_default_ttl_hours;
994 let expires_at = Some(match ttl_hours {
995 Some(hours) => UtcDateTime::now() + lean_ctx_time::Duration::hours(hours as i64),
996 None => UtcDateTime::now() + lean_ctx_time::Duration::hours(default_ttl_hours as i64),
997 });
998 self.scratchpad.push(ScratchpadEntry {
999 id: id.clone(),
1000 from_agent: from_agent.to_string(),
1001 to_agent: to_agent.map(std::string::ToString::to_string),
1002 task_id: None,
1003 category: category.to_string(),
1004 priority,
1005 privacy,
1006 message,
1007 metadata,
1008 project_root: project_root.map(std::string::ToString::to_string),
1009 timestamp: UtcDateTime::now(),
1010 read_by: vec![from_agent.to_string()],
1011 expires_at,
1012 });
1013
1014 let max_scratchpad_entries = max_scratchpad();
1015 if self.scratchpad.len() > max_scratchpad_entries {
1016 self.scratchpad
1017 .drain(0..self.scratchpad.len() - max_scratchpad_entries);
1018 }
1019
1020 self.updated_at = UtcDateTime::now();
1021 Ok(id)
1022 }
1023
1024 #[cfg(test)]
1025 pub(crate) fn read_unread(&mut self, agent_id: &str) -> Result<Vec<&ScratchpadEntry>, String> {
1026 self.read_unread_for_project(agent_id, None)
1027 }
1028
1029 #[cfg(test)]
1030 pub(crate) fn read_unread_scoped(
1031 &mut self,
1032 agent_id: &str,
1033 project_root: &str,
1034 ) -> Result<Vec<&ScratchpadEntry>, String> {
1035 self.read_unread_for_project(agent_id, Some(project_root))
1036 }
1037
1038 pub fn read_unread_page(
1044 &mut self,
1045 agent_id: &str,
1046 project_root: &str,
1047 budget: usize,
1048 render: impl Fn(&ScratchpadEntry) -> String,
1049 ) -> Result<(Vec<String>, usize), String> {
1050 self.require_active_for_presence(agent_id, "reading messages")?;
1051 let now = UtcDateTime::now();
1052 let floor = self.broadcast_floor(agent_id);
1053 let unread: Vec<usize> = self
1054 .scratchpad
1055 .iter()
1056 .enumerate()
1057 .filter(|(_, e)| unread_for(e, agent_id, Some(project_root), now, floor))
1058 .map(|(i, _)| i)
1059 .collect();
1060 let (mut shown, mut used) = (Vec::new(), 0_usize);
1061 for &index in &unread {
1062 let line = render(&self.scratchpad[index]);
1063 if !shown.is_empty() && used + line.len() > budget {
1064 break;
1065 }
1066 used += line.len();
1067 shown.push(line);
1068 self.scratchpad[index].read_by.push(agent_id.to_string());
1069 }
1070 if !shown.is_empty() {
1071 self.updated_at = now;
1072 }
1073 let left = unread.len() - shown.len();
1074 Ok((shown, left))
1075 }
1076
1077 pub(crate) fn has_unread_scoped(&self, agent_id: &str, project_root: &str) -> bool {
1080 let now = UtcDateTime::now();
1081 let floor = self.broadcast_floor(agent_id);
1082 self.scratchpad
1083 .iter()
1084 .any(|e| unread_for(e, agent_id, Some(project_root), now, floor))
1085 }
1086
1087 pub fn unread_scoped(&self, agent_id: &str, project_root: &str) -> Vec<&ScratchpadEntry> {
1090 let now = UtcDateTime::now();
1091 let floor = self.broadcast_floor(agent_id);
1092 self.scratchpad
1093 .iter()
1094 .filter(|e| unread_for(e, agent_id, Some(project_root), now, floor))
1095 .collect()
1096 }
1097
1098 pub fn mark_read(&mut self, agent_id: &str, ids: &[String]) -> usize {
1101 let mut marked = 0;
1102 for entry in self.scratchpad.iter_mut().filter(|e| ids.contains(&e.id)) {
1103 if !entry.read_by.iter().any(|reader| reader == agent_id) {
1104 entry.read_by.push(agent_id.to_owned());
1105 marked += 1;
1106 }
1107 }
1108 if marked > 0 {
1109 self.updated_at = UtcDateTime::now();
1110 }
1111 marked
1112 }
1113
1114 pub fn wait_for_unread(
1119 agent_id: &str,
1120 project_root: &str,
1121 timeout: std::time::Duration,
1122 mut on_poll: impl FnMut(),
1123 ) -> bool {
1124 let path = agents_dir().ok().map(|dir| dir.join("registry.json"));
1125 let modified = || {
1126 path.as_ref()
1127 .and_then(|p| std::fs::metadata(p).ok())
1128 .and_then(|m| m.modified().ok())
1129 };
1130 let deadline = std::time::Instant::now() + timeout;
1131 let mut last_poll = std::time::Instant::now();
1132 let mut seen = None;
1133 loop {
1134 let now_modified = modified();
1135 if seen.is_none() || now_modified != seen.flatten() {
1136 seen = Some(now_modified);
1137 if Self::load().is_some_and(|r| r.has_unread_scoped(agent_id, project_root)) {
1138 return true;
1139 }
1140 let racy = now_modified.is_some_and(|mtime| {
1144 !std::time::SystemTime::now()
1145 .duration_since(mtime)
1146 .is_ok_and(|age| age >= WAIT_RACY_MTIME)
1147 });
1148 if racy {
1149 seen = None;
1150 }
1151 }
1152 let now = std::time::Instant::now();
1153 if now >= deadline {
1154 return false;
1155 }
1156 if now.duration_since(last_poll) >= WAIT_KEEPALIVE {
1157 on_poll();
1158 last_poll = now;
1159 seen = None;
1161 }
1162 std::thread::sleep(WAIT_POLL.min(deadline - now));
1163 }
1164 }
1165
1166 #[cfg(test)]
1167 fn read_unread_for_project(
1168 &mut self,
1169 agent_id: &str,
1170 project_root: Option<&str>,
1171 ) -> Result<Vec<&ScratchpadEntry>, String> {
1172 self.require_active_for_presence(agent_id, "reading messages")?;
1173 let now = UtcDateTime::now();
1174 let floor = self.broadcast_floor(agent_id);
1175 let unread_indices: Vec<usize> = self
1176 .scratchpad
1177 .iter()
1178 .enumerate()
1179 .filter(|(_, e)| unread_for(e, agent_id, project_root, now, floor))
1180 .map(|(i, _)| i)
1181 .collect();
1182
1183 for i in &unread_indices {
1184 self.scratchpad[*i].read_by.push(agent_id.to_string());
1185 }
1186
1187 self.updated_at = UtcDateTime::now();
1188
1189 Ok(unread_indices
1190 .into_iter()
1191 .map(|index| &self.scratchpad[index])
1192 .collect())
1193 }
1194
1195 pub fn cleanup_stale(&mut self, max_age_hours: u64) {
1196 let now = UtcDateTime::now();
1197 let cutoff = now - lean_ctx_time::Duration::hours(max_age_hours as i64);
1198 let worker_cutoff = now - lean_ctx_time::Duration::seconds(active_worker_lease_seconds());
1199 let mut compatibility_identities = ProcessIdentityIndex::load();
1200 let mut identities_changed = false;
1201 let mut newly_certified = Vec::new();
1202
1203 for agent in &mut self.agents {
1204 if agent.status == AgentStatus::Finished {
1205 if is_recoverable_legacy_finished(agent) {
1206 if let Some(identity) = safe_legacy_identity(agent) {
1207 identities_changed |=
1208 compatibility_identities.insert(&agent.agent_id, &identity);
1209 newly_certified.push(agent.agent_id.clone());
1210 agent.status = AgentStatus::Active;
1211 agent.status_message =
1212 Some("legacy process identity recovered".to_string());
1213 }
1214 }
1215 continue;
1216 }
1217 if let Some(identity) = &agent.process_identity {
1218 identities_changed |= compatibility_identities.insert(&agent.agent_id, identity);
1219 }
1220 if process_identity_matches(agent, &compatibility_identities) {
1221 if agent.status == AgentStatus::Active && agent.last_active < worker_cutoff {
1230 if agent.transport.is_some() {
1231 agent.status = AgentStatus::Idle;
1232 agent.status_message = Some(TRANSPORT_IDLE.to_string());
1233 } else {
1234 agent.status = AgentStatus::Finished;
1235 agent.status_message = Some(WORKER_LEASE_EXPIRED.to_string());
1236 }
1237 }
1238 continue;
1239 }
1240 if let Some(identity) = safe_legacy_identity(agent) {
1241 identities_changed |= compatibility_identities.insert(&agent.agent_id, &identity);
1242 newly_certified.push(agent.agent_id.clone());
1243 continue;
1244 }
1245 {
1246 agent.status = AgentStatus::Finished;
1247 agent.status_message = Some("process identity no longer matches".to_string());
1248 }
1249 }
1250
1251 let mut finished_by_recency: Vec<_> = self
1255 .agents
1256 .iter()
1257 .filter(|agent| agent.status == AgentStatus::Finished && agent.last_active >= cutoff)
1258 .collect();
1259 finished_by_recency.sort_unstable_by(|left, right| {
1260 right
1261 .last_active
1262 .cmp(&left.last_active)
1263 .then_with(|| left.agent_id.cmp(&right.agent_id))
1264 });
1265 let retained_finished_ids: HashSet<String> = finished_by_recency
1266 .into_iter()
1267 .take(MAX_RETAINED_FINISHED_AGENTS)
1268 .map(|agent| agent.agent_id.clone())
1269 .collect();
1270
1271 self.agents.retain(|a| {
1274 let retire = a.status == AgentStatus::Finished
1275 && (a.last_active < cutoff || !retained_finished_ids.contains(&a.agent_id));
1276 if retire {
1277 crate::core::agent_budget::remove(&a.agent_id);
1278 }
1279 !retire
1280 });
1281 identities_changed |= compatibility_identities.retain_agents(self);
1282 if identities_changed && compatibility_identities.save().is_err() {
1283 for agent in &mut self.agents {
1284 if newly_certified.contains(&agent.agent_id) {
1285 agent.status = AgentStatus::Finished;
1286 agent.status_message =
1287 Some("legacy process identity could not be persisted".to_string());
1288 }
1289 }
1290 }
1291
1292 let now = UtcDateTime::now();
1294 self.scratchpad
1295 .retain(|entry| entry.expires_at.is_none_or(|exp| exp > now));
1296
1297 self.updated_at = UtcDateTime::now();
1298 }
1299
1300 #[cfg(any(test, feature = "test-support"))]
1301 pub fn save(&self) -> Result<(), String> {
1302 let dir = agents_dir()?;
1303 create_agents_dir(&dir)?;
1304
1305 let lock_path = dir.join("registry.lock");
1306 let _lock = FileLock::acquire(&lock_path)?;
1307
1308 self.save_locked(&dir)
1309 }
1310
1311 pub(super) fn save_locked(&self, dir: &std::path::Path) -> Result<(), String> {
1312 let path = dir.join("registry.json");
1313 save_registry_file(&path, self)
1314 }
1315
1316 pub fn load() -> Option<Self> {
1317 let dir = agents_dir().ok()?;
1318 let path = dir.join("registry.json");
1319 load_registry_file(&path).ok().flatten()
1320 }
1321
1322 pub fn load_or_create() -> Self {
1323 Self::load().unwrap_or_default()
1324 }
1325
1326 pub fn load_checked() -> Result<Self, String> {
1331 let dir = agents_dir()?;
1332 Ok(load_registry_file(&dir.join("registry.json"))?.unwrap_or_default())
1333 }
1334
1335 pub fn mutate_locked<T>(f: impl FnOnce(&mut Self) -> T) -> Result<(Self, T), String> {
1345 let dir = agents_dir()?;
1346 create_agents_dir(&dir)?;
1347
1348 let lock_path = dir.join("registry.lock");
1349 let _lock = FileLock::acquire(&lock_path)?;
1350
1351 let path = dir.join("registry.json");
1352 let mut registry = load_registry_file(&path)?.unwrap_or_default();
1353 let out = f(&mut registry);
1354 registry.save_locked(&dir)?;
1355 Ok((registry, out))
1356 }
1357}
1358
1359impl Default for AgentRegistry {
1360 fn default() -> Self {
1361 Self::new()
1362 }
1363}
1364
1365static ANNOUNCE: std::sync::OnceLock<fn()> = std::sync::OnceLock::new();
1369
1370pub fn register_announce(request: fn()) {
1372 let _ = ANNOUNCE.set(request);
1373}
1374
1375fn request_announce() {
1376 if let Some(request) = ANNOUNCE.get() {
1377 request();
1378 }
1379}
1380
1381#[cfg(test)]
1382#[path = "registry_tests.rs"]
1383mod tests;
1384
1385#[cfg(test)]
1386#[path = "registry_logical_session_tests.rs"]
1387mod logical_session_tests;
1388#[cfg(test)]
1390#[path = "registry_presence_tests.rs"]
1391mod presence_tests;
1392
1393#[path = "registry_logical_session.rs"]
1394mod logical_session;