terraphim_kg_agents 1.0.0

Specialized knowledge graph-based agent implementations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
//! Knowledge graph-based coordination agent implementation
//!
//! This module provides a specialized GenAgent implementation for supervising
//! and coordinating multiple agents in complex workflows.

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use log::{debug, info, warn};
use serde::{Deserialize, Serialize};

use terraphim_agent_registry::{
    AgentMetadata, KnowledgeGraphAgentMatcher, TerraphimKnowledgeGraphMatcher,
};
use terraphim_automata::Automata;
use terraphim_gen_agent::{GenAgent, GenAgentResult};
use terraphim_rolegraph::RoleGraph;
use terraphim_task_decomposition::Task;

use crate::{KgAgentError, KgAgentResult};

/// Message types for the coordination agent
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum CoordinationMessage {
    /// Start coordinating a workflow
    StartWorkflow {
        workflow_id: String,
        tasks: Vec<Task>,
        available_agents: Vec<AgentMetadata>,
    },
    /// Monitor workflow progress
    MonitorWorkflow { workflow_id: String },
    /// Handle agent failure
    HandleAgentFailure {
        agent_id: String,
        workflow_id: String,
    },
    /// Reassign task to different agent
    ReassignTask {
        task_id: String,
        new_agent_id: String,
    },
    /// Get workflow status
    GetWorkflowStatus { workflow_id: String },
    /// Cancel workflow
    CancelWorkflow { workflow_id: String },
    /// Update agent availability
    UpdateAgentAvailability { agent_id: String, available: bool },
}

/// Coordination agent state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordinationState {
    /// Active workflows
    pub active_workflows: HashMap<String, WorkflowExecution>,
    /// Agent availability tracking
    pub agent_availability: HashMap<String, AgentAvailability>,
    /// Coordination statistics
    pub stats: CoordinationStats,
    /// Configuration
    pub config: CoordinationConfig,
}

/// Workflow execution state
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowExecution {
    /// Workflow identifier
    pub workflow_id: String,
    /// Original tasks
    pub tasks: Vec<Task>,
    /// Task assignments
    pub task_assignments: HashMap<String, String>, // task_id -> agent_id
    /// Task execution status
    pub task_status: HashMap<String, TaskExecutionStatus>,
    /// Workflow start time
    pub start_time: std::time::SystemTime,
    /// Workflow status
    pub status: WorkflowStatus,
    /// Progress percentage
    pub progress: f64,
    /// Issues encountered
    pub issues: Vec<WorkflowIssue>,
}

/// Task execution status within a workflow
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum TaskExecutionStatus {
    Pending,
    Assigned,
    InProgress,
    Completed,
    Failed,
    Reassigned,
}

/// Workflow execution status
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum WorkflowStatus {
    Planning,
    Executing,
    Completed,
    Failed,
    Cancelled,
}

/// Workflow issue tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WorkflowIssue {
    /// Issue identifier
    pub issue_id: String,
    /// Issue type
    pub issue_type: IssueType,
    /// Description
    pub description: String,
    /// Affected task or agent
    pub affected_entity: String,
    /// Timestamp
    pub timestamp: std::time::SystemTime,
    /// Resolution status
    pub resolved: bool,
}

/// Types of workflow issues
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum IssueType {
    AgentFailure,
    TaskTimeout,
    DependencyViolation,
    ResourceConstraint,
    QualityIssue,
}

/// Agent availability information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentAvailability {
    /// Agent identifier
    pub agent_id: String,
    /// Current availability status
    pub available: bool,
    /// Current workload (number of assigned tasks)
    pub current_workload: u32,
    /// Maximum capacity
    pub max_capacity: u32,
    /// Last seen timestamp
    pub last_seen: std::time::SystemTime,
    /// Performance metrics
    pub performance: AgentPerformance,
}

/// Agent performance tracking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentPerformance {
    /// Success rate
    pub success_rate: f64,
    /// Average response time
    pub avg_response_time: std::time::Duration,
    /// Reliability score
    pub reliability_score: f64,
    /// Tasks completed
    pub tasks_completed: u64,
}

impl Default for AgentPerformance {
    fn default() -> Self {
        Self {
            success_rate: 1.0,
            avg_response_time: std::time::Duration::from_secs(60),
            reliability_score: 1.0,
            tasks_completed: 0,
        }
    }
}

