1pub mod circuit_breaker;
8
9pub use circuit_breaker::{A2ACircuitBreaker, CircuitState};
10
11use std::collections::HashMap;
12use std::sync::Arc;
13
14use anyhow::Result;
15use chrono::{DateTime, Utc};
16use serde::{Deserialize, Serialize};
17use tokio::sync::RwLock;
18use uuid::Uuid;
19
20use crate::event_bus::{EventBus, KernelEvent};
21use crate::types::{AgentId, AgentStatus};
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
25#[serde(tag = "type", rename_all = "snake_case")]
26pub enum A2AMessage {
27 TaskDelegation {
29 task_id: Uuid,
31 description: String,
33 payload: serde_json::Value,
35 priority: TaskPriority,
37 },
38 StatusUpdate {
40 task_id: Uuid,
42 progress: u8,
44 message: String,
46 },
47 ResultSharing {
49 task_id: Uuid,
51 result: serde_json::Value,
53 summary: String,
55 },
56 CapabilityQuery {
58 query: String,
60 required_capabilities: Vec<String>,
62 },
63 Handshake {
65 agent_id: AgentId,
67 name: String,
69 capabilities: Vec<String>,
71 },
72}
73
74impl A2AMessage {
75 pub fn type_name(&self) -> &'static str {
77 match self {
78 A2AMessage::TaskDelegation { .. } => "task_delegation",
79 A2AMessage::StatusUpdate { .. } => "status_update",
80 A2AMessage::ResultSharing { .. } => "result_sharing",
81 A2AMessage::CapabilityQuery { .. } => "capability_query",
82 A2AMessage::Handshake { .. } => "handshake",
83 }
84 }
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
89pub enum TaskPriority {
90 Low,
92 #[default]
94 Normal,
95 High,
97 Critical,
99}
100
101#[derive(Debug, Clone, Serialize, Deserialize)]
103pub struct TaskSpec {
104 pub task_id: Uuid,
106 pub description: String,
108 pub payload: serde_json::Value,
110 pub priority: TaskPriority,
112 pub deadline: Option<DateTime<Utc>>,
114}
115
116impl TaskSpec {
117 pub fn new(description: impl Into<String>, payload: serde_json::Value) -> Self {
119 Self {
120 task_id: Uuid::new_v4(),
121 description: description.into(),
122 payload,
123 priority: TaskPriority::default(),
124 deadline: None,
125 }
126 }
127
128 pub fn with_priority(mut self, priority: TaskPriority) -> Self {
130 self.priority = priority;
131 self
132 }
133
134 pub fn with_deadline(mut self, deadline: DateTime<Utc>) -> Self {
136 self.deadline = Some(deadline);
137 self
138 }
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
143pub struct A2ARequest {
144 pub request_id: Uuid,
146 pub from: AgentId,
148 pub to: AgentId,
150 pub message: A2AMessage,
152 pub timestamp: DateTime<Utc>,
154}
155
156impl A2ARequest {
157 pub fn new(from: AgentId, to: AgentId, message: A2AMessage) -> Self {
159 Self {
160 request_id: Uuid::new_v4(),
161 from,
162 to,
163 message,
164 timestamp: Utc::now(),
165 }
166 }
167}
168
169#[derive(Debug, Clone, Serialize, Deserialize)]
171pub struct A2AResponse {
172 pub response_id: Uuid,
174 pub request_id: Uuid,
176 pub from: AgentId,
178 pub to: AgentId,
180 pub accepted: bool,
182 pub payload: serde_json::Value,
184 pub timestamp: DateTime<Utc>,
186}
187
188impl A2AResponse {
189 pub fn success(
191 request_id: Uuid,
192 from: AgentId,
193 to: AgentId,
194 payload: serde_json::Value,
195 ) -> Self {
196 Self {
197 response_id: Uuid::new_v4(),
198 request_id,
199 from,
200 to,
201 accepted: true,
202 payload,
203 timestamp: Utc::now(),
204 }
205 }
206
207 pub fn error(request_id: Uuid, from: AgentId, to: AgentId, error: impl Into<String>) -> Self {
209 Self {
210 response_id: Uuid::new_v4(),
211 request_id,
212 from,
213 to,
214 accepted: false,
215 payload: serde_json::json!({ "error": error.into() }),
216 timestamp: Utc::now(),
217 }
218 }
219}
220
221#[derive(Debug, Clone, Serialize, Deserialize)]
223pub struct PendingMessage {
224 pub request: A2ARequest,
226 pub queued_at: DateTime<Utc>,
228}
229
230impl PendingMessage {
231 fn new(request: A2ARequest) -> Self {
232 Self {
233 request,
234 queued_at: Utc::now(),
235 }
236 }
237}
238
239#[derive(Debug, Clone, Serialize, Deserialize)]
244pub struct AgentCard {
245 pub agent_id: AgentId,
247 pub name: String,
249 pub description: String,
251 pub capabilities: Vec<String>,
253 pub skills: Vec<String>,
255 pub endpoint: String,
257 pub status: AgentStatus,
259}
260
261impl AgentCard {
262 pub fn new(agent_id: AgentId, name: impl Into<String>, description: impl Into<String>) -> Self {
264 Self {
265 agent_id,
266 name: name.into(),
267 description: description.into(),
268 capabilities: Vec::new(),
269 skills: Vec::new(),
270 endpoint: "local".into(),
271 status: AgentStatus::Starting,
272 }
273 }
274
275 pub fn with_capability(mut self, capability: impl Into<String>) -> Self {
277 self.capabilities.push(capability.into());
278 self
279 }
280
281 pub fn with_skill(mut self, skill: impl Into<String>) -> Self {
283 self.skills.push(skill.into());
284 self
285 }
286
287 pub fn with_endpoint(mut self, endpoint: impl Into<String>) -> Self {
289 self.endpoint = endpoint.into();
290 self
291 }
292
293 pub fn with_status(mut self, status: AgentStatus) -> Self {
295 self.status = status;
296 self
297 }
298
299 pub fn has_capability(&self, capability: &str) -> bool {
301 self.capabilities.iter().any(|c| c == capability)
302 }
303
304 pub fn has_skill(&self, skill: &str) -> bool {
306 self.skills.iter().any(|s| s == skill)
307 }
308}
309
310#[derive(Clone)]
315pub struct AgentCardRegistry {
316 cards: Arc<RwLock<HashMap<AgentId, AgentCard>>>,
318 event_bus: EventBus,
320}
321
322impl AgentCardRegistry {
323 pub fn new(event_bus: EventBus) -> Self {
325 Self {
326 cards: Arc::new(RwLock::new(HashMap::new())),
327 event_bus,
328 }
329 }
330
331 pub async fn register_agent(&self, card: AgentCard) -> Result<()> {
333 let agent_id = card.agent_id;
334 let mut cards = self.cards.write().await;
335 cards.insert(agent_id, card.clone());
336 drop(cards);
337
338 self.event_bus.publish(KernelEvent::AgentCreated {
339 id: agent_id,
340 name: card.name.clone(),
341 })?;
342
343 tracing::info!(agent_id = %agent_id, name = %card.name, "Agent registered in A2A registry");
344 Ok(())
345 }
346
347 pub async fn unregister_agent(&self, agent_id: AgentId) -> Result<()> {
349 let mut cards = self.cards.write().await;
350 if let Some(card) = cards.remove(&agent_id) {
351 tracing::info!(agent_id = %agent_id, name = %card.name, "Agent unregistered from A2A registry");
352 drop(cards);
353
354 self.event_bus
355 .publish(KernelEvent::AgentStopped { id: agent_id })?;
356 }
357 Ok(())
358 }
359
360 pub async fn find_agents_by_capability(&self, capability: &str) -> Result<Vec<AgentCard>> {
362 let cards = self.cards.read().await;
363 let matches: Vec<AgentCard> = cards
364 .values()
365 .filter(|card| card.has_capability(capability))
366 .cloned()
367 .collect();
368 Ok(matches)
369 }
370
371 pub async fn find_agents_by_skill(&self, skill: &str) -> Result<Vec<AgentCard>> {
373 let cards = self.cards.read().await;
374 let matches: Vec<AgentCard> = cards
375 .values()
376 .filter(|card| card.has_skill(skill))
377 .cloned()
378 .collect();
379 Ok(matches)
380 }
381
382 pub async fn get_agent(&self, agent_id: AgentId) -> Option<AgentCard> {
384 let cards = self.cards.read().await;
385 cards.get(&agent_id).cloned()
386 }
387
388 pub async fn list_agents(&self) -> Vec<AgentCard> {
390 let cards = self.cards.read().await;
391 cards.values().cloned().collect()
392 }
393
394 pub async fn agent_count(&self) -> usize {
396 let cards = self.cards.read().await;
397 cards.len()
398 }
399
400 pub async fn update_status(&self, agent_id: AgentId, status: AgentStatus) -> Result<()> {
402 let mut cards = self.cards.write().await;
403 if let Some(card) = cards.get_mut(&agent_id) {
404 card.status = status;
405 }
406 Ok(())
407 }
408}
409
410impl std::fmt::Debug for AgentCardRegistry {
411 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
412 f.debug_struct("AgentCardRegistry").finish()
413 }
414}
415
416struct AgentQueue {
421 messages: parking_lot::Mutex<Vec<PendingMessage>>,
423 notify: tokio::sync::Notify,
425}
426
427impl AgentQueue {
428 fn new() -> Self {
429 Self {
430 messages: parking_lot::Mutex::new(Vec::new()),
431 notify: tokio::sync::Notify::new(),
432 }
433 }
434}
435
436pub type DelegationHandler = Arc<
441 dyn Fn(
442 AgentId,
443 AgentId,
444 TaskSpec,
445 )
446 -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<serde_json::Value>> + Send>>
447 + Send
448 + Sync,
449>;
450
451#[derive(Debug, Clone, Serialize, Deserialize)]
457pub struct A2AMessageLogEntry {
458 pub from: AgentId,
460 pub to: AgentId,
462 pub message_type: String,
464 pub timestamp: DateTime<Utc>,
466 pub content: String,
468}
469
470#[derive(Debug, Clone, Serialize, Deserialize)]
474pub struct TopologyNode {
475 pub id: String,
477 pub label: String,
479 pub status: String,
481 pub capabilities: Vec<String>,
483 pub skills: Vec<String>,
485 pub last_seen: Option<String>,
488}
489
490#[derive(Debug, Clone, Serialize, Deserialize)]
496pub struct TopologyEdge {
497 pub from: String,
499 pub to: String,
501 pub message_count_5m: u32,
503 pub last_kind: String,
505}
506
507#[derive(Debug, Clone, Serialize, Deserialize)]
509pub struct TopologyResponse {
510 pub nodes: Vec<TopologyNode>,
512 pub edges: Vec<TopologyEdge>,
514}
515
516#[derive(Clone)]
518pub struct A2AProtocol {
519 registry: AgentCardRegistry,
521 queues: Arc<RwLock<HashMap<AgentId, Arc<AgentQueue>>>>,
523 event_bus: EventBus,
525 delegation_handler: Arc<RwLock<Option<DelegationHandler>>>,
527 message_log: Arc<parking_lot::RwLock<Vec<A2AMessageLogEntry>>>,
529}
530
531impl A2AProtocol {
532 pub const MAX_LOG_ENTRIES: usize = 10_000;
534
535 pub fn new(event_bus: EventBus) -> Self {
537 let registry = AgentCardRegistry::new(event_bus.clone());
538 Self {
539 registry,
540 queues: Arc::new(RwLock::new(HashMap::new())),
541 event_bus,
542 delegation_handler: Arc::new(RwLock::new(None)),
543 message_log: Arc::new(parking_lot::RwLock::new(Vec::with_capacity(256))),
544 }
545 }
546
547 pub async fn set_delegation_handler(&self, handler: DelegationHandler) {
553 let mut h = self.delegation_handler.write().await;
554 *h = Some(handler);
555 }
556
557 fn append_log(&self, entry: A2AMessageLogEntry) {
559 let mut log = self.message_log.write();
560 log.push(entry);
561 if log.len() > Self::MAX_LOG_ENTRIES {
562 let excess = log.len() - Self::MAX_LOG_ENTRIES;
563 log.drain(..excess);
564 }
565 }
566
567 pub fn get_message_log(&self, limit: Option<usize>) -> Vec<A2AMessageLogEntry> {
571 let log = self.message_log.read();
572 match limit {
573 Some(n) => log
574 .iter()
575 .rev()
576 .take(n)
577 .cloned()
578 .collect::<Vec<_>>()
579 .into_iter()
580 .rev()
581 .collect(),
582 None => log.clone(),
583 }
584 }
585
586 pub fn recent_messages(&self, secs: u64) -> Vec<A2AMessageLogEntry> {
592 let now = Utc::now();
593 let cutoff = now - chrono::Duration::seconds(secs as i64);
594 let log = self.message_log.read();
595 log.iter()
596 .filter(|entry| entry.timestamp >= cutoff)
597 .cloned()
598 .collect()
599 }
600
601 async fn get_or_create_queue(&self, agent_id: AgentId) -> Arc<AgentQueue> {
603 let mut queues = self.queues.write().await;
604 queues
605 .entry(agent_id)
606 .or_insert_with(|| Arc::new(AgentQueue::new()))
607 .clone()
608 }
609
610 pub fn registry(&self) -> &AgentCardRegistry {
612 &self.registry
613 }
614
615 pub async fn execute_delegation(
622 &self,
623 from: AgentId,
624 to: AgentId,
625 task: TaskSpec,
626 ) -> Option<Result<serde_json::Value>> {
627 let handler = self.delegation_handler.read().await;
628 let handler_ref = handler.as_ref()?;
629
630 let _ = self.event_bus.publish(KernelEvent::MessageReceived {
632 from,
633 content: format!("[task_delegation] {:?}", task.task_id),
634 });
635
636 self.append_log(A2AMessageLogEntry {
638 from,
639 to,
640 message_type: "task_delegation".to_string(),
641 timestamp: Utc::now(),
642 content: task.description.clone(),
643 });
644
645 tracing::info!(
646 from = %from,
647 to = %to,
648 task_id = %task.task_id,
649 "A2A execute_delegation: starting"
650 );
651
652 let result = handler_ref(from, to, task).await;
653
654 tracing::info!(
655 from = %from,
656 to = %to,
657 success = result.is_ok(),
658 "A2A execute_delegation: completed"
659 );
660
661 Some(result)
662 }
663
664 pub async fn send_message(
666 &self,
667 from: AgentId,
668 to: AgentId,
669 message: A2AMessage,
670 ) -> Result<Uuid> {
671 let msg_type = message.type_name();
672 let request = A2ARequest::new(from, to, message.clone());
673 let request_id = request.request_id;
674
675 let content_summary = match &request.message {
677 A2AMessage::TaskDelegation { description, .. } => description.clone(),
678 A2AMessage::StatusUpdate { message, .. } => message.clone(),
679 A2AMessage::ResultSharing { summary, .. } => summary.clone(),
680 A2AMessage::CapabilityQuery { query, .. } => query.clone(),
681 A2AMessage::Handshake { name, .. } => format!("handshake from {name}"),
682 };
683 self.append_log(A2AMessageLogEntry {
684 from,
685 to,
686 message_type: msg_type.to_string(),
687 timestamp: Utc::now(),
688 content: content_summary,
689 });
690
691 let queue = self.get_or_create_queue(to).await;
693 queue
694 .messages
695 .lock()
696 .push(PendingMessage::new(request.clone()));
697 queue.notify.notify_one();
698
699 self.event_bus.publish(KernelEvent::MessageReceived {
700 from,
701 content: format!("[{msg_type}] {request_id:?}"),
702 })?;
703
704 tracing::debug!(
705 from = %from,
706 to = %to,
707 request_id = %request_id,
708 msg_type,
709 "A2A message sent"
710 );
711
712 Ok(request_id)
713 }
714
715 pub async fn delegate_task(&self, from: AgentId, to: AgentId, task: TaskSpec) -> Result<Uuid> {
717 let message = A2AMessage::TaskDelegation {
718 task_id: task.task_id,
719 description: task.description.clone(),
720 payload: task.payload.clone(),
721 priority: task.priority,
722 };
723
724 self.send_message(from, to, message).await
725 }
726
727 pub async fn send_status_update(
729 &self,
730 from: AgentId,
731 to: AgentId,
732 task_id: Uuid,
733 progress: u8,
734 message: String,
735 ) -> Result<Uuid> {
736 let message = A2AMessage::StatusUpdate {
737 task_id,
738 progress,
739 message,
740 };
741
742 self.send_message(from, to, message).await
743 }
744
745 pub async fn share_result(
747 &self,
748 from: AgentId,
749 to: AgentId,
750 task_id: Uuid,
751 result: serde_json::Value,
752 summary: String,
753 ) -> Result<Uuid> {
754 let message = A2AMessage::ResultSharing {
755 task_id,
756 result,
757 summary,
758 };
759
760 self.send_message(from, to, message).await
761 }
762
763 pub async fn query_capabilities(&self, capability: &str) -> Result<Vec<AgentCard>> {
765 self.registry.find_agents_by_capability(capability).await
766 }
767
768 pub async fn send_handshake(&self, from: AgentId, to: AgentId) -> Result<Uuid> {
770 let card = self.registry.get_agent(from).await;
771
772 let (name, capabilities) = if let Some(card) = card {
773 (card.name, card.capabilities.clone())
774 } else {
775 ("unknown".into(), Vec::new())
776 };
777
778 let message = A2AMessage::Handshake {
779 agent_id: from,
780 name,
781 capabilities,
782 };
783
784 self.send_message(from, to, message).await
785 }
786
787 pub async fn receive_messages(&self, agent_id: AgentId) -> Vec<A2ARequest> {
789 let queues = self.queues.read().await;
790 if let Some(queue) = queues.get(&agent_id) {
791 let drained: Vec<PendingMessage> = queue.messages.lock().drain(..).collect();
792 drained.into_iter().map(|m| m.request).collect()
793 } else {
794 Vec::new()
795 }
796 }
797
798 pub async fn pending_count(&self, agent_id: AgentId) -> usize {
800 let queues = self.queues.read().await;
801 queues
802 .get(&agent_id)
803 .map(|q| q.messages.lock().len())
804 .unwrap_or(0)
805 }
806
807 pub async fn has_messages(&self, agent_id: AgentId) -> bool {
809 self.pending_count(agent_id).await > 0
810 }
811
812 pub async fn deliver_pending_messages(&self, agent_id: AgentId) -> Result<Vec<A2ARequest>> {
818 Ok(self.receive_messages(agent_id).await)
819 }
820
821 pub async fn send_and_wait(
829 &self,
830 from: AgentId,
831 to: AgentId,
832 message: A2AMessage,
833 timeout: std::time::Duration,
834 ) -> Result<A2AResponse> {
835 let wait_task_id = match &message {
837 A2AMessage::TaskDelegation { task_id, .. } => Some(*task_id),
838 _ => None,
839 };
840
841 let request_id = self.send_message(from, to, message).await?;
842 let queue = self.get_or_create_queue(from).await;
843 let deadline = tokio::time::Instant::now() + timeout;
844
845 loop {
846 {
848 let mut msgs = queue.messages.lock();
849 let match_idx = msgs.iter().position(|p| {
850 match (&p.request.message, wait_task_id) {
851 (A2AMessage::ResultSharing { task_id, .. }, Some(wait_id)) => {
853 *task_id == wait_id
854 }
855 (A2AMessage::ResultSharing { result, .. }, None) => {
857 result.get("request_id").and_then(|v| v.as_str())
858 == Some(&request_id.to_string())
859 }
860 _ => false,
861 }
862 });
863 if let Some(idx) = match_idx {
864 let matched = msgs.remove(idx);
865 if let A2AMessage::ResultSharing { result, .. } = matched.request.message {
866 return Ok(A2AResponse::success(request_id, to, from, result));
867 }
868 }
869 }
870
871 let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
873 if remaining.is_zero() {
874 anyhow::bail!("A2A response timeout after {timeout:?}");
875 }
876
877 tokio::select! {
878 _ = queue.notify.notified() => {
879 }
881 _ = tokio::time::sleep(remaining) => {
882 anyhow::bail!("A2A response timeout after {timeout:?}");
883 }
884 }
885 }
886 }
887}
888
889impl std::fmt::Debug for A2AProtocol {
890 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
891 f.debug_struct("A2AProtocol")
892 .field("registry", &self.registry)
893 .finish()
894 }
895}
896
897#[cfg(test)]
898mod tests {
899 use super::*;
900
901 fn create_test_event_bus() -> EventBus {
902 EventBus::new(256)
903 }
904
905 fn create_test_agent_id() -> AgentId {
906 Uuid::new_v4()
907 }
908
909 #[tokio::test]
910 async fn test_agent_card_creation() {
911 let agent_id = create_test_agent_id();
912 let card = AgentCard::new(agent_id, "test-agent", "A test agent")
913 .with_capability("code-review")
914 .with_capability("lint")
915 .with_skill("rust")
916 .with_endpoint("local");
917
918 assert_eq!(card.agent_id, agent_id);
919 assert_eq!(card.name, "test-agent");
920 assert!(card.has_capability("code-review"));
921 assert!(card.has_capability("lint"));
922 assert!(!card.has_capability("refactor"));
923 assert!(card.has_skill("rust"));
924 assert!(!card.has_skill("python"));
925 }
926
927 #[tokio::test]
928 async fn test_registry_register_unregister() {
929 let bus = create_test_event_bus();
930 let registry = AgentCardRegistry::new(bus);
931
932 let agent_id = create_test_agent_id();
933 let card = AgentCard::new(agent_id, "register-test", "Test agent").with_capability("test");
934
935 registry.register_agent(card.clone()).await.unwrap();
936 assert_eq!(registry.agent_count().await, 1);
937
938 let found = registry.get_agent(agent_id).await;
939 assert!(found.is_some());
940 assert_eq!(found.unwrap().name, "register-test");
941
942 registry.unregister_agent(agent_id).await.unwrap();
943 assert_eq!(registry.agent_count().await, 0);
944
945 let found = registry.get_agent(agent_id).await;
946 assert!(found.is_none());
947 }
948
949 #[tokio::test]
950 async fn test_registry_find_by_capability() {
951 let bus = create_test_event_bus();
952 let registry = AgentCardRegistry::new(bus);
953
954 let id1 = Uuid::new_v4();
955 let id2 = Uuid::new_v4();
956
957 registry
958 .register_agent(
959 AgentCard::new(id1, "agent-1", "First agent").with_capability("code-review"),
960 )
961 .await
962 .unwrap();
963
964 registry
965 .register_agent(
966 AgentCard::new(id2, "agent-2", "Second agent")
967 .with_capability("code-review")
968 .with_capability("refactor"),
969 )
970 .await
971 .unwrap();
972
973 let reviewers = registry
974 .find_agents_by_capability("code-review")
975 .await
976 .unwrap();
977 assert_eq!(reviewers.len(), 2);
978 }
979
980 #[tokio::test]
981 async fn test_a2a_protocol_send_receive() {
982 let bus = create_test_event_bus();
983 let a2a = A2AProtocol::new(bus);
984
985 let from = create_test_agent_id();
986 let to = create_test_agent_id();
987
988 let message = A2AMessage::Handshake {
989 agent_id: from,
990 name: "sender".into(),
991 capabilities: vec!["test".into()],
992 };
993
994 a2a.send_message(from, to, message).await.unwrap();
995 assert_eq!(a2a.pending_count(to).await, 1);
996
997 let messages = a2a.receive_messages(to).await;
998 assert_eq!(messages.len(), 1);
999 assert_eq!(messages[0].from, from);
1000 assert_eq!(messages[0].to, to);
1001 assert_eq!(a2a.pending_count(to).await, 0);
1002 }
1003
1004 #[tokio::test]
1005 async fn test_delegate_task() {
1006 let bus = create_test_event_bus();
1007 let a2a = A2AProtocol::new(bus);
1008
1009 let from = create_test_agent_id();
1010 let to = create_test_agent_id();
1011
1012 let task = TaskSpec::new("Review PR", serde_json::json!({ "pr": 42 }));
1013
1014 let request_id = a2a.delegate_task(from, to, task).await.unwrap();
1015 assert!(request_id != Uuid::nil());
1016
1017 let messages = a2a.receive_messages(to).await;
1018 assert_eq!(messages.len(), 1);
1019 }
1020
1021 #[test]
1022 fn test_recent_messages_filters_by_window() {
1023 let bus = create_test_event_bus();
1024 let a2a = A2AProtocol::new(bus);
1025
1026 let recent_ts = Utc::now();
1028 a2a.append_log(A2AMessageLogEntry {
1029 from: Uuid::new_v4(),
1030 to: Uuid::new_v4(),
1031 message_type: "task_delegation".into(),
1032 timestamp: recent_ts,
1033 content: "recent".into(),
1034 });
1035
1036 let old_ts = Utc::now() - chrono::Duration::seconds(600);
1038 a2a.append_log(A2AMessageLogEntry {
1039 from: Uuid::new_v4(),
1040 to: Uuid::new_v4(),
1041 message_type: "handshake".into(),
1042 timestamp: old_ts,
1043 content: "old".into(),
1044 });
1045
1046 let window = a2a.recent_messages(300);
1048 assert_eq!(window.len(), 1);
1049 assert_eq!(window[0].content, "recent");
1050 assert_eq!(window[0].message_type, "task_delegation");
1051
1052 let wider = a2a.recent_messages(900);
1054 assert_eq!(wider.len(), 2);
1055
1056 let narrow = a2a.recent_messages(1);
1058 assert_eq!(narrow.len(), 1);
1059 assert_eq!(narrow[0].content, "recent");
1060 }
1061
1062 #[tokio::test]
1063 async fn test_recent_messages_aggregates_fan_in_fan_out() {
1064 let bus = create_test_event_bus();
1066 let a2a = A2AProtocol::new(bus);
1067
1068 let orch = Uuid::new_v4();
1070 let worker_a = Uuid::new_v4();
1071 let worker_b = Uuid::new_v4();
1072 for (id, name) in [
1073 (orch, "orchestrator"),
1074 (worker_a, "worker-a"),
1075 (worker_b, "worker-b"),
1076 ] {
1077 a2a.registry
1078 .register_agent(AgentCard::new(id, name, "test").with_status(AgentStatus::Running))
1079 .await
1080 .unwrap();
1081 }
1082
1083 for _ in 0..2 {
1085 a2a.append_log(A2AMessageLogEntry {
1086 from: orch,
1087 to: worker_a,
1088 message_type: "task_delegation".into(),
1089 timestamp: Utc::now(),
1090 content: "do work".into(),
1091 });
1092 }
1093
1094 a2a.append_log(A2AMessageLogEntry {
1096 from: orch,
1097 to: worker_b,
1098 message_type: "task_delegation".into(),
1099 timestamp: Utc::now(),
1100 content: "do work b".into(),
1101 });
1102 a2a.append_log(A2AMessageLogEntry {
1103 from: worker_b,
1104 to: orch,
1105 message_type: "status_update".into(),
1106 timestamp: Utc::now(),
1107 content: "50%".into(),
1108 });
1109
1110 a2a.append_log(A2AMessageLogEntry {
1112 from: worker_a,
1113 to: orch,
1114 message_type: "result_sharing".into(),
1115 timestamp: Utc::now(),
1116 content: "done".into(),
1117 });
1118
1119 let entries = a2a.recent_messages(300);
1122 let mut aggregates: HashMap<(AgentId, AgentId), (u32, String)> = HashMap::new();
1123 for entry in &entries {
1124 let agg = aggregates
1125 .entry((entry.from, entry.to))
1126 .or_insert((0, String::new()));
1127 agg.0 = agg.0.saturating_add(1);
1128 agg.1 = entry.message_type.clone();
1129 }
1130
1131 let e1 = aggregates.get(&(orch, worker_a)).expect("edge 1 missing");
1133 assert_eq!(e1.0, 2, "orch->worker_a count");
1134 assert_eq!(e1.1, "task_delegation", "orch->worker_a last_kind");
1135
1136 let e2 = aggregates.get(&(orch, worker_b)).expect("edge 2 missing");
1138 assert_eq!(e2.0, 1, "orch->worker_b count");
1139 assert_eq!(e2.1, "task_delegation", "orch->worker_b last_kind");
1140
1141 let e3 = aggregates.get(&(worker_b, orch)).expect("edge 3 missing");
1143 assert_eq!(e3.0, 1, "worker_b->orch count");
1144 assert_eq!(e3.1, "status_update", "worker_b->orch last_kind");
1145
1146 let e4 = aggregates.get(&(worker_a, orch)).expect("edge 4 missing");
1148 assert_eq!(e4.0, 1, "worker_a->orch count");
1149 assert_eq!(e4.1, "result_sharing", "worker_a->orch last_kind");
1150
1151 assert_eq!(aggregates.len(), 4);
1153 }
1154}