1use lean_ctx::core::a2a::message::{MessagePriority, PrivacyLevel};
3use lean_ctx::core::a2a::task::TaskStore;
4use lean_ctx::core::agents::{
5 AgentDiary, AgentRegistry, AgentStatus, DiaryEntryType, ScratchpadEntry,
6};
7use lean_ctx::core::ocla::capsule::global_capsule_store;
8use lean_ctx::core::ocla::registry::OclaRegistry;
9use lean_ctx::core::ocla::types::{
10 AGENT_ENVELOPE_SCHEMA_VERSION, AgentEnvelope, AgentMessageRequest, OclaRequestContext,
11};
12
13#[path = "ctx_agent_claims.rs"]
14pub(crate) mod claims;
15#[path = "ctx_agent_control.rs"]
16mod control;
17#[path = "ctx_agent_lease.rs"]
18mod lease;
19use control::{control_status, lease_resource};
20#[cfg(test)]
21use lease::LeaseSettle;
22
23fn presence_ttl_hours() -> u64 {
24 lean_ctx::core::config::Config::load()
25 .agents
26 .presence_ttl_hours
27}
28
29fn scratchpad_default_ttl_hours() -> u64 {
30 lean_ctx::core::config::Config::load()
31 .agents
32 .scratchpad_default_ttl_hours
33}
34
35pub(crate) const ACTIONS: &[&str] = &[
38 "register",
39 "list",
40 "post",
41 "read",
42 "wait",
43 "status",
44 "info",
45 "handoff",
46 "sync",
47 "claim",
48 "release",
49 "claims",
50 "brief",
51 "return",
52 "export",
53 "diary",
54 "recall_diary",
55 "diaries",
56 "share_knowledge",
57 "receive_knowledge",
58 "poll_events",
59 "control_status",
60 "lease_acquire",
61 "lease_renew",
62 "lease_release",
63 "plan_claims",
64 "send",
65 "reply",
66 "inbox",
67 "ack",
68];
69
70pub fn handle_ack(
75 current_agent_id: Option<&str>,
76 directive_id: Option<&str>,
77 verdict: Option<&str>,
78 reason_code: Option<&str>,
79 reason: Option<&str>,
80) -> Result<String, String> {
81 use lean_ctx::core::agents::{DirectiveStore, Verdict};
82 let Some(agent_id) = current_agent_id else {
83 return Err("Error: agent must be registered first (use action=register)".to_string());
84 };
85 let Some(directive_id) = directive_id.map(str::trim).filter(|id| !id.is_empty()) else {
86 return Err("Error: ack needs directive_id".to_string());
87 };
88 let Some(verdict) = verdict.and_then(Verdict::parse) else {
89 return Err("Error: ack needs verdict=accept or verdict=refuse".to_string());
90 };
91 let answered = DirectiveStore::mutate(|registry, store| {
92 store.ack(
93 registry,
94 agent_id,
95 directive_id,
96 verdict,
97 reason_code,
98 reason,
99 )
100 })
101 .map_err(|error| format!("Error: {error}"))?;
102 Ok(match answered.reason_code {
103 Some(code) => format!(
104 "Directive {directive_id}: refused ({code}). Cloud is told on the next relay pass."
105 ),
106 None => {
107 format!("Directive {directive_id}: accepted. Cloud is told on the next relay pass.")
108 }
109 })
110}
111
112#[derive(Debug, Clone, Default)]
114pub struct MessageArgs {
115 pub message_type: Option<String>,
116 pub text: Option<String>,
117 pub to: Option<String>,
118 pub reply_to: Option<String>,
119 pub references: Vec<String>,
120 pub accept: Option<bool>,
122}
123
124impl MessageArgs {
125 fn untyped(text: Option<&str>, category: Option<&str>, to: Option<&str>) -> Self {
126 Self {
127 message_type: category.map(str::to_string),
128 text: text.map(str::to_string),
129 to: to.map(str::to_string),
130 ..Self::default()
131 }
132 }
133}
134
135pub fn handle_message(
140 action: &str,
141 args: &MessageArgs,
142 project_root: &str,
143 current_agent_id: Option<&str>,
144) -> String {
145 use lean_ctx_cloud::bus::messages_v2::{Extras, send};
146 let Some(agent) = current_agent_id else {
147 return "Error: agent must be registered first (use action=register)".to_string();
148 };
149 if action == "inbox" {
150 return match read_messages_as(agent, project_root, true) {
151 Ok(text) | Err(text) => text,
152 };
153 }
154 let Some(text) = args.text.as_deref() else {
155 return format!("Error: message is required for {action}");
156 };
157 let reply_to = args.reply_to.as_deref();
158 if action == "reply" && reply_to.is_none() {
159 return "Error: reply_to (the msg_… id of the message answered) is required".to_string();
160 }
161 let message_type = args
162 .message_type
163 .as_deref()
164 .or((action == "reply").then_some("answer"));
165 let extras = Extras {
166 to_worker: args.to.as_deref(),
167 reply_to,
168 accept: args.accept,
169 resource: args.references.first().map(String::as_str),
170 refs: &args.references,
171 };
172 match send(project_root, agent, message_type, text, extras) {
173 Ok(id) => format!(
174 "Queued [{}] {id}; the LeanCTX Cloud relay sends it to the vault's agents",
175 message_type.unwrap_or("?")
176 ),
177 Err(error) => format!("Error: {error}"),
178 }
179}
180
181pub fn handle_read(
188 message: Option<&str>,
189 current_agent_id: Option<&str>,
190 project_root: &str,
191) -> Result<String, String> {
192 if let Some(text) = message
194 && let Err(withheld) = lean_ctx::core::context_admission::carrier::admit_for_store(text)
195 {
196 return Err(format!("Error: {}", withheld.message("agent message")));
197 }
198 read_messages(current_agent_id, project_root)
199}
200
201fn read_messages(current_agent_id: Option<&str>, project_root: &str) -> Result<String, String> {
203 let Some(agent_id) = current_agent_id else {
204 return Err("Error: agent must be registered first (use action=register)".to_string());
205 };
206 let mut text = read_messages_as(agent_id, project_root, true)?;
207 if let Some(sessions) =
209 lean_ctx::core::providers::emspace::admitted_sessions_block(project_root)
210 {
211 text.push_str(&sessions);
212 }
213 Ok(text)
214}
215
216fn renewed_line(agent_id: &str) -> String {
218 format!(
219 "Note: the registration of {agent_id} had expired and was renewed; retry a claim refused meanwhile.\n"
220 )
221}
222
223pub(crate) const READ_PAGE_BYTES: usize = 6_000;
227
228fn render_message(m: &ScratchpadEntry, project_root: &str) -> String {
230 let next = lean_ctx_cloud::bus::task_events::TaskAction::of(m)
236 .map(|action| format!(" next: {}\n", action.call()))
237 .unwrap_or_default();
238 format!("{}{next}", render_text(m, project_root))
239}
240
241fn render_text(m: &ScratchpadEntry, project_root: &str) -> String {
243 let age = (lean_ctx_time::UtcDateTime::now() - m.timestamp).num_minutes();
244 if lean_ctx_cloud::bus::relay_v2::is_inbound(m) {
247 lean_ctx::core::context_admission::capture::note_origin(
249 &lean_ctx::core::context_admission::origin::SourceClass::External(
250 lean_ctx::core::context_admission::origin::InputOrigin::new(
251 lean_ctx::core::context_admission::origin::InputKind::BusMessage,
252 format!("cloud:{}", m.id),
253 ),
254 ),
255 );
256 return format!(
257 " [cloud] ({age}m ago):\n{}\n",
258 m.served_message(Some(project_root))
259 );
260 }
261 format!(
262 " [{}] from {} ({}m ago): {}\n",
263 m.category,
264 m.from_agent,
265 age,
266 m.served_message(Some(project_root))
267 )
268}
269
270pub fn read_messages_as(
276 agent_id: &str,
277 project_root: &str,
278 own_process: bool,
279) -> Result<String, String> {
280 let (shown, left) = match AgentRegistry::mutate_locked(|registry| {
281 if own_process {
282 registry.renew_worker(agent_id)?;
283 }
284 registry.read_unread_page(agent_id, project_root, READ_PAGE_BYTES, |m| {
285 render_message(m, project_root)
286 })
287 }) {
288 Ok((_, Ok(page))) => page,
289 Ok((_, Err(error))) => {
290 tracing::warn!("lean-ctx: message read rejected: {error}");
291 return Err(format!("Error: {error}"));
292 }
293 Err(e) => {
294 tracing::warn!(
295 "lean-ctx: failed to persist agent registry (messages may reappear): {e}"
296 );
297 return Err("Error: failed to read messages".to_string());
298 }
299 };
300
301 let mut renewed = if lean_ctx::core::agents::take_renewed(agent_id) {
302 renewed_line(agent_id)
303 } else {
304 String::new()
305 };
306 if own_process && let Some(note) = lean_ctx::core::binary_identity::replaced_note() {
308 renewed.insert_str(0, ¬e);
309 }
310 if let Some(lines) = lean_ctx::core::agents::pending_lines(
312 &lean_ctx::core::agents::DirectiveStore::load(),
313 agent_id,
314 ) {
315 renewed.push_str(&lines);
316 renewed.push('\n');
317 }
318 if shown.is_empty() {
319 return Ok(format!("{renewed}No new messages."));
320 }
321
322 let mut out = format!("{renewed}New messages ({}):\n", shown.len());
323 for line in &shown {
324 out.push_str(line);
325 }
326 if left > 0 {
327 out.push_str(&format!(
328 "{left} more unread (still unread): read again for the next ones.\n"
329 ));
330 }
331 Ok(out)
332}
333
334pub const WAIT_DEFAULT_SECS: u64 = 600;
336pub const WAIT_MAX_SECS: u64 = 1800;
337
338pub fn wait_timeout_line(secs: u64) -> String {
340 format!("No new messages within {secs}s.")
341}
342
343pub fn wait_messages(
349 agent_id: &str,
350 project_root: &str,
351 timeout_secs: Option<u64>,
352 own_process: bool,
353) -> Result<Option<String>, String> {
354 let secs = timeout_secs.unwrap_or(WAIT_DEFAULT_SECS).min(WAIT_MAX_SECS);
355 if own_process {
356 AgentRegistry::renew_worker_persistent(agent_id).map_err(|e| format!("Error: {e}"))?;
358 }
359 let arrived = AgentRegistry::wait_for_unread(
360 agent_id,
361 project_root,
362 std::time::Duration::from_secs(secs),
363 || {
364 if own_process && let Err(e) = AgentRegistry::renew_worker_persistent(agent_id) {
365 tracing::debug!("lean-ctx: wait keepalive for {agent_id}: {e}");
366 }
367 },
368 );
369 if arrived {
370 return read_messages_as(agent_id, project_root, own_process).map(Some);
371 }
372 lean_ctx::core::agents::friction::record_for(
373 lean_ctx::core::agents::friction::WAIT_TIMEOUT,
374 Some(agent_id),
375 Some(project_root),
376 );
377 Ok(None)
378}
379
380pub fn handle_wait(
383 current_agent_id: Option<&str>,
384 project_root: &str,
385 timeout_secs: Option<u64>,
386) -> Result<String, String> {
387 let Some(agent_id) = current_agent_id else {
388 return Err("Error: agent must be registered first (use action=register)".to_string());
389 };
390 let secs = timeout_secs.unwrap_or(WAIT_DEFAULT_SECS).min(WAIT_MAX_SECS);
391 Ok(
392 match wait_messages(agent_id, project_root, timeout_secs, true)? {
393 Some(text) => text,
394 None if lean_ctx::core::agents::take_renewed(agent_id) => {
395 format!("{}{}", renewed_line(agent_id), wait_timeout_line(secs))
396 }
397 None => wait_timeout_line(secs),
398 },
399 )
400}
401
402pub fn role_and_name(
408 role: Option<&str>,
409 name: Option<&str>,
410) -> (Option<String>, Option<String>, Vec<String>) {
411 let mut warnings = Vec::new();
412 let mut display = None;
413 if let Some(raw) = name {
414 display = lean_ctx::core::activity::session_name(raw);
415 if display.is_none() {
416 warnings.push("warning: name ignored (1-128 characters, one line)".to_owned());
417 }
418 }
419 let role_id = role.and_then(lean_ctx::core::agents::role_id);
420 if let (Some(raw), None) = (role, &role_id) {
421 warnings.push(format!(
422 "warning: unknown_role: {:?} is not a role id (coder, reviewer, tester, …); \
423 pass a display name as name=",
424 raw.chars().take(64).collect::<String>()
425 ));
426 if display.is_none() {
427 display = lean_ctx::core::activity::session_name(raw);
428 }
429 }
430 (role_id, display, warnings)
431}
432
433pub fn register(
437 agent_type: Option<&str>,
438 role: Option<&str>,
439 name: Option<&str>,
440 durable_identity_id: Option<&str>,
441 project_root: &str,
442) -> String {
443 let atype = agent_type.unwrap_or("unknown");
444 let (role, name, warnings) = role_and_name(role, name);
445 let stored = AgentRegistry::mutate_locked(|registry| {
446 registry.cleanup_stale(presence_ttl_hours());
447 let agent_id =
448 registry.register(atype, role.as_deref(), project_root, durable_identity_id)?;
449 if let Some(name) = &name {
450 registry.set_display_name(&agent_id, name);
451 }
452 let entry = registry.agents.iter().find(|a| a.agent_id == agent_id);
453 Ok((
454 agent_id.clone(),
455 entry.and_then(|a| a.role.clone()),
456 entry.and_then(|a| a.display_name.clone()),
457 ))
458 })
459 .and_then(|(_, stored)| stored);
460 match stored {
461 Ok((agent_id, role, name)) => {
462 lean_ctx_cloud::bus::presence::request_announce();
465 let mut text = format!(
468 "Agent registered: {agent_id} (type: {atype}, role: {}, name: {})",
469 role.as_deref().unwrap_or("none"),
470 name.as_deref().unwrap_or("none"),
471 );
472 for warning in warnings {
473 text.push('\n');
474 text.push_str(&warning);
475 }
476 if let Some(note) = lean_ctx::core::binary_identity::replaced_note() {
477 text.push('\n');
478 text.push_str(note.trim_end());
479 }
480 text
481 }
482 Err(e) => format!("Registration failed: {e}"),
483 }
484}
485
486#[derive(Debug, Clone, Copy, Default)]
490pub struct PostFields<'a> {
491 pub kind: Option<&'a str>,
492 pub task_id: Option<&'a str>,
493 pub thread: Option<&'a str>,
494}
495
496#[allow(clippy::too_many_arguments)]
500pub fn handle(
501 action: &str,
502 agent_type: Option<&str>,
503 role: Option<&str>,
504 durable_identity_id: Option<&str>,
505 project_root: &str,
506 current_agent_id: Option<&str>,
507 message: Option<&str>,
508 category: Option<&str>,
509 to_agent: Option<&str>,
510 status: Option<&str>,
511 privacy: Option<&str>,
512 priority: Option<&str>,
513 ttl_hours: Option<u64>,
514 format: Option<&str>,
515 write: bool,
516 filename: Option<&str>,
517 request_id: Option<&str>,
518) -> String {
519 handle_with(
520 action,
521 agent_type,
522 role,
523 durable_identity_id,
524 project_root,
525 current_agent_id,
526 message,
527 category,
528 to_agent,
529 status,
530 privacy,
531 priority,
532 ttl_hours,
533 format,
534 write,
535 filename,
536 request_id,
537 PostFields::default(),
538 )
539}
540
541fn checked_post_fields(
550 registry: &AgentRegistry,
551 sender: &str,
552 project_root: &str,
553 post: PostFields<'_>,
554 priority: &MessagePriority,
555) -> Result<(Option<String>, std::collections::BTreeMap<String, String>), String> {
556 use lean_ctx_cloud::bus::queen_kinds::{self, QueenKind, SenderRefusal};
557 let kind = QueenKind::from_input(post.kind)?;
558 if let Some(task_id) = post.task_id {
559 queen_kinds::check_task_id(task_id)?;
560 }
561 if let Some(thread) = post.thread {
562 queen_kinds::check_thread(thread)?;
563 }
564 if let Some(kind) = kind
565 && matches!(priority, MessagePriority::High | MessagePriority::Critical)
566 && !kind.allows_high()
567 {
568 return Err(format!(
569 "priority high is only for kinds conflict, escalate and stop, not {}",
570 kind.as_str()
571 ));
572 }
573 let now = lean_ctx_time::UtcDateTime::now().timestamp_millis();
576 queen_kinds::check_sender(registry, sender, kind, now).map_err(|refused| match refused {
577 SenderRefusal::NotQueen(why) | SenderRefusal::RateLimited(why) => why,
578 })?;
579 if kind.is_some()
580 && let Some(why) = lean_ctx::core::policy::cloud_orchestrator::network_refusal(Some(
581 std::path::Path::new(project_root),
582 ))
583 {
584 return Err(why);
585 }
586 let mut metadata = std::collections::BTreeMap::new();
587 if let Some(kind) = kind {
588 metadata.insert(queen_kinds::KIND_KEY.to_owned(), kind.as_str().to_owned());
589 }
590 if let Some(thread) = post.thread {
591 metadata.insert(queen_kinds::THREAD_KEY.to_owned(), thread.to_owned());
592 }
593 Ok((post.task_id.map(str::to_owned), metadata))
594}
595
596#[allow(clippy::too_many_arguments)]
598pub fn handle_with(
599 action: &str,
600 agent_type: Option<&str>,
601 role: Option<&str>,
602 durable_identity_id: Option<&str>,
603 project_root: &str,
604 current_agent_id: Option<&str>,
605 message: Option<&str>,
606 category: Option<&str>,
607 to_agent: Option<&str>,
608 status: Option<&str>,
609 privacy: Option<&str>,
610 priority: Option<&str>,
611 ttl_hours: Option<u64>,
612 format: Option<&str>,
613 write: bool,
614 filename: Option<&str>,
615 request_id: Option<&str>,
616 post: PostFields<'_>,
617) -> String {
618 let earlier = current_agent_id.filter(|_| action != "read").map(|agent| {
619 lean_ctx_cloud::background::earlier(&lean_ctx_cloud::bus::leases::caller(agent))
620 });
621 let answer = handle_action(
622 action,
623 agent_type,
624 role,
625 durable_identity_id,
626 project_root,
627 current_agent_id,
628 message,
629 category,
630 to_agent,
631 status,
632 privacy,
633 priority,
634 ttl_hours,
635 format,
636 write,
637 filename,
638 request_id,
639 post,
640 );
641 match earlier {
642 Some(earlier) => earlier.present(answer),
643 None => answer,
644 }
645}
646
647#[allow(clippy::too_many_arguments)]
648fn handle_action(
649 action: &str,
650 agent_type: Option<&str>,
651 role: Option<&str>,
652 durable_identity_id: Option<&str>,
653 project_root: &str,
654 current_agent_id: Option<&str>,
655 message: Option<&str>,
656 category: Option<&str>,
657 to_agent: Option<&str>,
658 status: Option<&str>,
659 privacy: Option<&str>,
660 priority: Option<&str>,
661 _ttl_hours: Option<u64>,
662 format: Option<&str>,
663 write: bool,
664 filename: Option<&str>,
665 request_id: Option<&str>,
666 post: PostFields<'_>,
667) -> String {
668 let admitted_message = match message
673 .map(lean_ctx::core::context_admission::carrier::admit_for_store)
674 .transpose()
675 {
676 Ok(admitted) => admitted,
677 Err(withheld) => return format!("Error: {}", withheld.message("agent message")),
678 };
679 let message = admitted_message.as_deref();
680 match action {
681 "register" => register(agent_type, role, None, durable_identity_id, project_root),
682
683 "list" => {
684 let registry = match AgentRegistry::mutate_locked(|registry| {
685 registry.cleanup_stale(presence_ttl_hours());
686 }) {
687 Ok((registry, ())) => registry,
688 Err(e) => {
689 tracing::warn!("lean-ctx: failed to persist agent registry: {e}");
690 AgentRegistry::load_or_create()
691 }
692 };
693
694 let agents = registry.list_active(Some(project_root));
695 let sessions =
696 lean_ctx::core::providers::emspace::admitted_sessions_block(project_root)
697 .unwrap_or_default();
698 if agents.is_empty() {
699 return format!("No active agents for this project.{sessions}");
700 }
701
702 let store = lean_ctx_cloud::CloudStore::open().ok();
705 let instance = store
706 .as_ref()
707 .and_then(|s| s.instance().ok().flatten())
708 .map(|record| record.instance_id);
709 let book = match (&store, &instance) {
710 (Some(store), Some(id)) => {
711 lean_ctx_cloud::workers::attach::list(store, id).unwrap_or_default()
712 }
713 _ => Vec::new(),
714 };
715 let mut roster = lean_ctx_cloud::workers::roster::render(
716 &agents,
717 instance.as_deref().map(|id| (id, book.as_slice())),
718 lean_ctx_time::UtcDateTime::now(),
719 );
720 if let Some(store) = &store {
721 roster.push_str(&lean_ctx_cloud::bus::presence::render_remote(
722 store.data_dir(),
723 lean_ctx_time::UtcDateTime::now(),
724 ));
725 }
726 roster.push_str(&sessions);
727 roster
728 }
729
730 "post" => {
731 let Some(msg) = message else {
732 return "Error: message is required for post".to_string();
733 };
734 let cat = category.unwrap_or("status");
735 let from = current_agent_id.unwrap_or("anonymous");
736 let msg_privacy = privacy.map_or(PrivacyLevel::Team, PrivacyLevel::parse_str);
737 let msg_priority = priority.map_or(MessagePriority::Normal, MessagePriority::parse_str);
738 let ttl_hours = _ttl_hours.or(Some(scratchpad_default_ttl_hours()));
739 if msg_privacy == PrivacyLevel::Private && to_agent.is_none() {
740 return "Error: private messages require to_agent".to_string();
741 }
742 let registry = AgentRegistry::load_or_create();
743 let to_agent = match to_agent
746 .map(|t| lean_ctx_cloud::bus::queen_kinds::resolve_to(®istry, t))
747 .transpose()
748 {
749 Ok(to) => to,
750 Err(refused) => return format!("Error: not posted: {refused}"),
751 };
752 let to_agent = to_agent.as_deref();
753 let (task_id, metadata) =
754 match checked_post_fields(®istry, from, project_root, post, &msg_priority) {
755 Ok(fields) => fields,
756 Err(refused) => return format!("Error: not posted: {refused}"),
757 };
758 let msg = {
762 match lean_ctx_cloud::bus::person_rules::check_local_post(
765 ®istry,
766 current_agent_id,
767 cat,
768 to_agent,
769 msg,
770 ) {
771 Ok(text) => text,
772 Err(refused) => return format!("Error: not posted: {refused}"),
773 }
774 };
775 let msg = msg.as_str();
776 let request = AgentMessageRequest {
777 project_root: project_root.to_string(),
778 from_agent_id: from.to_string(),
779 to_agent_id: to_agent.map(str::to_string),
780 category: cat.to_string(),
781 message: msg.to_string(),
782 privacy: msg_privacy,
783 priority: msg_priority,
784 ttl_hours,
785 request_id: request_id.map(str::to_string),
786 task_id,
787 metadata,
788 };
789 match OclaRegistry::global().agent_gateway.route_message(&request) {
790 Ok(msg_id) => {
791 let target = to_agent.unwrap_or("all agents (broadcast)");
792 format!("Posted [{cat}] to {target}: {msg} (id: {msg_id})")
793 }
794 Err(e) => format!("Post failed: {e}"),
795 }
796 }
797
798 "read" => match read_messages(current_agent_id, project_root) {
801 Ok(text) | Err(text) => text,
802 },
803
804 "wait" => match handle_wait(current_agent_id, project_root, None) {
807 Ok(text) | Err(text) => text,
808 },
809
810 "send" => handle_message(
813 "send",
814 &MessageArgs::untyped(message, category, to_agent),
815 project_root,
816 current_agent_id,
817 ),
818 "reply" => handle_message(
819 "reply",
820 &MessageArgs::untyped(message, category, to_agent),
821 project_root,
822 current_agent_id,
823 ),
824 "inbox" => handle_message(
825 "inbox",
826 &MessageArgs::untyped(message, category, to_agent),
827 project_root,
828 current_agent_id,
829 ),
830
831 "status" => {
832 let Some(agent_id) = current_agent_id else {
833 return "Error: agent must be registered first".to_string();
834 };
835 let new_status = match status {
836 Some("active") => AgentStatus::Active,
837 Some("idle") => AgentStatus::Idle,
838 Some("finished") => AgentStatus::Finished,
839 Some(other) => {
840 return format!("Unknown status: {other}. Use: active, idle, finished");
841 }
842 None => return "Error: status value is required".to_string(),
843 };
844 let status_msg = message;
845
846 match AgentRegistry::mutate_locked(|registry| {
847 registry.set_status_by_agent(agent_id, new_status.clone(), status_msg)
848 })
849 .and_then(|(_, result)| result)
850 {
851 Ok(()) => {
852 let released = if matches!(new_status, AgentStatus::Finished) {
854 lean_ctx::core::unit_claims::release_agent(agent_id)
855 } else {
856 0
857 };
858 format!(
859 "Status updated: {} → {}{}{}",
860 agent_id,
861 new_status,
862 status_msg.map(|m| format!(" ({m})")).unwrap_or_default(),
863 if released > 0 {
864 format!("; released {released} unit claim(s)")
865 } else {
866 String::new()
867 }
868 )
869 }
870 Err(e) => format!("Status update rejected: {e}"),
871 }
872 }
873
874 "claims" => claims::handle_claims(project_root, current_agent_id),
877
878 "plan_claims" => {
879 let holder = current_agent_id
880 .map(str::to_string)
881 .unwrap_or_else(crate::tools::claims_gate::process_agent);
882 claims::plan(project_root, &holder, message)
883 }
884
885 "info" => {
886 let registry = AgentRegistry::mutate_locked(|registry| {
887 registry.cleanup_stale(presence_ttl_hours());
888 })
889 .map(|(registry, ())| registry)
890 .unwrap_or_else(|_| AgentRegistry::load_or_create());
891 let total = registry.agents.len();
892 let active = registry.list_active(None).len();
893 let messages = registry.scratchpad.len();
894 format!(
895 "Agent Registry: {total} total, {active} active, {messages} scratchpad entries\nLast updated: {}",
896 registry.updated_at.format("%Y-%m-%d %H:%M UTC")
897 )
898 }
899
900 "handoff" => {
901 let Some(from) = current_agent_id else {
902 return "Error: agent must be registered first".to_string();
903 };
904 let Some(target) = to_agent else {
905 return "Error: to_agent is required for handoff".to_string();
906 };
907 let summary = message.unwrap_or("(no summary provided)");
908 let scratchpad_ttl = scratchpad_default_ttl_hours();
909 if target.starts_with("wkr_") {
914 use lean_ctx_cloud::bus::messages_v2::{Extras, send};
915 let extras = Extras {
916 to_worker: Some(target),
917 ..Extras::default()
918 };
919 return match send(project_root, from, Some("handoff"), summary, extras) {
920 Ok(id) => {
921 let waiting = format!("handoff to {target} offered through LeanCTX Cloud");
922 let _ = AgentRegistry::mutate_locked(|registry| {
923 registry.set_status(from, AgentStatus::Idle, Some(&waiting))
924 });
925 format!(
926 "Handoff offered (cloud): {from} → {target} message={id}; \
927 {target} answers it (accept or decline)\nSummary: {summary}"
928 )
929 }
930 Err(error) => format!("Handoff rejected: {error}"),
931 };
932 }
933
934 if let Err(error) = AgentRegistry::mutate_locked(|registry| {
935 registry.post_message_scoped(
939 Some(project_root),
940 from,
941 Some(target),
942 "handoff",
943 &format!("HANDOFF from {from}: {summary}"),
944 PrivacyLevel::Team,
945 MessagePriority::Normal,
946 Some(scratchpad_ttl),
947 )?;
948 registry.set_status(from, AgentStatus::Finished, Some("handed off"))
949 })
950 .and_then(|(_, result)| result)
951 {
952 return format!("Handoff rejected: {error}");
953 }
954
955 let handoff_message = format!("HANDOFF: {summary}");
957 let capsule_ref = global_capsule_store().register(handoff_message.as_bytes());
958 let mut envelope = AgentEnvelope {
959 schema_version: AGENT_ENVELOPE_SCHEMA_VERSION,
960 relay_id: String::new(),
961 context: OclaRequestContext::new(
962 format!("handoff:{capsule_ref}"),
963 project_root.to_string(),
964 from.to_string(),
965 capsule_ref.clone(),
966 None,
967 Some(format!("handoff:{from}:{target}")),
968 ),
969 from_agent_id: from.to_string(),
970 to_agent_id: target.to_string(),
971 capsule_ref,
972 budget_tokens: handoff_message.len().max(1) as u64,
973 };
974 if let Err(error) = envelope.assign_relay_id() {
975 tracing::debug!("OCLA relay setup failed (non-fatal): {error}");
976 } else if let Err(error) = OclaRegistry::global().agent_gateway.relay_agent(envelope) {
977 tracing::debug!("OCLA relay failed (non-fatal): {error}");
978 }
979
980 lean_ctx::core::scent_field::deposit_for(
983 project_root,
984 from,
985 lean_ctx::core::scent_field::ScentKind::Done,
986 summary,
987 1.0,
988 );
989
990 format!("Handoff complete: {from} → {target}\nSummary: {summary}")
991 }
992
993 "claim" => {
997 let Some(target) = message else {
998 return "Error: message (the claim target, e.g. a file path or task label) is required for claim".to_string();
999 };
1000 let agent = current_agent_id.map_or_else(
1001 || lean_ctx::core::scent_field::scent_agent_id().to_string(),
1002 str::to_string,
1003 );
1004 let normalized = lean_ctx::core::pathutil::normalize_tool_path(target);
1005 match lean_ctx::core::scent_field::claim(project_root, &agent, &normalized) {
1006 Ok(()) => {
1007 format!("Claimed: {normalized} (by {agent}, decays in ~10m unless re-claimed)")
1008 }
1009 Err(e) => format!("Claim REJECTED: {normalized} — {e}"),
1010 }
1011 }
1012
1013 "release" => {
1015 let Some(target) = message else {
1016 return "Error: message (the claim target) is required for release".to_string();
1017 };
1018 let agent = current_agent_id.map_or_else(
1019 || lean_ctx::core::scent_field::scent_agent_id().to_string(),
1020 str::to_string,
1021 );
1022 let normalized = lean_ctx::core::pathutil::normalize_tool_path(target);
1023 lean_ctx::core::scent_field::release(project_root, &agent, &normalized);
1024 format!("Released: {normalized}")
1025 }
1026
1027 "brief" => {
1031 let Some(task) = message else {
1032 return "Error: message (the sub-agent task) is required for brief".to_string();
1033 };
1034 let budget = priority
1035 .and_then(|p| p.parse::<usize>().ok())
1036 .unwrap_or(2000);
1037 let Some(knowledge) = lean_ctx::core::knowledge::ProjectKnowledge::load(project_root)
1038 else {
1039 return "No knowledge stored for this project yet — a briefing pack needs facts. Use ctx_knowledge(action=\"remember\") first.".to_string();
1040 };
1041 let pack =
1043 lean_ctx::core::subagent_contract::build_briefing_pack(&knowledge, task, budget);
1044 match lean_ctx::core::subagent_contract::serialize_pack(&pack) {
1045 Ok(json) => json,
1046 Err(e) => format!("Error: {e}"),
1047 }
1048 }
1049
1050 "return" => {
1054 let Some(report) = message else {
1055 return "Error: message (the sub-agent report) is required for return".to_string();
1056 };
1057 let (facts, rejected) = lean_ctx::core::subagent_contract::parse_return_lines(report);
1058 if facts.is_empty() {
1059 return format!(
1060 "No contract-formatted lines found ({} rejected). Expected 'category/key: value' per line.",
1061 rejected.len()
1062 );
1063 }
1064
1065 let session_label = current_agent_id.unwrap_or("subagent");
1066 let policy = match crate::tools::knowledge_shared::load_policy_or_error() {
1067 Ok(p) => p,
1068 Err(e) => return e,
1069 };
1070 let count = facts.len();
1071 let res = lean_ctx::core::knowledge::ProjectKnowledge::mutate_locked(
1072 project_root,
1073 |knowledge| {
1074 for f in &facts {
1075 knowledge.remember(
1076 &f.category,
1077 &f.key,
1078 &f.value,
1079 session_label,
1080 0.8,
1081 &policy,
1082 );
1083 }
1084 },
1085 );
1086 match res {
1087 Ok(_) => {
1088 let mut out = format!(
1089 "Return synthesis: {count} fact(s) distilled into parent knowledge"
1090 );
1091 if !rejected.is_empty() {
1092 out.push_str(&format!(
1093 "\n{} line(s) rejected (not 'category/key: value'):",
1094 rejected.len()
1095 ));
1096 for r in rejected.iter().take(5) {
1097 out.push_str(&format!("\n ✗ {r}"));
1098 }
1099 }
1100 out
1101 }
1102 Err(e) => format!("Error: knowledge store update failed: {e}"),
1103 }
1104 }
1105
1106 "sync" => {
1107 let registry = AgentRegistry::mutate_locked(|registry| {
1108 registry.cleanup_stale(presence_ttl_hours());
1109 })
1110 .map(|(registry, ())| registry)
1111 .unwrap_or_else(|_| AgentRegistry::load_or_create());
1112 let pending_count = current_agent_id.map_or(0, |id| {
1113 registry
1114 .scratchpad
1115 .iter()
1116 .filter(|e| {
1117 !e.read_by.contains(&id.to_string())
1118 && e.from_agent != id
1119 && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(id))
1120 && e.project_root.as_deref().is_some_and(|own| {
1121 lean_ctx::core::pathutil::same_project(own, project_root)
1122 })
1123 })
1124 .count()
1125 });
1126 let agents = registry.list_active(Some(project_root));
1127
1128 if agents.is_empty() {
1129 return "No active agents to sync with.".to_string();
1130 }
1131
1132 let shared_dir = lean_ctx::core::data_dir::lean_ctx_data_dir()
1134 .unwrap_or_default()
1135 .join("agents")
1136 .join("shared")
1137 .join(lean_ctx::core::project_hash::hash_project_root(
1138 project_root,
1139 ));
1140
1141 let shared_count = if shared_dir.exists() {
1142 std::fs::read_dir(&shared_dir).map_or(0, std::iter::Iterator::count)
1143 } else {
1144 0
1145 };
1146
1147 let mut out = "Multi-Agent Sync Status:\n".to_string();
1148 out.push_str(&format!(" Active agents: {}\n", agents.len()));
1149 for a in &agents {
1150 let role = a.role.as_deref().unwrap_or("-");
1151 let age = (lean_ctx_time::UtcDateTime::now() - a.last_active).num_minutes();
1152 out.push_str(&format!(
1153 " {} [{}] role={} ({}m ago)\n",
1154 a.agent_id, a.agent_type, role, age
1155 ));
1156 }
1157 out.push_str(&format!(" Pending messages: {pending_count}\n"));
1158 out.push_str(&format!(" Shared contexts: {shared_count}\n"));
1159
1160 let scents = lean_ctx::core::scent_field::sync_block(project_root);
1163 if !scents.is_empty() {
1164 out.push_str(&scents);
1165 }
1166 out
1167 }
1168
1169 "control_status" => control_status(project_root, current_agent_id),
1174
1175 "export" => {
1176 let Some(agent_id) = current_agent_id else {
1177 return "Error: agent must be registered first (use action=register)".to_string();
1178 };
1179
1180 fn privacy_label(p: &PrivacyLevel) -> &'static str {
1181 match p {
1182 PrivacyLevel::Public => "public",
1183 PrivacyLevel::Team => "team",
1184 PrivacyLevel::Private => "private",
1185 }
1186 }
1187
1188 fn priority_label(p: &MessagePriority) -> &'static str {
1189 match p {
1190 MessagePriority::Low => "low",
1191 MessagePriority::Normal => "normal",
1192 MessagePriority::High => "high",
1193 MessagePriority::Critical => "critical",
1194 }
1195 }
1196
1197 fn maybe_redact(s: &str, should_redact: bool) -> String {
1198 if should_redact {
1199 lean_ctx::core::redaction::redact_text(s)
1200 } else {
1201 s.to_string()
1202 }
1203 }
1204
1205 #[derive(serde::Serialize)]
1206 struct ExportAgentV1 {
1207 agent_id: String,
1208 agent_type: String,
1209 role: Option<String>,
1210 status: String,
1211 status_message: Option<String>,
1212 started_at: String,
1213 last_active: String,
1214 pid: u32,
1215 }
1216
1217 #[derive(serde::Serialize)]
1218 struct ExportMessageV1 {
1219 id: String,
1220 from_agent: String,
1221 to_agent: Option<String>,
1222 category: String,
1223 privacy: String,
1224 priority: String,
1225 message: String,
1226 metadata: std::collections::BTreeMap<String, String>,
1227 timestamp: String,
1228 expires_at: Option<String>,
1229 read_by_count: usize,
1230 }
1231
1232 #[derive(serde::Serialize)]
1233 struct ExportTaskV1 {
1234 id: String,
1235 from_agent: String,
1236 to_agent: String,
1237 state: String,
1238 description: String,
1239 created_at: String,
1240 updated_at: String,
1241 messages: usize,
1242 artifacts: usize,
1243 transitions: usize,
1244 }
1245
1246 #[derive(serde::Serialize)]
1247 struct ExportDiaryEntryV1 {
1248 entry_type: String,
1249 content: String,
1250 context: Option<String>,
1251 timestamp: String,
1252 }
1253
1254 #[derive(serde::Serialize)]
1255 struct ExportDiaryV1 {
1256 agent_id: String,
1257 agent_type: String,
1258 project_root: String,
1259 updated_at: String,
1260 entries: Vec<ExportDiaryEntryV1>,
1261 }
1262
1263 #[derive(serde::Serialize)]
1264 struct A2ASnapshotV1 {
1265 schema_version: u32,
1266 created_at: String,
1267 project_root: String,
1268 agent_id: String,
1269 agents: Vec<ExportAgentV1>,
1270 messages: Vec<ExportMessageV1>,
1271 tasks: Vec<ExportTaskV1>,
1272 diary: Option<ExportDiaryV1>,
1273 }
1274
1275 let privacy_mode = privacy.unwrap_or("redacted");
1276 let allow_full = privacy_mode == "full"
1277 && !lean_ctx::core::redaction::redaction_enabled_for_active_role();
1278 let should_redact = !allow_full;
1279
1280 let now = lean_ctx_time::UtcDateTime::now();
1281 let mut registry = AgentRegistry::load_or_create();
1282 registry.cleanup_stale(presence_ttl_hours());
1283
1284 let mut agents: Vec<ExportAgentV1> = registry
1285 .list_active(Some(project_root))
1286 .into_iter()
1287 .map(|a| ExportAgentV1 {
1288 agent_id: a.agent_id.clone(),
1289 agent_type: a.agent_type.clone(),
1290 role: a.role.clone(),
1291 status: a.status.to_string(),
1292 status_message: a.status_message.clone(),
1293 started_at: a.started_at.to_rfc3339(),
1294 last_active: a.last_active.to_rfc3339(),
1295 pid: a.pid,
1296 })
1297 .collect();
1298 agents.sort_by(|a, b| a.agent_id.cmp(&b.agent_id));
1299
1300 let mut messages: Vec<ExportMessageV1> = registry
1301 .scratchpad
1302 .iter()
1303 .filter(|e| {
1304 e.project_root.as_deref().is_some_and(|own| {
1305 lean_ctx::core::pathutil::same_project(own, project_root)
1306 }) && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
1307 })
1308 .take(200)
1309 .map(|m| ExportMessageV1 {
1310 id: m.id.clone(),
1311 from_agent: m.from_agent.clone(),
1312 to_agent: m.to_agent.clone(),
1313 category: m.category.clone(),
1314 privacy: privacy_label(&m.privacy).to_string(),
1315 priority: priority_label(&m.priority).to_string(),
1316 message: maybe_redact(&m.served_message(Some(project_root)), should_redact),
1317 metadata: m
1319 .metadata
1320 .iter()
1321 .filter(|(k, _)| k.as_str() != lean_ctx::core::agents::BINDING_METADATA_KEY)
1322 .map(|(k, v)| (k.clone(), maybe_redact(v, should_redact)))
1323 .collect(),
1324 timestamp: m.timestamp.to_rfc3339(),
1325 expires_at: m.expires_at.map(lean_ctx_time::UtcDateTime::to_rfc3339),
1326 read_by_count: m.read_by.len(),
1327 })
1328 .collect();
1329 messages.sort_by(|a, b| a.timestamp.cmp(&b.timestamp).then_with(|| a.id.cmp(&b.id)));
1330
1331 const EXPORT_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
1336 let tasks = TaskStore::default_path().and_then(|path| {
1337 TaskStore::mutate_locked_within(&path, EXPORT_LOCK_WAIT, |task_store| {
1338 task_store.cleanup_old(72);
1339 Ok::<_, std::io::Error>(
1340 task_store
1341 .tasks_for_agent(agent_id)
1342 .into_iter()
1343 .take(200)
1344 .map(|t| ExportTaskV1 {
1345 id: t.id.clone(),
1346 from_agent: t.from_agent.clone(),
1347 to_agent: t.to_agent.clone(),
1348 state: t.state.to_string(),
1349 description: maybe_redact(&t.served_description(), should_redact),
1350 created_at: t.created_at.to_rfc3339(),
1351 updated_at: t.updated_at.to_rfc3339(),
1352 messages: t.messages.len(),
1353 artifacts: t.artifacts.len(),
1354 transitions: t.history.len(),
1355 })
1356 .collect::<Vec<ExportTaskV1>>(),
1357 )
1358 })
1359 });
1360 let mut tasks = match tasks {
1361 Ok(tasks) => tasks,
1362 Err(error) => {
1363 tracing::warn!("lean-ctx: failed to read task store: {error}");
1364 return "Error: task storage unavailable".to_string();
1365 }
1366 };
1367 tasks.sort_by(|a, b| {
1368 b.updated_at
1369 .cmp(&a.updated_at)
1370 .then_with(|| a.id.cmp(&b.id))
1371 });
1372
1373 let diary =
1374 AgentDiary::load_for_project(agent_id, project_root).map(|d| ExportDiaryV1 {
1375 agent_id: d.agent_id,
1376 agent_type: d.agent_type,
1377 project_root: d.project_root,
1378 updated_at: d.updated_at.to_rfc3339(),
1379 entries: d
1380 .entries
1381 .iter()
1382 .rev()
1383 .take(25)
1384 .rev()
1385 .map(|e| ExportDiaryEntryV1 {
1386 entry_type: e.entry_type.to_string(),
1387 content: maybe_redact(&e.content, should_redact),
1388 context: e.context.as_deref().map(|c| maybe_redact(c, should_redact)),
1389 timestamp: e.timestamp.to_rfc3339(),
1390 })
1391 .collect(),
1392 });
1393
1394 let payload = A2ASnapshotV1 {
1395 schema_version: lean_ctx::core::contracts::A2A_SNAPSHOT_V1_SCHEMA_VERSION,
1396 created_at: now.to_rfc3339(),
1397 project_root: project_root.to_string(),
1398 agent_id: agent_id.to_string(),
1399 agents,
1400 messages,
1401 tasks,
1402 diary,
1403 };
1404
1405 let json = serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".to_string());
1406
1407 if write {
1408 let name = filename.map_or_else(
1409 || format!("a2a-snapshot-v1_{}.json", now.format("%Y%m%d_%H%M%S")),
1410 str::to_string,
1411 );
1412 let out_path =
1413 match write_a2a_snapshot(std::path::Path::new(project_root), &name, &json) {
1414 Ok(path) => path,
1415 Err(e) => return format!("Error: write snapshot: {e}"),
1416 };
1417
1418 return format!(
1419 "A2A snapshot exported: {}\n agents: {}\n messages: {}\n tasks: {}",
1420 out_path.display(),
1421 payload.agents.len(),
1422 payload.messages.len(),
1423 payload.tasks.len()
1424 );
1425 }
1426
1427 match format.unwrap_or("json") {
1428 "text" => format!(
1429 "A2A snapshot (v1)\n agents: {}\n messages: {}\n tasks: {}",
1430 payload.agents.len(),
1431 payload.messages.len(),
1432 payload.tasks.len()
1433 ),
1434 _ => json,
1435 }
1436 }
1437
1438 "diary" => {
1439 let Some(agent_id) = current_agent_id else {
1440 return "Error: agent must be registered first".to_string();
1441 };
1442 let Some(content) = message else {
1443 return "Error: message is required for diary entry".to_string();
1444 };
1445 let entry_type = match category.unwrap_or("progress") {
1446 "discovery" | "found" => DiaryEntryType::Discovery,
1447 "decision" | "decided" => DiaryEntryType::Decision,
1448 "blocker" | "blocked" => DiaryEntryType::Blocker,
1449 "progress" | "done" => DiaryEntryType::Progress,
1450 "insight" => DiaryEntryType::Insight,
1451 other => {
1452 return format!(
1453 "Unknown diary type: {other}. Use: discovery, decision, blocker, progress, insight"
1454 );
1455 }
1456 };
1457 let atype = agent_type.unwrap_or("unknown");
1458 let mut diary = AgentDiary::load_or_create(agent_id, atype, project_root);
1459 let context_str = to_agent;
1460 diary.add_entry(entry_type.clone(), content, context_str);
1461 match diary.save() {
1462 Ok(()) => format!("Diary entry [{entry_type}] added: {content}"),
1463 Err(e) => format!("Diary entry added but save failed: {e}"),
1464 }
1465 }
1466
1467 "recall_diary" | "diary_recall" => {
1468 let Some(agent_id) = current_agent_id else {
1469 let diaries = AgentDiary::list_for_project(project_root);
1470 if diaries.is_empty() {
1471 return "No agent diaries found.".to_string();
1472 }
1473 let mut out = format!("Agent Diaries ({}):\n", diaries.len());
1474 for (id, count, updated) in &diaries {
1475 let age = (lean_ctx_time::UtcDateTime::now() - *updated).num_minutes();
1476 out.push_str(&format!(" {id}: {count} entries ({age}m ago)\n"));
1477 }
1478 return out;
1479 };
1480 match AgentDiary::load_for_project(agent_id, project_root) {
1481 Some(diary) => diary.format_summary(),
1482 None => format!("No diary found for agent '{agent_id}'."),
1483 }
1484 }
1485
1486 "diaries" => {
1487 let diaries = AgentDiary::list_for_project(project_root);
1488 if diaries.is_empty() {
1489 return "No agent diaries found.".to_string();
1490 }
1491 let mut out = format!("Agent Diaries ({}):\n", diaries.len());
1492 for (id, count, updated) in &diaries {
1493 let age = (lean_ctx_time::UtcDateTime::now() - *updated).num_minutes();
1494 out.push_str(&format!(" {id}: {count} entries ({age}m ago)\n"));
1495 }
1496 out
1497 }
1498
1499 "share_knowledge" => {
1500 let cat = category.unwrap_or("general");
1501 let Some(msg_text) = message else {
1502 return "Error: message required (format: key1=value1;key2=value2)".to_string();
1503 };
1504 let facts: Vec<(String, String)> = msg_text
1505 .split(';')
1506 .filter_map(|kv| {
1507 let (k, v) = kv.split_once('=')?;
1508 Some((k.trim().to_string(), v.trim().to_string()))
1509 })
1510 .collect();
1511 if facts.is_empty() {
1512 return "Error: no valid key=value pairs found".to_string();
1513 }
1514 let Some(from) = current_agent_id else {
1515 return "Error: agent must be registered first".to_string();
1516 };
1517 match AgentRegistry::mutate_locked(|registry| {
1519 registry.require_active_for_presence(from, "sharing knowledge")?;
1520 registry.share_knowledge(project_root, from, cat, &facts)
1521 })
1522 .and_then(|(_, shared)| shared)
1523 {
1524 Ok(count) => format!("Shared {count} facts in category '{cat}' with this project"),
1525 Err(e) => format!("Share failed: {e}"),
1526 }
1527 }
1528
1529 "receive_knowledge" => {
1530 let Some(agent_id) = current_agent_id else {
1531 return "Error: agent must be registered first".to_string();
1532 };
1533 let facts = match AgentRegistry::mutate_locked(|registry| {
1534 registry.require_active_for_presence(agent_id, "receiving knowledge")?;
1535 registry.receive_shared_knowledge(project_root, agent_id)
1536 })
1537 .and_then(|(_, facts)| facts)
1538 {
1539 Ok(facts) => facts,
1540 Err(e) => return format!("Receive failed: {e}"),
1541 };
1542 if facts.is_empty() {
1543 return "No new shared knowledge.".to_string();
1544 }
1545 let mut out = format!("Received {} facts:\n", facts.len());
1546 for f in &facts {
1547 let age = (lean_ctx_time::UtcDateTime::now() - f.timestamp).num_minutes();
1548 out.push_str(&format!(
1549 " [{}] {} (from {}, {}m ago)\n",
1550 f.category, f.text, f.from_agent, age
1551 ));
1552 }
1553 out
1554 }
1555
1556 "poll_events" => {
1557 let Some(agent_id) = current_agent_id else {
1558 return "Error: agent must be registered first".to_string();
1559 };
1560 let workspace_id = to_agent.unwrap_or(project_root);
1561 let channel_id = category.unwrap_or("default");
1562 let since_id: i64 = message.and_then(|s| s.parse().ok()).unwrap_or(0);
1563 let limit: usize = _ttl_hours.unwrap_or(50) as usize;
1564
1565 let rt = lean_ctx::core::context_os::runtime();
1566 let events = rt.bus.read(workspace_id, channel_id, since_id, limit);
1567
1568 let filter = lean_ctx::core::context_os::TopicFilter {
1569 agent_id: Some(agent_id.to_string()),
1570 kinds: privacy.and_then(|s| {
1571 let kinds: Vec<_> = s
1572 .split(',')
1573 .map(|k| lean_ctx::core::context_os::ContextEventKindV1::parse(k.trim()))
1574 .collect();
1575 if kinds.is_empty() { None } else { Some(kinds) }
1576 }),
1577 ..Default::default()
1578 };
1579
1580 let filtered: Vec<_> = events.into_iter().filter(|e| filter.matches(e)).collect();
1581 if filtered.is_empty() {
1582 return format!("No new events since id={since_id} for {agent_id}.");
1583 }
1584
1585 let mut out = format!("Events ({}, since={since_id}):\n", filtered.len());
1586 for ev in &filtered {
1587 let actor = ev.actor.as_deref().unwrap_or("-");
1588 out.push_str(&format!(
1589 " #{} [{}] actor={} cl={} ({})\n",
1590 ev.id,
1591 ev.kind,
1592 actor,
1593 ev.consistency_level,
1594 ev.timestamp.format("%H:%M:%S")
1595 ));
1596 }
1597 if let Some(last) = filtered.last() {
1598 out.push_str(&format!("cursor={}", last.id));
1599 }
1600 out
1601 }
1602
1603 "lease_acquire" => lease::acquire(project_root, current_agent_id, message, _ttl_hours),
1605 "lease_release" => lease::release(project_root, current_agent_id, message, category),
1606 "lease_renew" => lease::renew(
1607 project_root,
1608 current_agent_id,
1609 message,
1610 category,
1611 _ttl_hours,
1612 ),
1613
1614 "ack" => match handle_ack(current_agent_id, message, category, status, None) {
1618 Ok(text) | Err(text) => text,
1619 },
1620
1621 _ => format!("Unknown action: {action}. Use: {}", ACTIONS.join(", ")),
1622 }
1623}
1624
1625fn write_a2a_snapshot(
1629 project_root: &std::path::Path,
1630 name: &str,
1631 json: &str,
1632) -> Result<std::path::PathBuf, String> {
1633 lean_ctx::core::context_proof::proof_destination(project_root, name)?.write(json)
1634}
1635
1636#[cfg(test)]
1637#[path = "ctx_agent_tests.rs"]
1638mod tests;
1639