/// Coordination statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordinationStats {
    /// Total workflows coordinated
    pub total_workflows: u64,
    /// Successful workflows
    pub successful_workflows: u64,
    /// Average workflow completion time
    pub avg_completion_time: std::time::Duration,
    /// Agent utilization rates
    pub agent_utilization: HashMap<String, f64>,
    /// Issue resolution rate
    pub issue_resolution_rate: f64,
}

impl Default for CoordinationStats {
    fn default() -> Self {
        Self {
            total_workflows: 0,
            successful_workflows: 0,
            avg_completion_time: std::time::Duration::ZERO,
            agent_utilization: HashMap::new(),
            issue_resolution_rate: 1.0,
        }
    }
}

/// Coordination agent configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CoordinationConfig {
    /// Maximum concurrent workflows
    pub max_concurrent_workflows: usize,
    /// Workflow monitoring interval
    pub monitoring_interval: std::time::Duration,
    /// Task timeout threshold
    pub task_timeout: std::time::Duration,
    /// Agent failure detection timeout
    pub agent_failure_timeout: std::time::Duration,
    /// Enable automatic task reassignment
    pub enable_auto_reassignment: bool,
    /// Maximum reassignment attempts
    pub max_reassignment_attempts: u32,
}

impl Default for CoordinationConfig {
    fn default() -> Self {
        Self {
            max_concurrent_workflows: 10,
            monitoring_interval: std::time::Duration::from_secs(30),
            task_timeout: std::time::Duration::from_secs(300),
            agent_failure_timeout: std::time::Duration::from_secs(60),
            enable_auto_reassignment: true,
            max_reassignment_attempts: 3,
        }
    }
}

impl Default for CoordinationState {
    fn default() -> Self {
        Self {
            active_workflows: HashMap::new(),
            agent_availability: HashMap::new(),
            stats: CoordinationStats::default(),
            config: CoordinationConfig::default(),
        }
    }
}

/// Knowledge graph-based coordination agent
pub struct KnowledgeGraphCoordinationAgent {
    /// Agent identifier
    agent_id: String,
    /// Agent matcher for task assignment
    agent_matcher: Arc<TerraphimKnowledgeGraphMatcher>,
    /// Agent state
    state: CoordinationState,
}

impl KnowledgeGraphCoordinationAgent {
    /// Create a new coordination agent
    pub fn new(
        agent_id: String,
        automata: Arc<Automata>,
        role_graphs: HashMap<String, Arc<RoleGraph>>,
        config: CoordinationConfig,
    ) -> Self {
        let agent_matcher = Arc::new(TerraphimKnowledgeGraphMatcher::with_default_config(
            automata,
            role_graphs,
        ));

        let state = CoordinationState {
            active_workflows: HashMap::new(),
            agent_availability: HashMap::new(),
            stats: CoordinationStats::default(),
            config,
        };

        Self {
            agent_id,
            agent_matcher,
            state,
        }
    }

    /// Start coordinating a workflow
    async fn start_workflow(
        &mut self,
        workflow_id: String,
        tasks: Vec<Task>,
        available_agents: Vec<AgentMetadata>,
    ) -> KgAgentResult<WorkflowExecution> {
        info!("Starting workflow coordination: {}", workflow_id);

        if self.state.active_workflows.len() >= self.state.config.max_concurrent_workflows {
            return Err(KgAgentError::CoordinationFailed(
                "Maximum concurrent workflows reached".to_string(),
            ));
        }

        // Initialize agent availability tracking
        for agent in &available_agents {
            self.state.agent_availability.insert(
                agent.agent_id.to_string(),
                AgentAvailability {
                    agent_id: agent.agent_id.to_string(),
                    available: true,
                    current_workload: 0,
                    max_capacity: 5, // Default capacity
                    last_seen: std::time::SystemTime::now(),
                    performance: AgentPerformance::default(),
                },
            );
        }

        // Create initial workflow execution state
        let mut workflow = WorkflowExecution {
            workflow_id: workflow_id.clone(),
            tasks: tasks.clone(),
            task_assignments: HashMap::new(),
            task_status: HashMap::new(),
            start_time: std::time::SystemTime::now(),
            status: WorkflowStatus::Planning,
            progress: 0.0,
            issues: Vec::new(),
        };

        // Initialize task status
        for task in &tasks {
            workflow
                .task_status
                .insert(task.task_id.clone(), TaskExecutionStatus::Pending);
        }

        // Assign tasks to agents using knowledge graph matching
        let coordination_result = self
            .agent_matcher
            .coordinate_workflow(&tasks, &available_agents)
            .await
            .map_err(|e| KgAgentError::CoordinationFailed(e.to_string()))?;

        // Update task assignments based on coordination result
        for step in &coordination_result.steps {
            workflow
                .task_assignments
                .insert(step.step_id.clone(), step.assigned_agent.clone());
            workflow
                .task_status
                .insert(step.step_id.clone(), TaskExecutionStatus::Assigned);

            // Update agent workload
            if let Some(availability) = self.state.agent_availability.get_mut(&step.assigned_agent)
            {
                availability.current_workload += 1;
            }
        }

        workflow.status = WorkflowStatus::Executing;
        self.state
            .active_workflows
            .insert(workflow_id.clone(), workflow.clone());
        self.state.stats.total_workflows += 1;

        info!(
            "Workflow {} started with {} tasks assigned to {} agents",
            workflow_id,
            tasks.len(),
            coordination_result.agent_assignments.len()
        );

        Ok(workflow)
    }

