1use crate::core::a2a::message::{MessagePriority, PrivacyLevel};
2use crate::core::a2a::task::TaskStore;
3use crate::core::agents::{
4 AgentDiary, AgentRegistry, AgentStatus, DiaryEntryType, ScratchpadEntry,
5};
6use crate::core::ocla::capsule::global_capsule_store;
7use crate::core::ocla::registry::OclaRegistry;
8use crate::core::ocla::types::{
9 AGENT_ENVELOPE_SCHEMA_VERSION, AgentEnvelope, AgentMessageRequest, OclaRequestContext,
10};
11
12#[path = "ctx_agent_control.rs"]
13mod control;
14use control::{control_status, lease_resource};
15
16fn presence_ttl_hours() -> u64 {
17 crate::core::config::Config::load()
18 .agents
19 .presence_ttl_hours
20}
21
22fn scratchpad_default_ttl_hours() -> u64 {
23 crate::core::config::Config::load()
24 .agents
25 .scratchpad_default_ttl_hours
26}
27
28pub(crate) const ACTIONS: &[&str] = &[
31 "register",
32 "list",
33 "post",
34 "read",
35 "wait",
36 "status",
37 "info",
38 "handoff",
39 "sync",
40 "claim",
41 "release",
42 "brief",
43 "return",
44 "export",
45 "diary",
46 "recall_diary",
47 "diaries",
48 "share_knowledge",
49 "receive_knowledge",
50 "poll_events",
51 "control_status",
52 "lease_acquire",
53 "lease_renew",
54 "lease_release",
55 "send",
56 "reply",
57 "inbox",
58];
59
60#[derive(Debug, Clone, Default)]
62pub struct MessageArgs {
63 pub message_type: Option<String>,
64 pub text: Option<String>,
65 pub to: Option<String>,
66 pub to_instance: Option<String>,
67 pub reply_to: Option<String>,
68 pub deadline_hours: Option<u64>,
69 pub swarm_id: Option<String>,
70 pub references: Vec<String>,
71}
72
73impl MessageArgs {
74 fn untyped(text: Option<&str>, category: Option<&str>, to: Option<&str>) -> Self {
75 Self {
76 message_type: category.map(str::to_string),
77 text: text.map(str::to_string),
78 to: to.map(str::to_string),
79 ..Self::default()
80 }
81 }
82}
83
84pub fn handle_message(
89 action: &str,
90 args: &MessageArgs,
91 project_root: &str,
92 current_agent_id: Option<&str>,
93) -> String {
94 use crate::core::hive::bus::messages::{
95 InboxFilter, SendRequest, TYPES, inbox_for_root, send_from_root,
96 };
97 let Some(agent) = current_agent_id else {
98 return "Error: agent must be registered first (use action=register)".to_string();
99 };
100 if action == "inbox" {
101 let filter = InboxFilter {
102 message_type: args.message_type.as_deref(),
103 };
104 return inbox_for_root(project_root, agent, filter)
105 .unwrap_or_else(|e| format!("Error: {e}"));
106 }
107 let Some(text) = args.text.as_deref() else {
108 return format!("Error: message is required for {action}");
109 };
110 let reply_to = args.reply_to.as_deref();
111 if action == "reply" && reply_to.is_none() {
112 return "Error: reply_to (the gid of the message answered) is required".to_string();
113 }
114 let message_type = args
115 .message_type
116 .as_deref()
117 .or((action == "reply").then_some("answer"));
118 let request = SendRequest {
119 message_type,
120 text,
121 to: args.to.as_deref(),
122 to_instance: args.to_instance.as_deref(),
123 reply_to,
124 deadline_hours: args.deadline_hours,
125 swarm_id: args.swarm_id.as_deref(),
126 references: &args.references,
127 };
128 match send_from_root(project_root, agent, &request) {
129 Ok(id) => format!(
130 "Queued [{}] {id}; the Hive relay sends it (types: {TYPES})",
131 message_type.unwrap_or("?")
132 ),
133 Err(error) => format!("Error: {error}"),
134 }
135}
136
137pub fn handle_read(
144 message: Option<&str>,
145 current_agent_id: Option<&str>,
146 project_root: &str,
147) -> Result<String, String> {
148 if let Some(text) = message
150 && let Err(withheld) = crate::core::context_admission::carrier::admit_for_store(text)
151 {
152 return Err(format!("Error: {}", withheld.message("agent message")));
153 }
154 read_messages(current_agent_id, project_root)
155}
156
157fn read_messages(current_agent_id: Option<&str>, project_root: &str) -> Result<String, String> {
159 let Some(agent_id) = current_agent_id else {
160 return Err("Error: agent must be registered first (use action=register)".to_string());
161 };
162 read_messages_as(agent_id, project_root, true)
163}
164
165fn renewed_line(agent_id: &str) -> String {
167 format!(
168 "Note: the registration of {agent_id} had expired and was renewed; retry a claim refused meanwhile.\n"
169 )
170}
171
172pub(crate) const READ_PAGE_BYTES: usize = 6_000;
176
177fn render_message(m: &ScratchpadEntry, project_root: &str) -> String {
179 let age = (chrono::Utc::now() - m.timestamp).num_minutes();
180 if crate::core::hive::bus::relay::is_inbound(m) {
183 return format!(
184 " [hive] ({age}m ago):\n{}\n",
185 m.served_message(Some(project_root))
186 );
187 }
188 format!(
189 " [{}] from {} ({}m ago): {}\n",
190 m.category,
191 m.from_agent,
192 age,
193 m.served_message(Some(project_root))
194 )
195}
196
197pub(crate) fn read_messages_as(
203 agent_id: &str,
204 project_root: &str,
205 own_process: bool,
206) -> Result<String, String> {
207 let (shown, left) = match AgentRegistry::mutate_locked(|registry| {
208 if own_process {
209 registry.renew_worker(agent_id)?;
210 }
211 registry.read_unread_page(agent_id, project_root, READ_PAGE_BYTES, |m| {
212 render_message(m, project_root)
213 })
214 }) {
215 Ok((_, Ok(page))) => page,
216 Ok((_, Err(error))) => {
217 tracing::warn!("lean-ctx: message read rejected: {error}");
218 return Err(format!("Error: {error}"));
219 }
220 Err(e) => {
221 tracing::warn!(
222 "lean-ctx: failed to persist agent registry (messages may reappear): {e}"
223 );
224 return Err("Error: failed to read messages".to_string());
225 }
226 };
227
228 let mut renewed = if crate::core::agents::take_renewed(agent_id) {
229 renewed_line(agent_id)
230 } else {
231 String::new()
232 };
233 if own_process && let Some(note) = crate::core::binary_identity::replaced_note() {
235 renewed.insert_str(0, ¬e);
236 }
237 let hive = crate::core::hive::bus::messages::waiting_hint(project_root, agent_id)
239 .map(|hint| format!("{hint}\n"))
240 .unwrap_or_default();
241 if shown.is_empty() {
242 return Ok(format!("{renewed}{hive}No new messages."));
243 }
244
245 let mut out = format!("{renewed}{hive}New messages ({}):\n", shown.len());
246 for line in &shown {
247 out.push_str(line);
248 }
249 if left > 0 {
250 out.push_str(&format!(
251 "{left} more unread (still unread): read again for the next ones.\n"
252 ));
253 }
254 Ok(out)
255}
256
257pub(crate) const WAIT_DEFAULT_SECS: u64 = 600;
259pub(crate) const WAIT_MAX_SECS: u64 = 1800;
260
261pub(crate) fn wait_timeout_line(secs: u64) -> String {
263 format!("No new messages within {secs}s.")
264}
265
266pub(crate) fn wait_messages(
272 agent_id: &str,
273 project_root: &str,
274 timeout_secs: Option<u64>,
275 own_process: bool,
276) -> Result<Option<String>, String> {
277 let secs = timeout_secs.unwrap_or(WAIT_DEFAULT_SECS).min(WAIT_MAX_SECS);
278 if own_process {
279 AgentRegistry::renew_worker_persistent(agent_id).map_err(|e| format!("Error: {e}"))?;
281 }
282 let arrived = AgentRegistry::wait_for_unread(
283 agent_id,
284 project_root,
285 std::time::Duration::from_secs(secs),
286 || {
287 if own_process && let Err(e) = AgentRegistry::renew_worker_persistent(agent_id) {
288 tracing::debug!("lean-ctx: wait keepalive for {agent_id}: {e}");
289 }
290 },
291 );
292 if arrived {
293 return read_messages_as(agent_id, project_root, own_process).map(Some);
294 }
295 crate::core::agents::friction::record_for(
296 crate::core::agents::friction::WAIT_TIMEOUT,
297 Some(agent_id),
298 Some(project_root),
299 );
300 Ok(None)
301}
302
303pub fn handle_wait(
306 current_agent_id: Option<&str>,
307 project_root: &str,
308 timeout_secs: Option<u64>,
309) -> Result<String, String> {
310 let Some(agent_id) = current_agent_id else {
311 return Err("Error: agent must be registered first (use action=register)".to_string());
312 };
313 let secs = timeout_secs.unwrap_or(WAIT_DEFAULT_SECS).min(WAIT_MAX_SECS);
314 Ok(
315 match wait_messages(agent_id, project_root, timeout_secs, true)? {
316 Some(text) => text,
317 None if crate::core::agents::take_renewed(agent_id) => {
318 format!("{}{}", renewed_line(agent_id), wait_timeout_line(secs))
319 }
320 None => wait_timeout_line(secs),
321 },
322 )
323}
324
325#[allow(clippy::too_many_arguments)]
326pub fn handle(
327 action: &str,
328 agent_type: Option<&str>,
329 role: Option<&str>,
330 durable_identity_id: Option<&str>,
331 project_root: &str,
332 current_agent_id: Option<&str>,
333 message: Option<&str>,
334 category: Option<&str>,
335 to_agent: Option<&str>,
336 status: Option<&str>,
337 privacy: Option<&str>,
338 priority: Option<&str>,
339 _ttl_hours: Option<u64>,
340 format: Option<&str>,
341 write: bool,
342 filename: Option<&str>,
343 request_id: Option<&str>,
344) -> String {
345 let admitted_message = match message
350 .map(crate::core::context_admission::carrier::admit_for_store)
351 .transpose()
352 {
353 Ok(admitted) => admitted,
354 Err(withheld) => return format!("Error: {}", withheld.message("agent message")),
355 };
356 let message = admitted_message.as_deref();
357 match action {
358 "register" => {
359 let atype = agent_type.unwrap_or("unknown");
360 match AgentRegistry::mutate_locked(|registry| {
361 registry.cleanup_stale(presence_ttl_hours());
362 registry.register(atype, role, project_root, durable_identity_id)
363 })
364 .and_then(|(_, agent_id)| agent_id)
365 {
366 Ok(agent_id) => {
367 crate::core::hive::bus::presence::request_announce();
370 format!(
373 "Agent registered: {agent_id} (type: {atype}, role: {}){}",
374 role.unwrap_or("none"),
375 crate::core::binary_identity::replaced_note()
376 .map(|note| format!("\n{}", note.trim_end()))
377 .unwrap_or_default()
378 )
379 }
380 Err(e) => format!("Registration failed: {e}"),
381 }
382 }
383
384 "list" => {
385 let registry = match AgentRegistry::mutate_locked(|registry| {
386 registry.cleanup_stale(presence_ttl_hours());
387 }) {
388 Ok((registry, ())) => registry,
389 Err(e) => {
390 tracing::warn!("lean-ctx: failed to persist agent registry: {e}");
391 AgentRegistry::load_or_create()
392 }
393 };
394
395 let agents = registry.list_active(Some(project_root));
396 if agents.is_empty() {
397 return "No active agents for this project.".to_string();
398 }
399
400 let store = crate::core::hive::HiveStore::open().ok();
403 let instance = store
404 .as_ref()
405 .and_then(|s| s.instance().ok().flatten())
406 .map(|record| record.instance_id);
407 let book = match (&store, &instance) {
408 (Some(store), Some(id)) => {
409 crate::core::hive::workers::attach::list(store, id).unwrap_or_default()
410 }
411 _ => Vec::new(),
412 };
413 crate::core::hive::workers::roster::render(
414 &agents,
415 instance.as_deref().map(|id| (id, book.as_slice())),
416 chrono::Utc::now(),
417 )
418 }
419
420 "post" => {
421 let Some(msg) = message else {
422 return "Error: message is required for post".to_string();
423 };
424 let cat = category.unwrap_or("status");
425 let from = current_agent_id.unwrap_or("anonymous");
426 let msg_privacy = privacy.map_or(PrivacyLevel::Team, PrivacyLevel::parse_str);
427 let msg_priority = priority.map_or(MessagePriority::Normal, MessagePriority::parse_str);
428 let ttl_hours = _ttl_hours.or(Some(scratchpad_default_ttl_hours()));
429 if msg_privacy == PrivacyLevel::Private && to_agent.is_none() {
430 return "Error: private messages require to_agent".to_string();
431 }
432 let request = AgentMessageRequest {
433 project_root: project_root.to_string(),
434 from_agent_id: from.to_string(),
435 to_agent_id: to_agent.map(str::to_string),
436 category: cat.to_string(),
437 message: msg.to_string(),
438 privacy: msg_privacy,
439 priority: msg_priority,
440 ttl_hours,
441 request_id: request_id.map(str::to_string),
442 };
443 match OclaRegistry::global().agent_gateway.route_message(&request) {
444 Ok(msg_id) => {
445 let target = to_agent.unwrap_or("all agents (broadcast)");
446 format!("Posted [{cat}] to {target}: {msg} (id: {msg_id})")
447 }
448 Err(e) => format!("Post failed: {e}"),
449 }
450 }
451
452 "read" => match read_messages(current_agent_id, project_root) {
455 Ok(text) | Err(text) => text,
456 },
457
458 "wait" => match handle_wait(current_agent_id, project_root, None) {
461 Ok(text) | Err(text) => text,
462 },
463
464 "send" => handle_message(
467 "send",
468 &MessageArgs::untyped(message, category, to_agent),
469 project_root,
470 current_agent_id,
471 ),
472 "reply" => handle_message(
473 "reply",
474 &MessageArgs::untyped(message, category, to_agent),
475 project_root,
476 current_agent_id,
477 ),
478 "inbox" => handle_message(
479 "inbox",
480 &MessageArgs::untyped(message, category, to_agent),
481 project_root,
482 current_agent_id,
483 ),
484
485 "status" => {
486 let Some(agent_id) = current_agent_id else {
487 return "Error: agent must be registered first".to_string();
488 };
489 let new_status = match status {
490 Some("active") => AgentStatus::Active,
491 Some("idle") => AgentStatus::Idle,
492 Some("finished") => AgentStatus::Finished,
493 Some(other) => {
494 return format!("Unknown status: {other}. Use: active, idle, finished");
495 }
496 None => return "Error: status value is required".to_string(),
497 };
498 let status_msg = message;
499
500 match AgentRegistry::mutate_locked(|registry| {
501 registry.set_status(agent_id, new_status.clone(), status_msg)
502 })
503 .and_then(|(_, result)| result)
504 {
505 Ok(()) => format!(
506 "Status updated: {} → {}{}",
507 agent_id,
508 new_status,
509 status_msg.map(|m| format!(" ({m})")).unwrap_or_default()
510 ),
511 Err(e) => format!("Status update rejected: {e}"),
512 }
513 }
514
515 "info" => {
516 let registry = AgentRegistry::mutate_locked(|registry| {
517 registry.cleanup_stale(presence_ttl_hours());
518 })
519 .map(|(registry, ())| registry)
520 .unwrap_or_else(|_| AgentRegistry::load_or_create());
521 let total = registry.agents.len();
522 let active = registry.list_active(None).len();
523 let messages = registry.scratchpad.len();
524 format!(
525 "Agent Registry: {total} total, {active} active, {messages} scratchpad entries\nLast updated: {}",
526 registry.updated_at.format("%Y-%m-%d %H:%M UTC")
527 )
528 }
529
530 "handoff" => {
531 let Some(from) = current_agent_id else {
532 return "Error: agent must be registered first".to_string();
533 };
534 let Some(target) = to_agent else {
535 return "Error: to_agent is required for handoff".to_string();
536 };
537 if let Some(refusal) = crate::core::hive::bus::control::veto_refusal(
539 Some(from),
540 &[&format!("handoff:{from}:{target}")],
541 ) {
542 return format!("Handoff rejected: {refusal}");
543 }
544 let summary = message.unwrap_or("(no summary provided)");
545 let scratchpad_ttl = scratchpad_default_ttl_hours();
546 let remote = match crate::core::hive::bus::handoff::remote_target(
549 std::path::Path::new(project_root),
550 target,
551 ) {
552 Ok(remote) => remote,
553 Err(ambiguous) => return format!("Handoff rejected: {ambiguous}"),
554 };
555 let waiting = format!("handing off to {target} (awaiting the Hive ack)");
556
557 let entry_id = match AgentRegistry::mutate_locked(|registry| {
558 let entry_id = registry.post_message_scoped(
562 Some(project_root),
563 from,
564 Some(target),
565 "handoff",
566 &format!("HANDOFF from {from}: {summary}"),
567 PrivacyLevel::Team,
568 MessagePriority::Normal,
569 Some(scratchpad_ttl),
570 )?;
571 if remote.is_some() {
572 registry.set_status(from, AgentStatus::Idle, Some(&waiting))?;
573 } else {
574 registry.set_status(from, AgentStatus::Finished, Some("handed off"))?;
575 }
576 Ok(entry_id)
577 })
578 .and_then(|(_, result)| result)
579 {
580 Ok(entry_id) => entry_id,
581 Err(error) => return format!("Handoff rejected: {error}"),
582 };
583 let offered = remote.map(|r| {
584 crate::core::hive::bus::handoff::offer(
585 &r.data_dir,
586 &r.org_id,
587 &r.vault_id,
588 from,
589 target,
590 &entry_id,
591 )
592 });
593
594 let handoff_message = format!("HANDOFF: {summary}");
596 let capsule_ref = global_capsule_store().register(handoff_message.as_bytes());
597 let mut envelope = AgentEnvelope {
598 schema_version: AGENT_ENVELOPE_SCHEMA_VERSION,
599 relay_id: String::new(),
600 context: OclaRequestContext::new(
601 format!("handoff:{capsule_ref}"),
602 project_root.to_string(),
603 from.to_string(),
604 capsule_ref.clone(),
605 None,
606 Some(format!("handoff:{from}:{target}")),
607 ),
608 from_agent_id: from.to_string(),
609 to_agent_id: target.to_string(),
610 capsule_ref,
611 budget_tokens: handoff_message.len().max(1) as u64,
612 };
613 if let Err(error) = envelope.assign_relay_id() {
614 tracing::debug!("OCLA relay setup failed (non-fatal): {error}");
615 } else if let Err(error) = OclaRegistry::global().agent_gateway.relay_agent(envelope) {
616 tracing::debug!("OCLA relay failed (non-fatal): {error}");
617 }
618
619 crate::core::scent_field::deposit_for(
622 project_root,
623 from,
624 crate::core::scent_field::ScentKind::Done,
625 summary,
626 1.0,
627 );
628
629 match offered {
630 Some(Ok(handoff_id)) => format!(
631 "Handoff offered (hive): {from} → {target} handoff_id={handoff_id}; \
632 {from} finishes when {target}'s machine acks\nSummary: {summary}"
633 ),
634 Some(Err(error)) => {
635 let _ = AgentRegistry::mutate_locked(|registry| {
636 registry.set_status(from, AgentStatus::Active, Some("handoff not sent"))
637 });
638 format!("Handoff rejected: the Hive offer could not be queued ({error})")
639 }
640 None => format!("Handoff complete: {from} → {target}\nSummary: {summary}"),
641 }
642 }
643
644 "claim" => {
648 let Some(target) = message else {
649 return "Error: message (the claim target, e.g. a file path or task label) is required for claim".to_string();
650 };
651 let agent = current_agent_id.map_or_else(
652 || crate::core::scent_field::scent_agent_id().to_string(),
653 str::to_string,
654 );
655 let normalized = crate::core::pathutil::normalize_tool_path(target);
656 match crate::core::scent_field::claim(project_root, &agent, &normalized) {
657 Ok(()) => {
658 format!("Claimed: {normalized} (by {agent}, decays in ~10m unless re-claimed)")
659 }
660 Err(e) => format!("Claim REJECTED: {normalized} — {e}"),
661 }
662 }
663
664 "release" => {
666 let Some(target) = message else {
667 return "Error: message (the claim target) is required for release".to_string();
668 };
669 let agent = current_agent_id.map_or_else(
670 || crate::core::scent_field::scent_agent_id().to_string(),
671 str::to_string,
672 );
673 let normalized = crate::core::pathutil::normalize_tool_path(target);
674 crate::core::scent_field::release(project_root, &agent, &normalized);
675 format!("Released: {normalized}")
676 }
677
678 "brief" => {
682 let Some(task) = message else {
683 return "Error: message (the sub-agent task) is required for brief".to_string();
684 };
685 let budget = priority
686 .and_then(|p| p.parse::<usize>().ok())
687 .unwrap_or(2000);
688 let Some(knowledge) = crate::core::knowledge::ProjectKnowledge::load(project_root)
689 else {
690 return "No knowledge stored for this project yet — a briefing pack needs facts. Use ctx_knowledge(action=\"remember\") first.".to_string();
691 };
692 let pack =
694 crate::core::subagent_contract::build_briefing_pack(&knowledge, task, budget);
695 match crate::core::subagent_contract::serialize_pack(&pack) {
696 Ok(json) => json,
697 Err(e) => format!("Error: {e}"),
698 }
699 }
700
701 "return" => {
705 let Some(report) = message else {
706 return "Error: message (the sub-agent report) is required for return".to_string();
707 };
708 let (facts, rejected) = crate::core::subagent_contract::parse_return_lines(report);
709 if facts.is_empty() {
710 return format!(
711 "No contract-formatted lines found ({} rejected). Expected 'category/key: value' per line.",
712 rejected.len()
713 );
714 }
715
716 let session_label = current_agent_id.unwrap_or("subagent");
717 let policy = match crate::tools::knowledge_shared::load_policy_or_error() {
718 Ok(p) => p,
719 Err(e) => return e,
720 };
721 let count = facts.len();
722 let res = crate::core::knowledge::ProjectKnowledge::mutate_locked(
723 project_root,
724 |knowledge| {
725 for f in &facts {
726 knowledge.remember(
727 &f.category,
728 &f.key,
729 &f.value,
730 session_label,
731 0.8,
732 &policy,
733 );
734 }
735 },
736 );
737 match res {
738 Ok(_) => {
739 let mut out = format!(
740 "Return synthesis: {count} fact(s) distilled into parent knowledge"
741 );
742 if !rejected.is_empty() {
743 out.push_str(&format!(
744 "\n{} line(s) rejected (not 'category/key: value'):",
745 rejected.len()
746 ));
747 for r in rejected.iter().take(5) {
748 out.push_str(&format!("\n ✗ {r}"));
749 }
750 }
751 out
752 }
753 Err(e) => format!("Error: knowledge store update failed: {e}"),
754 }
755 }
756
757 "sync" => {
758 let registry = AgentRegistry::mutate_locked(|registry| {
759 registry.cleanup_stale(presence_ttl_hours());
760 })
761 .map(|(registry, ())| registry)
762 .unwrap_or_else(|_| AgentRegistry::load_or_create());
763 let pending_count = current_agent_id.map_or(0, |id| {
764 registry
765 .scratchpad
766 .iter()
767 .filter(|e| {
768 !e.read_by.contains(&id.to_string())
769 && e.from_agent != id
770 && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(id))
771 && e.project_root.as_deref().is_some_and(|own| {
772 crate::core::pathutil::same_project(own, project_root)
773 })
774 })
775 .count()
776 });
777 let agents = registry.list_active(Some(project_root));
778
779 if agents.is_empty() {
780 return "No active agents to sync with.".to_string();
781 }
782
783 let shared_dir = crate::core::data_dir::lean_ctx_data_dir()
785 .unwrap_or_default()
786 .join("agents")
787 .join("shared")
788 .join(crate::core::project_hash::hash_project_root(project_root));
789
790 let shared_count = if shared_dir.exists() {
791 std::fs::read_dir(&shared_dir).map_or(0, std::iter::Iterator::count)
792 } else {
793 0
794 };
795
796 let mut out = "Multi-Agent Sync Status:\n".to_string();
797 out.push_str(&format!(" Active agents: {}\n", agents.len()));
798 for a in &agents {
799 let role = a.role.as_deref().unwrap_or("-");
800 let age = (chrono::Utc::now() - a.last_active).num_minutes();
801 out.push_str(&format!(
802 " {} [{}] role={} ({}m ago)\n",
803 a.agent_id, a.agent_type, role, age
804 ));
805 }
806 out.push_str(&format!(" Pending messages: {pending_count}\n"));
807 out.push_str(&format!(" Shared contexts: {shared_count}\n"));
808
809 let scents = crate::core::scent_field::sync_block(project_root);
812 if !scents.is_empty() {
813 out.push_str(&scents);
814 }
815 out
816 }
817
818 "control_status" => control_status(project_root, current_agent_id),
823
824 "export" => {
825 let Some(agent_id) = current_agent_id else {
826 return "Error: agent must be registered first (use action=register)".to_string();
827 };
828
829 fn privacy_label(p: &PrivacyLevel) -> &'static str {
830 match p {
831 PrivacyLevel::Public => "public",
832 PrivacyLevel::Team => "team",
833 PrivacyLevel::Private => "private",
834 }
835 }
836
837 fn priority_label(p: &MessagePriority) -> &'static str {
838 match p {
839 MessagePriority::Low => "low",
840 MessagePriority::Normal => "normal",
841 MessagePriority::High => "high",
842 MessagePriority::Critical => "critical",
843 }
844 }
845
846 fn maybe_redact(s: &str, should_redact: bool) -> String {
847 if should_redact {
848 crate::core::redaction::redact_text(s)
849 } else {
850 s.to_string()
851 }
852 }
853
854 #[derive(serde::Serialize)]
855 struct ExportAgentV1 {
856 agent_id: String,
857 agent_type: String,
858 role: Option<String>,
859 status: String,
860 status_message: Option<String>,
861 started_at: String,
862 last_active: String,
863 pid: u32,
864 }
865
866 #[derive(serde::Serialize)]
867 struct ExportMessageV1 {
868 id: String,
869 from_agent: String,
870 to_agent: Option<String>,
871 category: String,
872 privacy: String,
873 priority: String,
874 message: String,
875 metadata: std::collections::BTreeMap<String, String>,
876 timestamp: String,
877 expires_at: Option<String>,
878 read_by_count: usize,
879 }
880
881 #[derive(serde::Serialize)]
882 struct ExportTaskV1 {
883 id: String,
884 from_agent: String,
885 to_agent: String,
886 state: String,
887 description: String,
888 created_at: String,
889 updated_at: String,
890 messages: usize,
891 artifacts: usize,
892 transitions: usize,
893 }
894
895 #[derive(serde::Serialize)]
896 struct ExportDiaryEntryV1 {
897 entry_type: String,
898 content: String,
899 context: Option<String>,
900 timestamp: String,
901 }
902
903 #[derive(serde::Serialize)]
904 struct ExportDiaryV1 {
905 agent_id: String,
906 agent_type: String,
907 project_root: String,
908 updated_at: String,
909 entries: Vec<ExportDiaryEntryV1>,
910 }
911
912 #[derive(serde::Serialize)]
913 struct A2ASnapshotV1 {
914 schema_version: u32,
915 created_at: String,
916 project_root: String,
917 agent_id: String,
918 agents: Vec<ExportAgentV1>,
919 messages: Vec<ExportMessageV1>,
920 tasks: Vec<ExportTaskV1>,
921 diary: Option<ExportDiaryV1>,
922 }
923
924 let privacy_mode = privacy.unwrap_or("redacted");
925 let allow_full = privacy_mode == "full"
926 && !crate::core::redaction::redaction_enabled_for_active_role();
927 let should_redact = !allow_full;
928
929 let now = chrono::Utc::now();
930 let mut registry = AgentRegistry::load_or_create();
931 registry.cleanup_stale(presence_ttl_hours());
932
933 let mut agents: Vec<ExportAgentV1> = registry
934 .list_active(Some(project_root))
935 .into_iter()
936 .map(|a| ExportAgentV1 {
937 agent_id: a.agent_id.clone(),
938 agent_type: a.agent_type.clone(),
939 role: a.role.clone(),
940 status: a.status.to_string(),
941 status_message: a.status_message.clone(),
942 started_at: a.started_at.to_rfc3339(),
943 last_active: a.last_active.to_rfc3339(),
944 pid: a.pid,
945 })
946 .collect();
947 agents.sort_by(|a, b| a.agent_id.cmp(&b.agent_id));
948
949 let mut messages: Vec<ExportMessageV1> = registry
950 .scratchpad
951 .iter()
952 .filter(|e| {
953 e.project_root
954 .as_deref()
955 .is_some_and(|own| crate::core::pathutil::same_project(own, project_root))
956 && (e.to_agent.is_none() || e.to_agent.as_deref() == Some(agent_id))
957 })
958 .take(200)
959 .map(|m| ExportMessageV1 {
960 id: m.id.clone(),
961 from_agent: m.from_agent.clone(),
962 to_agent: m.to_agent.clone(),
963 category: m.category.clone(),
964 privacy: privacy_label(&m.privacy).to_string(),
965 priority: priority_label(&m.priority).to_string(),
966 message: maybe_redact(&m.served_message(Some(project_root)), should_redact),
967 metadata: m
969 .metadata
970 .iter()
971 .filter(|(k, _)| k.as_str() != crate::core::agents::BINDING_METADATA_KEY)
972 .map(|(k, v)| (k.clone(), maybe_redact(v, should_redact)))
973 .collect(),
974 timestamp: m.timestamp.to_rfc3339(),
975 expires_at: m.expires_at.map(|t| t.to_rfc3339()),
976 read_by_count: m.read_by.len(),
977 })
978 .collect();
979 messages.sort_by(|a, b| a.timestamp.cmp(&b.timestamp).then_with(|| a.id.cmp(&b.id)));
980
981 const EXPORT_LOCK_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
986 let tasks = TaskStore::default_path().and_then(|path| {
987 TaskStore::mutate_locked_within(&path, EXPORT_LOCK_WAIT, |task_store| {
988 task_store.cleanup_old(72);
989 Ok::<_, std::io::Error>(
990 task_store
991 .tasks_for_agent(agent_id)
992 .into_iter()
993 .take(200)
994 .map(|t| ExportTaskV1 {
995 id: t.id.clone(),
996 from_agent: t.from_agent.clone(),
997 to_agent: t.to_agent.clone(),
998 state: t.state.to_string(),
999 description: maybe_redact(&t.served_description(), should_redact),
1000 created_at: t.created_at.to_rfc3339(),
1001 updated_at: t.updated_at.to_rfc3339(),
1002 messages: t.messages.len(),
1003 artifacts: t.artifacts.len(),
1004 transitions: t.history.len(),
1005 })
1006 .collect::<Vec<ExportTaskV1>>(),
1007 )
1008 })
1009 });
1010 let mut tasks = match tasks {
1011 Ok(tasks) => tasks,
1012 Err(error) => {
1013 tracing::warn!("lean-ctx: failed to read task store: {error}");
1014 return "Error: task storage unavailable".to_string();
1015 }
1016 };
1017 tasks.sort_by(|a, b| {
1018 b.updated_at
1019 .cmp(&a.updated_at)
1020 .then_with(|| a.id.cmp(&b.id))
1021 });
1022
1023 let diary =
1024 AgentDiary::load_for_project(agent_id, project_root).map(|d| ExportDiaryV1 {
1025 agent_id: d.agent_id,
1026 agent_type: d.agent_type,
1027 project_root: d.project_root,
1028 updated_at: d.updated_at.to_rfc3339(),
1029 entries: d
1030 .entries
1031 .iter()
1032 .rev()
1033 .take(25)
1034 .rev()
1035 .map(|e| ExportDiaryEntryV1 {
1036 entry_type: e.entry_type.to_string(),
1037 content: maybe_redact(&e.content, should_redact),
1038 context: e.context.as_deref().map(|c| maybe_redact(c, should_redact)),
1039 timestamp: e.timestamp.to_rfc3339(),
1040 })
1041 .collect(),
1042 });
1043
1044 let payload = A2ASnapshotV1 {
1045 schema_version: crate::core::contracts::A2A_SNAPSHOT_V1_SCHEMA_VERSION,
1046 created_at: now.to_rfc3339(),
1047 project_root: project_root.to_string(),
1048 agent_id: agent_id.to_string(),
1049 agents,
1050 messages,
1051 tasks,
1052 diary,
1053 };
1054
1055 let json = serde_json::to_string_pretty(&payload).unwrap_or_else(|_| "{}".to_string());
1056
1057 if write {
1058 let proofs_dir = std::path::Path::new(project_root)
1059 .join(".lean-ctx")
1060 .join("proofs");
1061 if let Err(e) = std::fs::create_dir_all(&proofs_dir) {
1062 return format!("Error: create proofs dir: {e}");
1063 }
1064
1065 let name = if let Some(f) = filename {
1066 let p = std::path::Path::new(f);
1067 if p.components().count() != 1 {
1068 return "Error: filename must be a plain file name (no directories)"
1069 .to_string();
1070 }
1071 f.to_string()
1072 } else {
1073 format!("a2a-snapshot-v1_{}.json", now.format("%Y%m%d_%H%M%S"))
1074 };
1075
1076 let out_path = proofs_dir.join(name);
1077 if let Err(e) = std::fs::write(&out_path, &json) {
1078 return format!("Error: write snapshot: {e}");
1079 }
1080
1081 return format!(
1082 "A2A snapshot exported: {}\n agents: {}\n messages: {}\n tasks: {}",
1083 out_path.display(),
1084 payload.agents.len(),
1085 payload.messages.len(),
1086 payload.tasks.len()
1087 );
1088 }
1089
1090 match format.unwrap_or("json") {
1091 "text" => format!(
1092 "A2A snapshot (v1)\n agents: {}\n messages: {}\n tasks: {}",
1093 payload.agents.len(),
1094 payload.messages.len(),
1095 payload.tasks.len()
1096 ),
1097 _ => json,
1098 }
1099 }
1100
1101 "diary" => {
1102 let Some(agent_id) = current_agent_id else {
1103 return "Error: agent must be registered first".to_string();
1104 };
1105 let Some(content) = message else {
1106 return "Error: message is required for diary entry".to_string();
1107 };
1108 let entry_type = match category.unwrap_or("progress") {
1109 "discovery" | "found" => DiaryEntryType::Discovery,
1110 "decision" | "decided" => DiaryEntryType::Decision,
1111 "blocker" | "blocked" => DiaryEntryType::Blocker,
1112 "progress" | "done" => DiaryEntryType::Progress,
1113 "insight" => DiaryEntryType::Insight,
1114 other => {
1115 return format!(
1116 "Unknown diary type: {other}. Use: discovery, decision, blocker, progress, insight"
1117 );
1118 }
1119 };
1120 let atype = agent_type.unwrap_or("unknown");
1121 let mut diary = AgentDiary::load_or_create(agent_id, atype, project_root);
1122 let context_str = to_agent;
1123 diary.add_entry(entry_type.clone(), content, context_str);
1124 match diary.save() {
1125 Ok(()) => format!("Diary entry [{entry_type}] added: {content}"),
1126 Err(e) => format!("Diary entry added but save failed: {e}"),
1127 }
1128 }
1129
1130 "recall_diary" | "diary_recall" => {
1131 let Some(agent_id) = current_agent_id else {
1132 let diaries = AgentDiary::list_for_project(project_root);
1133 if diaries.is_empty() {
1134 return "No agent diaries found.".to_string();
1135 }
1136 let mut out = format!("Agent Diaries ({}):\n", diaries.len());
1137 for (id, count, updated) in &diaries {
1138 let age = (chrono::Utc::now() - *updated).num_minutes();
1139 out.push_str(&format!(" {id}: {count} entries ({age}m ago)\n"));
1140 }
1141 return out;
1142 };
1143 match AgentDiary::load_for_project(agent_id, project_root) {
1144 Some(diary) => diary.format_summary(),
1145 None => format!("No diary found for agent '{agent_id}'."),
1146 }
1147 }
1148
1149 "diaries" => {
1150 let diaries = AgentDiary::list_for_project(project_root);
1151 if diaries.is_empty() {
1152 return "No agent diaries found.".to_string();
1153 }
1154 let mut out = format!("Agent Diaries ({}):\n", diaries.len());
1155 for (id, count, updated) in &diaries {
1156 let age = (chrono::Utc::now() - *updated).num_minutes();
1157 out.push_str(&format!(" {id}: {count} entries ({age}m ago)\n"));
1158 }
1159 out
1160 }
1161
1162 "share_knowledge" => {
1163 let cat = category.unwrap_or("general");
1164 let Some(msg_text) = message else {
1165 return "Error: message required (format: key1=value1;key2=value2)".to_string();
1166 };
1167 let facts: Vec<(String, String)> = msg_text
1168 .split(';')
1169 .filter_map(|kv| {
1170 let (k, v) = kv.split_once('=')?;
1171 Some((k.trim().to_string(), v.trim().to_string()))
1172 })
1173 .collect();
1174 if facts.is_empty() {
1175 return "Error: no valid key=value pairs found".to_string();
1176 }
1177 let Some(from) = current_agent_id else {
1178 return "Error: agent must be registered first".to_string();
1179 };
1180 match AgentRegistry::mutate_locked(|registry| {
1182 registry.require_active_for_presence(from, "sharing knowledge")?;
1183 registry.share_knowledge(project_root, from, cat, &facts)
1184 })
1185 .and_then(|(_, shared)| shared)
1186 {
1187 Ok(count) => format!("Shared {count} facts in category '{cat}' with this project"),
1188 Err(e) => format!("Share failed: {e}"),
1189 }
1190 }
1191
1192 "receive_knowledge" => {
1193 let Some(agent_id) = current_agent_id else {
1194 return "Error: agent must be registered first".to_string();
1195 };
1196 let facts = match AgentRegistry::mutate_locked(|registry| {
1197 registry.require_active_for_presence(agent_id, "receiving knowledge")?;
1198 registry.receive_shared_knowledge(project_root, agent_id)
1199 })
1200 .and_then(|(_, facts)| facts)
1201 {
1202 Ok(facts) => facts,
1203 Err(e) => return format!("Receive failed: {e}"),
1204 };
1205 if facts.is_empty() {
1206 return "No new shared knowledge.".to_string();
1207 }
1208 let mut out = format!("Received {} facts:\n", facts.len());
1209 for f in &facts {
1210 let age = (chrono::Utc::now() - f.timestamp).num_minutes();
1211 out.push_str(&format!(
1212 " [{}] {} (from {}, {}m ago)\n",
1213 f.category, f.text, f.from_agent, age
1214 ));
1215 }
1216 out
1217 }
1218
1219 "poll_events" => {
1220 let Some(agent_id) = current_agent_id else {
1221 return "Error: agent must be registered first".to_string();
1222 };
1223 let workspace_id = to_agent.unwrap_or(project_root);
1224 let channel_id = category.unwrap_or("default");
1225 let since_id: i64 = message.and_then(|s| s.parse().ok()).unwrap_or(0);
1226 let limit: usize = _ttl_hours.unwrap_or(50) as usize;
1227
1228 let rt = crate::core::context_os::runtime();
1229 let events = rt.bus.read(workspace_id, channel_id, since_id, limit);
1230
1231 let filter = crate::core::context_os::TopicFilter {
1232 agent_id: Some(agent_id.to_string()),
1233 kinds: privacy.and_then(|s| {
1234 let kinds: Vec<_> = s
1235 .split(',')
1236 .map(|k| crate::core::context_os::ContextEventKindV1::parse(k.trim()))
1237 .collect();
1238 if kinds.is_empty() { None } else { Some(kinds) }
1239 }),
1240 ..Default::default()
1241 };
1242
1243 let filtered: Vec<_> = events.into_iter().filter(|e| filter.matches(e)).collect();
1244 if filtered.is_empty() {
1245 return format!("No new events since id={since_id} for {agent_id}.");
1246 }
1247
1248 let mut out = format!("Events ({}, since={since_id}):\n", filtered.len());
1249 for ev in &filtered {
1250 let actor = ev.actor.as_deref().unwrap_or("-");
1251 out.push_str(&format!(
1252 " #{} [{}] actor={} cl={} ({})\n",
1253 ev.id,
1254 ev.kind,
1255 actor,
1256 ev.consistency_level,
1257 ev.timestamp.format("%H:%M:%S")
1258 ));
1259 }
1260 if let Some(last) = filtered.last() {
1261 out.push_str(&format!("cursor={}", last.id));
1262 }
1263 out
1264 }
1265
1266 "lease_acquire" => {
1268 let Some(agent_id) = current_agent_id else {
1269 return "Error: agent must be registered first".to_string();
1270 };
1271 let Some(target) = message else {
1272 return "Error: message (path or symbol:<name>) is required".to_string();
1273 };
1274 if let Err(error) = AgentRegistry::load_or_create()
1275 .require_active_for_presence(agent_id, "acquiring a lease")
1276 {
1277 return format!("Lease rejected: {error}");
1278 }
1279 let (resource_kind, resource_ref) = match lease_resource(project_root, target) {
1280 Ok(resource) => resource,
1281 Err(error) => return format!("Lease rejected: {error}"),
1282 };
1283 if let Some(refusal) =
1285 crate::core::hive::bus::control::veto_refusal(Some(agent_id), &[&resource_ref])
1286 {
1287 return format!("Lease rejected: {refusal}");
1288 }
1289 let duration_ms = match _ttl_hours.unwrap_or(0) {
1290 0 => 10 * 60 * 1_000,
1291 1 => 60 * 60 * 1_000,
1292 _ => return "Error: ttl_hours for lease must be 0 (10min) or 1 (1h)".to_string(),
1293 };
1294 let request = crate::core::agent_lease::AgentLeaseRequestV1 {
1295 schema_version: crate::core::agent_lease::AGENT_LEASE_SCHEMA_VERSION,
1296 lease_request_ref: format!(
1297 "lease-request:{}",
1298 blake3::hash(format!("{agent_id}:{resource_ref}").as_bytes()).to_hex()
1299 ),
1300 resource_kind,
1301 resource_ref: resource_ref.clone(),
1302 owner_agent_id: agent_id.to_string(),
1303 duration_ms,
1304 };
1305 match crate::core::agent_lease::acquire_shared(request) {
1306 Ok(crate::core::agent_lease::AgentLeaseAcquireV1::Granted(lease)) => {
1307 use crate::core::hive::bus::leases::{self, Outcome};
1309 let hive = leases::acquire(
1310 std::path::Path::new(project_root),
1311 agent_id,
1312 target,
1313 duration_ms,
1314 &lease.lease_ref,
1315 );
1316 let release_local = || {
1317 let _ = crate::core::agent_lease::release_shared(
1318 resource_kind,
1319 &resource_ref,
1320 agent_id,
1321 &lease.lease_ref,
1322 );
1323 };
1324 match hive {
1325 Outcome::Held {
1326 agent_id: holder,
1327 instance_id,
1328 expires_at,
1329 } => {
1330 release_local();
1331 format!(
1332 "Lease HELD (hive): resource={resource_ref} owner={holder} \
1333 instance={instance_id} expires={expires_at}"
1334 )
1335 }
1336 Outcome::Vetoed => {
1337 release_local();
1338 "Lease rejected: a workspace veto bars this agent from it \
1339 until the veto is lifted"
1340 .to_string()
1341 }
1342 Outcome::Granted { ref expires_at, .. } => format!(
1343 "Lease granted: {} resource={} owner={} expires_at_epoch_ms={} {} hive_expires_at={expires_at}",
1344 lease.lease_ref,
1345 resource_ref,
1346 agent_id,
1347 lease.expires_at_epoch_ms,
1348 leases::scope_line(&hive)
1349 ),
1350 other => format!(
1351 "Lease granted: {} resource={} owner={} expires_at_epoch_ms={} {}",
1352 lease.lease_ref,
1353 resource_ref,
1354 agent_id,
1355 lease.expires_at_epoch_ms,
1356 leases::scope_line(&match other {
1357 Outcome::Superseded => Outcome::Local("Hive lost the lease".into()),
1358 other => other,
1359 })
1360 ),
1361 }
1362 }
1363 Ok(crate::core::agent_lease::AgentLeaseAcquireV1::HeldBy {
1364 owner_agent_id,
1365 lease_ref,
1366 expires_at_epoch_ms,
1367 }) => format!(
1368 "Lease HELD: resource={resource_ref} owner={owner_agent_id} lease_ref={lease_ref} expires={expires_at_epoch_ms}"
1369 ),
1370 Err(e) => format!("Lease rejected: {e}"),
1371 }
1372 }
1373
1374 "lease_release" => {
1376 let Some(agent_id) = current_agent_id else {
1377 return "Error: agent must be registered first".to_string();
1378 };
1379 let Some(target) = message else {
1380 return "Error: message (same path or symbol:<name>) is required".to_string();
1381 };
1382 let Some(lease_ref) = category else {
1383 return "Error: category (lease_ref from lease_acquire) is required".to_string();
1384 };
1385 let (resource_kind, resource_ref) = match lease_resource(project_root, target) {
1386 Ok(resource) => resource,
1387 Err(error) => return format!("Release failed: {error}"),
1388 };
1389 crate::core::hive::bus::leases::queue_release(lease_ref);
1391 match crate::core::agent_lease::release_shared(
1392 resource_kind,
1393 &resource_ref,
1394 agent_id,
1395 lease_ref,
1396 ) {
1397 Ok(true) => format!("Lease released: {lease_ref} resource={resource_ref}"),
1398 Ok(false) => format!("No active lease found for resource={resource_ref}"),
1399 Err(e) => format!("Release failed: {e}"),
1400 }
1401 }
1402
1403 "lease_renew" => {
1407 let Some(agent_id) = current_agent_id else {
1408 return "Error: agent must be registered first".to_string();
1409 };
1410 let Some(target) = message else {
1411 return "Error: message (same path or symbol:<name>) is required for renew"
1412 .to_string();
1413 };
1414 let Some(lease_ref) = category else {
1415 return "Error: category (lease_ref from lease_acquire) is required".to_string();
1416 };
1417 if let Err(error) = AgentRegistry::load_or_create()
1418 .require_active_for_presence(agent_id, "renewing a lease")
1419 {
1420 return format!("Lease renewal rejected: {error}");
1421 }
1422 let (resource_kind, resource_ref) = match lease_resource(project_root, target) {
1423 Ok(resource) => resource,
1424 Err(error) => return format!("Lease renewal rejected: {error}"),
1425 };
1426 if let Some(refusal) = crate::core::hive::bus::control::veto_refusal(
1427 Some(agent_id),
1428 &[lease_ref, &resource_ref],
1429 ) {
1430 return format!("Lease renewal rejected: {refusal}");
1431 }
1432 let duration_ms = match _ttl_hours.unwrap_or(0) {
1433 0 => 10 * 60 * 1_000,
1434 1 => 60 * 60 * 1_000,
1435 _ => return "Error: ttl_hours for lease must be 0 (10min) or 1 (1h)".to_string(),
1436 };
1437 match crate::core::agent_lease::renew_shared(
1438 resource_kind,
1439 &resource_ref,
1440 agent_id,
1441 lease_ref,
1442 duration_ms,
1443 ) {
1444 Ok(lease) => {
1445 use crate::core::hive::bus::leases::{self, Outcome};
1446 match leases::renew(std::path::Path::new(project_root), lease_ref, duration_ms)
1447 {
1448 outcome @ (Outcome::Superseded | Outcome::Vetoed) => {
1449 let _ = crate::core::agent_lease::release_shared(
1450 resource_kind,
1451 &resource_ref,
1452 agent_id,
1453 lease_ref,
1454 );
1455 if outcome == Outcome::Vetoed {
1456 "Lease renewal rejected: a workspace veto ended it".to_string()
1457 } else {
1458 "Lease renewal rejected: Hive no longer holds it for you \
1459 (expired on the service clock or superseded); acquire it again"
1460 .to_string()
1461 }
1462 }
1463 hive => format!(
1464 "Lease renewed: {} resource={} owner={} expires_at_epoch_ms={} {}",
1465 lease.lease_ref,
1466 resource_ref,
1467 agent_id,
1468 lease.expires_at_epoch_ms,
1469 leases::scope_line(&hive)
1470 ),
1471 }
1472 }
1473 Err(e) => format!("Lease renewal rejected: {e}"),
1474 }
1475 }
1476
1477 _ => format!("Unknown action: {action}. Use: {}", ACTIONS.join(", ")),
1478 }
1479}
1480
1481#[cfg(test)]
1482#[path = "ctx_agent_tests.rs"]
1483mod tests;
1484