    /// Monitor workflow progress
    async fn monitor_workflow(&mut self, workflow_id: &str) -> KgAgentResult<WorkflowExecution> {
        debug!("Monitoring workflow: {}", workflow_id);

        let workflow = self
            .state
            .active_workflows
            .get_mut(workflow_id)
            .ok_or_else(|| {
                KgAgentError::CoordinationFailed(format!("Workflow {} not found", workflow_id))
            })?;

        // Check for task timeouts
        let now = std::time::SystemTime::now();
        let timeout_threshold = self.state.config.task_timeout;

        for (task_id, status) in &mut workflow.task_status {
            if *status == TaskExecutionStatus::InProgress {
                let elapsed = now.duration_since(workflow.start_time).unwrap_or_default();
                if elapsed > timeout_threshold {
                    *status = TaskExecutionStatus::Failed;
                    workflow.issues.push(WorkflowIssue {
                        issue_id: format!("timeout_{}", uuid::Uuid::new_v4()),
                        issue_type: IssueType::TaskTimeout,
                        description: format!(
                            "Task {} timed out after {:.2}s",
                            task_id,
                            elapsed.as_secs_f64()
                        ),
                        affected_entity: task_id.clone(),
                        timestamp: now,
                        resolved: false,
                    });
                }
            }
        }

        // Check agent availability
        for (agent_id, availability) in &mut self.state.agent_availability {
            let elapsed = now
                .duration_since(availability.last_seen)
                .unwrap_or_default();
            if elapsed > self.state.config.agent_failure_timeout {
                availability.available = false;
                workflow.issues.push(WorkflowIssue {
                    issue_id: format!("agent_failure_{}", uuid::Uuid::new_v4()),
                    issue_type: IssueType::AgentFailure,
                    description: format!("Agent {} appears to be unavailable", agent_id),
                    affected_entity: agent_id.clone(),
                    timestamp: now,
                    resolved: false,
                });
            }
        }

        // Update progress
        let total_tasks = workflow.task_status.len();
        let completed_tasks = workflow
            .task_status
            .values()
            .filter(|&status| *status == TaskExecutionStatus::Completed)
            .count();

        workflow.progress = if total_tasks > 0 {
            completed_tasks as f64 / total_tasks as f64
        } else {
            0.0
        };

        // Update workflow status
        if workflow.progress >= 1.0 {
            workflow.status = WorkflowStatus::Completed;
            self.state.stats.successful_workflows += 1;
        } else if workflow
            .task_status
            .values()
            .any(|status| *status == TaskExecutionStatus::Failed)
        {
            workflow.status = WorkflowStatus::Failed;
        }

        debug!(
            "Workflow {} progress: {:.1}%, status: {:?}",
            workflow_id,
            workflow.progress * 100.0,
            workflow.status
        );

        Ok(workflow.clone())
    }

    /// Handle agent failure
    async fn handle_agent_failure(
        &mut self,
        agent_id: &str,
        workflow_id: &str,
    ) -> KgAgentResult<()> {
        warn!(
            "Handling agent failure: {} in workflow {}",
            agent_id, workflow_id
        );

        // Mark agent as unavailable
        if let Some(availability) = self.state.agent_availability.get_mut(agent_id) {
            availability.available = false;
            availability.current_workload = 0;
        }

        // Find tasks assigned to the failed agent
        let workflow = self
            .state
            .active_workflows
            .get_mut(workflow_id)
            .ok_or_else(|| {
                KgAgentError::CoordinationFailed(format!("Workflow {} not found", workflow_id))
            })?;

        let failed_tasks: Vec<String> = workflow
            .task_assignments
            .iter()
            .filter(|(_, assigned_agent)| *assigned_agent == agent_id)
            .map(|(task_id, _)| task_id.clone())
            .collect();

        // Attempt to reassign tasks if auto-reassignment is enabled
        if self.state.config.enable_auto_reassignment {
            for task_id in failed_tasks {
                if let Err(e) = self.reassign_task(&task_id, workflow_id).await {
                    warn!("Failed to reassign task {}: {}", task_id, e);
                    workflow
                        .task_status
                        .insert(task_id, TaskExecutionStatus::Failed);
                }
            }
        }

        Ok(())
    }

    /// Reassign a task to a different agent
    async fn reassign_task(&mut self, task_id: &str, workflow_id: &str) -> KgAgentResult<String> {
        debug!("Reassigning task {} in workflow {}", task_id, workflow_id);

        let workflow = self
            .state
            .active_workflows
            .get_mut(workflow_id)
            .ok_or_else(|| {
                KgAgentError::CoordinationFailed(format!("Workflow {} not found", workflow_id))
            })?;

        // Find the task
        let task = workflow
            .tasks
            .iter()
            .find(|t| t.task_id == task_id)
            .ok_or_else(|| {
                KgAgentError::CoordinationFailed(format!(
                    "Task {} not found in workflow {}",
                    task_id, workflow_id
                ))
            })?;

        // Find available agents
        let available_agents: Vec<AgentMetadata> = self
            .state
            .agent_availability
            .values()
            .filter(|a| a.available && a.current_workload < a.max_capacity)
            .map(|a| {
                // Create a minimal AgentMetadata for matching
                // In a real implementation, this would come from the agent registry
                let agent_id = crate::AgentPid::from_string(a.agent_id.clone());
                let supervisor_id = crate::SupervisorId::new();
                let role = terraphim_agent_registry::AgentRole::new(
                    "worker".to_string(),
                    "Worker Agent".to_string(),
                    "General purpose worker".to_string(),
                );
                AgentMetadata::new(agent_id, supervisor_id, role)
            })
            .collect();

        if available_agents.is_empty() {
            return Err(KgAgentError::CoordinationFailed(
                "No available agents for task reassignment".to_string(),
            ));
        }

        // Use agent matcher to find the best agent
        let matches = self
            .agent_matcher
            .match_task_to_agents(task, &available_agents, 1)
            .await
            .map_err(|e| KgAgentError::CoordinationFailed(e.to_string()))?;

        let best_match = matches.first().ok_or_else(|| {
            KgAgentError::CoordinationFailed("No suitable agent found for reassignment".to_string())
        })?;

        let new_agent_id = best_match.agent.agent_id.to_string();

        // Update task assignment
        workflow
            .task_assignments
            .insert(task_id.to_string(), new_agent_id.clone());
        workflow
            .task_status
            .insert(task_id.to_string(), TaskExecutionStatus::Reassigned);

        // Update agent workload
        if let Some(availability) = self.state.agent_availability.get_mut(&new_agent_id) {
            availability.current_workload += 1;
        }

        info!("Task {} reassigned to agent {}", task_id, new_agent_id);
        Ok(new_agent_id)
    }

    /// Update agent availability
    fn update_agent_availability(&mut self, agent_id: &str, available: bool) {
        if let Some(availability) = self.state.agent_availability.get_mut(agent_id) {
            availability.available = available;
            availability.last_seen = std::time::SystemTime::now();
            if !available {
                availability.current_workload = 0;
            }
        }
    }

    /// Cancel a workflow
    async fn cancel_workflow(&mut self, workflow_id: &str) -> KgAgentResult<()> {
        info!("Cancelling workflow: {}", workflow_id);

        let workflow = self
            .state
            .active_workflows
            .get_mut(workflow_id)
            .ok_or_else(|| {
                KgAgentError::CoordinationFailed(format!("Workflow {} not found", workflow_id))
            })?;

        workflow.status = WorkflowStatus::Cancelled;

        // Free up agent resources
        for (_, agent_id) in &workflow.task_assignments {
            if let Some(availability) = self.state.agent_availability.get_mut(agent_id) {
                availability.current_workload = availability.current_workload.saturating_sub(1);
            }
        }

        Ok(())
    }
}

#[async_trait]
impl GenAgent<CoordinationState> for KnowledgeGraphCoordinationAgent {
    type Message = CoordinationMessage;

    async fn init(&mut self, _init_args: serde_json::Value) -> GenAgentResult<()> {
        info!("Initializing coordination agent: {}", self.agent_id);
        Ok(())
    }

    async fn handle_call(&mut self, message: Self::Message) -> GenAgentResult<serde_json::Value> {
        match message {
            CoordinationMessage::StartWorkflow {
                workflow_id,
                tasks,
                available_agents,
            } => {
                let workflow = self
                    .start_workflow(workflow_id, tasks, available_agents)
                    .await
                    .map_err(|e| {
                        terraphim_gen_agent::GenAgentError::ExecutionError(
                            self.agent_id.clone(),
                            e.to_string(),
                        )
                    })?;
                Ok(serde_json::to_value(workflow).unwrap())
            }
            CoordinationMessage::MonitorWorkflow { workflow_id } => {
                let workflow = self.monitor_workflow(&workflow_id).await.map_err(|e| {
                    terraphim_gen_agent::GenAgentError::ExecutionError(
                        self.agent_id.clone(),
                        e.to_string(),
                    )
                })?;
                Ok(serde_json::to_value(workflow).unwrap())
            }
            CoordinationMessage::GetWorkflowStatus { workflow_id } => {
                let workflow = self
                    .state
                    .active_workflows
                    .get(&workflow_id)
                    .ok_or_else(|| {
                        terraphim_gen_agent::GenAgentError::ExecutionError(
                            self.agent_id.clone(),
                            format!("Workflow {} not found", workflow_id),
                        )
                    })?;
                Ok(serde_json::to_value(&workflow.status).unwrap())
            }
            CoordinationMessage::ReassignTask {
                task_id,
                new_agent_id,
            } => {
                // Find workflow containing the task
                let workflow_id = self
                    .state
                    .active_workflows
                    .iter()
                    .find(|(_, workflow)| workflow.task_assignments.contains_key(&task_id))
                    .map(|(id, _)| id.clone())
                    .ok_or_else(|| {
                        terraphim_gen_agent::GenAgentError::ExecutionError(
                            self.agent_id.clone(),
                            format!("Task {} not found in any workflow", task_id),
                        )
                    })?;

                let assigned_agent =
                    self.reassign_task(&task_id, &workflow_id)
                        .await
                        .map_err(|e| {
                            terraphim_gen_agent::GenAgentError::ExecutionError(
                                self.agent_id.clone(),
                                e.to_string(),
                            )
                        })?;
                Ok(serde_json::to_value(assigned_agent).unwrap())
            }
            _ => {
                // Other messages don't return values in call context
                Ok(serde_json::Value::Null)
            }
        }
    }

    async fn handle_cast(&mut self, message: Self::Message) -> GenAgentResult<()> {
        match message {
            CoordinationMessage::HandleAgentFailure {
                agent_id,
                workflow_id,
            } => {
                let _ = self.handle_agent_failure(&agent_id, &workflow_id).await;
            }
            CoordinationMessage::UpdateAgentAvailability {
                agent_id,
                available,
            } => {
                self.update_agent_availability(&agent_id, available);
            }
            CoordinationMessage::CancelWorkflow { workflow_id } => {
                let _ = self.cancel_workflow(&workflow_id).await;
            }
            _ => {
                // Other messages handled in call context
            }
        }
        Ok(())
    }

    async fn handle_info(&mut self, _message: serde_json::Value) -> GenAgentResult<()> {
        // Handle periodic monitoring, health checks, etc.
        Ok(())
    }

    async fn terminate(&mut self, _reason: String) -> GenAgentResult<()> {
        info!("Terminating coordination agent: {}", self.agent_id);
        // Cancel all active workflows
        let workflow_ids: Vec<String> = self.state.active_workflows.keys().cloned().collect();
        for workflow_id in workflow_ids {
            let _ = self.cancel_workflow(&workflow_id).await;
        }
        Ok(())
    }

    fn get_state(&self) -> &CoordinationState {
        &self.state
    }

    fn get_state_mut(&mut self) -> &mut CoordinationState {
        &mut self.state
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use terraphim_task_decomposition::TaskComplexity;

    fn create_test_task() -> Task {
        Task::new(
            "test_task".to_string(),
            "Test task for coordination".to_string(),
            TaskComplexity::Simple,
            1,
        )
    }

    fn create_test_agent_metadata() -> AgentMetadata {
        let agent_id = crate::AgentPid::new();
        let supervisor_id = crate::SupervisorId::new();
        let role = terraphim_agent_registry::AgentRole::new(
            "worker".to_string(),
            "Test Worker".to_string(),
            "Test worker agent".to_string(),
        );
        AgentMetadata::new(agent_id, supervisor_id, role)
    }

    async fn create_test_agent() -> KnowledgeGraphCoordinationAgent {
        use terraphim_automata::{load_thesaurus, AutomataPath};
        use terraphim_types::RoleName;

        let automata = Arc::new(terraphim_automata::Automata::default());

        let role_name = RoleName::new("coordinator");
        let thesaurus = load_thesaurus(&AutomataPath::local_example())
            .await
            .unwrap();
        let role_graph = Arc::new(RoleGraph::new(role_name, thesaurus).await.unwrap());

        let mut role_graphs = HashMap::new();
        role_graphs.insert("coordinator".to_string(), role_graph);

        KnowledgeGraphCoordinationAgent::new(
            "test_coordinator".to_string(),
            automata,
            role_graphs,
            CoordinationConfig::default(),
        )
    }

    #[tokio::test]
    async fn test_coordination_agent_creation() {
        let agent = create_test_agent().await;
        assert_eq!(agent.agent_id, "test_coordinator");
        assert_eq!(agent.state.active_workflows.len(), 0);
    }

    #[tokio::test]
    async fn test_start_workflow() {
        let mut agent = create_test_agent().await;
        let tasks = vec![create_test_task()];
        let agents = vec![create_test_agent_metadata()];

        let result = agent
            .start_workflow("test_workflow".to_string(), tasks, agents)
            .await;

        assert!(result.is_ok());
        let workflow = result.unwrap();
        assert_eq!(workflow.workflow_id, "test_workflow");
        assert_eq!(workflow.status, WorkflowStatus::Executing);
    }

    #[tokio::test]
    async fn test_monitor_workflow() {
        let mut agent = create_test_agent().await;
        let tasks = vec![create_test_task()];
        let agents = vec![create_test_agent_metadata()];

        let workflow = agent
            .start_workflow("test_workflow".to_string(), tasks, agents)
            .await
            .unwrap();

        let monitored = agent.monitor_workflow(&workflow.workflow_id).await.unwrap();
        assert_eq!(monitored.workflow_id, workflow.workflow_id);
    }

    #[tokio::test]
    async fn test_agent_availability_update() {
        let mut agent = create_test_agent().await;
        let agent_metadata = create_test_agent_metadata();
        let agent_id = agent_metadata.agent_id.to_string();

        // Initialize agent availability
        agent.state.agent_availability.insert(
            agent_id.clone(),
            AgentAvailability {
                agent_id: agent_id.clone(),
                available: true,
                current_workload: 0,
                max_capacity: 5,
                last_seen: std::time::SystemTime::now(),
                performance: AgentPerformance::default(),
            },
        );

        agent.update_agent_availability(&agent_id, false);
        assert!(!agent.state.agent_availability[&agent_id].available);
    }

    #[tokio::test]
    async fn test_gen_agent_interface() {
        let mut agent = create_test_agent().await;

        // Test initialization
        let init_result = agent.init(serde_json::json!({})).await;
        assert!(init_result.is_ok());

        // Test cast message
        let message = CoordinationMessage::UpdateAgentAvailability {
            agent_id: "test_agent".to_string(),
            available: true,
        };
        let cast_result = agent.handle_cast(message).await;
        assert!(cast_result.is_ok());

        // Test termination
        let terminate_result = agent.terminate("test".to_string()).await;
        assert!(terminate_result.is_ok());
    }
}