terraphim_agent_registry 1.19.2

Knowledge graph-based agent registry for intelligent agent discovery and capability matching
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
//! Knowledge graph integration for agent registry
//!
//! Integrates with Terraphim's existing knowledge graph infrastructure to provide
//! intelligent agent discovery and capability matching using automata and role graphs.

use std::collections::{HashMap, HashSet};
use std::sync::Arc;

use serde::{Deserialize, Serialize};

use terraphim_rolegraph::RoleGraph;

use crate::{AgentMetadata, RegistryResult};

/// Knowledge graph-based agent discovery and matching
pub struct KnowledgeGraphIntegration {
    /// Role graph for role-based agent specialization
    role_graph: Arc<RoleGraph>,
    /// Automata for knowledge extraction and context analysis
    automata_config: AutomataConfig,
    /// Cached knowledge graph queries for performance
    query_cache: Arc<tokio::sync::RwLock<HashMap<String, QueryResult>>>,
    /// Semantic similarity thresholds
    similarity_thresholds: SimilarityThresholds,
}

/// Configuration for automata-based knowledge extraction
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AutomataConfig {
    /// Minimum confidence threshold for extraction
    pub min_confidence: f64,
    /// Maximum number of paragraphs to extract
    pub max_paragraphs: usize,
    /// Context window size for extraction
    pub context_window: usize,
    /// Language models to use for extraction
    pub language_models: Vec<String>,
}

impl Default for AutomataConfig {
    fn default() -> Self {
        Self {
            min_confidence: 0.7,
            max_paragraphs: 10,
            context_window: 512,
            language_models: vec!["default".to_string()],
        }
    }
}

/// Similarity thresholds for different types of matching
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SimilarityThresholds {
    /// Role similarity threshold
    pub role_similarity: f64,
    /// Capability similarity threshold
    pub capability_similarity: f64,
    /// Domain similarity threshold
    pub domain_similarity: f64,
    /// Concept similarity threshold
    pub concept_similarity: f64,
}

impl Default for SimilarityThresholds {
    fn default() -> Self {
        Self {
            role_similarity: 0.8,
            capability_similarity: 0.75,
            domain_similarity: 0.7,
            concept_similarity: 0.65,
        }
    }
}

/// Cached query result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryResult {
    /// Query hash for cache key
    pub query_hash: String,
    /// Extracted concepts and relationships
    pub concepts: Vec<String>,
    /// Connectivity analysis results
    pub connectivity: ConnectivityResult,
    /// Timestamp when cached
    pub cached_at: chrono::DateTime<chrono::Utc>,
    /// Cache expiry time
    pub expires_at: chrono::DateTime<chrono::Utc>,
}

/// Result of connectivity analysis
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConnectivityResult {
    /// Whether all terms are connected
    pub all_connected: bool,
    /// Connection paths found
    pub paths: Vec<Vec<String>>,
    /// Disconnected terms
    pub disconnected: Vec<String>,
    /// Connection strength score
    pub strength_score: f64,
}

/// Agent discovery query
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentDiscoveryQuery {
    /// Required roles
    pub required_roles: Vec<String>,
    /// Required capabilities
    pub required_capabilities: Vec<String>,
    /// Required knowledge domains
    pub required_domains: Vec<String>,
    /// Task description for context extraction
    pub task_description: Option<String>,
    /// Minimum success rate
    pub min_success_rate: Option<f64>,
    /// Maximum resource usage
    pub max_resource_usage: Option<crate::ResourceUsage>,
    /// Preferred agent tags
    pub preferred_tags: Vec<String>,
}

/// Agent discovery result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentDiscoveryResult {
    /// Matching agents with scores
    pub matches: Vec<AgentMatch>,
    /// Query analysis results
    pub query_analysis: QueryAnalysis,
    /// Suggestions for improving the query
    pub suggestions: Vec<String>,
}

/// Individual agent match result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AgentMatch {
    /// Agent metadata
    pub agent: AgentMetadata,
    /// Overall match score (0.0 to 1.0)
    pub match_score: f64,
    /// Detailed scoring breakdown
    pub score_breakdown: ScoreBreakdown,
    /// Explanation of the match
    pub explanation: String,
}

/// Detailed scoring breakdown
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ScoreBreakdown {
    /// Role compatibility score
    pub role_score: f64,
    /// Capability match score
    pub capability_score: f64,
    /// Domain expertise score
    pub domain_score: f64,
    /// Performance score
    pub performance_score: f64,
    /// Availability score
    pub availability_score: f64,
}

/// Query analysis results
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct QueryAnalysis {
    /// Extracted concepts from task description
    pub extracted_concepts: Vec<String>,
    /// Identified knowledge domains
    pub identified_domains: Vec<String>,
    /// Suggested roles based on analysis
    pub suggested_roles: Vec<String>,
    /// Connectivity analysis of requirements
    pub connectivity_analysis: ConnectivityResult,
}

impl KnowledgeGraphIntegration {
    /// Create new knowledge graph integration
    pub fn new(
        role_graph: Arc<RoleGraph>,
        automata_config: AutomataConfig,
        similarity_thresholds: SimilarityThresholds,
    ) -> Self {
        Self {
            role_graph,
            automata_config,
            query_cache: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
            similarity_thresholds,
        }
    }

    /// Discover agents based on requirements using knowledge graph analysis
    pub async fn discover_agents(
        &self,
        query: AgentDiscoveryQuery,
        available_agents: &[AgentMetadata],
    ) -> RegistryResult<AgentDiscoveryResult> {
        // Analyze the query using knowledge graph
        let query_analysis = self.analyze_query(&query).await?;

        // Filter agents that meet basic requirements
        let mut eligible_agents = Vec::new();
        for agent in available_agents {
            if self
                .check_basic_requirements(agent, &query)
                .await
                .unwrap_or(false)
            {
                eligible_agents.push(agent);
            }
        }

        // Score and rank eligible agents
        let mut matches = Vec::new();
        for agent in eligible_agents {
            if let Ok(agent_match) = self.score_agent_match(agent, &query, &query_analysis).await {
                matches.push(agent_match);
            }
        }

        // Sort by match score (highest first)
        #[allow(clippy::unnecessary_sort_by)]
        matches.sort_by(|a, b| {
            b.match_score
                .partial_cmp(&a.match_score)
                .unwrap_or(std::cmp::Ordering::Equal)
        });

        // Generate suggestions for improving the query
        let suggestions = self
            .generate_query_suggestions(&query, &query_analysis, &matches)
            .await;

        Ok(AgentDiscoveryResult {
            matches,
            query_analysis,
            suggestions,
        })
    }

    /// Check if agent meets basic requirements for the query
    async fn check_basic_requirements(
        &self,
        agent: &AgentMetadata,
        query: &AgentDiscoveryQuery,
    ) -> RegistryResult<bool> {
        // Check if agent meets required roles
        if !query.required_roles.is_empty() {
            let has_required_role = query.required_roles.iter().any(|required_role| {
                agent.primary_role.role_id == *required_role
                    || agent
                        .secondary_roles
                        .iter()
                        .any(|role| role.role_id == *required_role)
            });

            if !has_required_role {
                return Ok(false);
            }
        }

        // Check if agent meets required capabilities
        if !query.required_capabilities.is_empty() {
            let has_required_capability = query.required_capabilities.iter().any(|required_cap| {
                agent
                    .capabilities
                    .iter()
                    .any(|cap| cap.capability_id == *required_cap)
            });

            if !has_required_capability {
                return Ok(false);
            }
        }

        // Check if agent meets maximum resource usage if specified
        // Note: For now, we'll accept all agents for resource usage since the statistics
        // structure would need to be enhanced to support current resource tracking
        if query.max_resource_usage.is_some() {
            // TODO: Implement proper resource usage checking when AgentStatistics
            // supports current resource usage tracking
        }

        Ok(true)
    }

    /// Analyze a discovery query using knowledge graph
    async fn analyze_query(&self, query: &AgentDiscoveryQuery) -> RegistryResult<QueryAnalysis> {
        let mut extracted_concepts = Vec::new();
        let mut identified_domains = Vec::new();
        let mut suggested_roles = Vec::new();

        // Extract concepts from task description if provided
        if let Some(task_description) = &query.task_description {
            extracted_concepts = self.extract_concepts_from_text(task_description).await?;
            identified_domains = self
                .identify_domains_from_concepts(&extracted_concepts)
                .await?;
        }

        // Analyze required roles and suggest additional ones
        for role_id in &query.required_roles {
            if let Some(related_roles) = self.find_related_roles(role_id).await? {
                suggested_roles.extend(related_roles);
            }
        }

        // Analyze connectivity of all requirements
        let all_terms: Vec<String> = query
            .required_roles
            .iter()
            .chain(query.required_capabilities.iter())
            .chain(query.required_domains.iter())
            .chain(extracted_concepts.iter())
            .cloned()
            .collect();

        let connectivity_analysis = self.analyze_term_connectivity(&all_terms).await?;

        Ok(QueryAnalysis {
            extracted_concepts,
            identified_domains,
            suggested_roles,
            connectivity_analysis,
        })
    }

    /// Score how well an agent matches a query
    async fn score_agent_match(
        &self,
        agent: &AgentMetadata,
        query: &AgentDiscoveryQuery,
        query_analysis: &QueryAnalysis,
    ) -> RegistryResult<AgentMatch> {
        // Calculate individual scores
        let role_score = self
            .calculate_role_score(agent, &query.required_roles)
            .await?;
        let capability_score = self
            .calculate_capability_score(agent, &query.required_capabilities)
            .await?;
        let domain_score = self
            .calculate_domain_score(
                agent,
                &query.required_domains,
                &query_analysis.identified_domains,
            )
            .await?;
        let performance_score = self.calculate_performance_score(agent, query).await?;
        let availability_score = self.calculate_availability_score(agent).await?;

        // Weighted overall score
        let match_score = (role_score * 0.25
            + capability_score * 0.25
            + domain_score * 0.20
            + performance_score * 0.20
            + availability_score * 0.10)
            .clamp(0.0, 1.0);

        let score_breakdown = ScoreBreakdown {
            role_score,
            capability_score,
            domain_score,
            performance_score,
            availability_score,
        };

        let explanation = self.generate_match_explanation(agent, &score_breakdown, query_analysis);

        Ok(AgentMatch {
            agent: agent.clone(),
            match_score,
            score_breakdown,
            explanation,
        })
    }

    /// Extract concepts from text using automata
    async fn extract_concepts_from_text(&self, text: &str) -> RegistryResult<Vec<String>> {
        // Honour the configured context window: only the leading portion of the
        // text (up to `context_window` characters) is scanned for concepts.
        let scan_end = text
            .char_indices()
            .nth(self.automata_config.context_window)
            .map(|(idx, _)| idx)
            .unwrap_or(text.len());
        let text = &text[..scan_end];

        // Simple concept extraction - split text into words and filter
        let mut concepts = HashSet::new();

        // Split by whitespace and common punctuation
        let words: Vec<&str> = text
            .split(|c: char| c.is_whitespace() || c == ',' || c == '.' || c == ';' || c == ':')
            .collect();

        for word in words {
            let clean_word = word.trim().to_lowercase();
            // Filter out short words and common stop words
            if clean_word.len() > 2
                && ![
                    "the", "and", "for", "with", "using", "from", "that", "this", "are", "was",
                    "were", "been", "have", "has", "had", "not", "but", "they", "you", "their",
                    "can", "will",
                ]
                .contains(&clean_word.as_str())
                && !clean_word.chars().all(|c| c.is_ascii_punctuation())
            {
                concepts.insert(clean_word);
            }
        }

        Ok(concepts.into_iter().collect())
    }

    /// Identify knowledge domains from concepts
    async fn identify_domains_from_concepts(
        &self,
        concepts: &[String],
    ) -> RegistryResult<Vec<String>> {
        // This would typically use domain classification models
        // For now, we'll use simple keyword matching
        let mut domains = HashSet::new();

        for concept in concepts {
            let concept_lower = concept.to_lowercase();

            // Simple domain classification based on keywords
            if concept_lower.contains("plan") || concept_lower.contains("strategy") {
                domains.insert("planning".to_string());
            }
            if concept_lower.contains("data") || concept_lower.contains("analysis") {
                domains.insert("data_analysis".to_string());
            }
            if concept_lower.contains("execute") || concept_lower.contains("implement") {
                domains.insert("execution".to_string());
            }
            if concept_lower.contains("coordinate") || concept_lower.contains("manage") {
                domains.insert("coordination".to_string());
            }
            if concept_lower.contains("neural")
                || concept_lower.contains("network")
                || concept_lower.contains("deep")
                || concept_lower.contains("learning")
                || concept_lower.contains("machine")
                || concept_lower.contains("model")
                || concept_lower.contains("classification")
                || concept_lower.contains("image")
            {
                domains.insert("machine_learning".to_string());
            }
            if concept_lower.contains("tensor") || concept_lower.contains("flow") {
                domains.insert("tensorflow".to_string());
            }
        }

        Ok(domains.into_iter().collect())
    }

    /// Find related roles using role graph
    async fn find_related_roles(&self, _role_id: &str) -> RegistryResult<Option<Vec<String>>> {
        // TODO: Implement role graph querying when the appropriate methods are available
        // For now, return empty to maintain functionality
        Ok(Some(Vec::new()))
    }

    /// Analyze connectivity of terms using knowledge graph
    async fn analyze_term_connectivity(
        &self,
        terms: &[String],
    ) -> RegistryResult<ConnectivityResult> {
        if terms.is_empty() {
            return Ok(ConnectivityResult {
                all_connected: true,
                paths: Vec::new(),
                disconnected: Vec::new(),
                strength_score: 1.0,
            });
        }

        // Check cache first
        let cache_key = format!("connectivity_{}", terms.join("_"));
        {
            let cache = self.query_cache.read().await;
            if let Some(cached_result) = cache.get(&cache_key)
                && cached_result.expires_at > chrono::Utc::now()
            {
                return Ok(cached_result.connectivity.clone());
            }
        }

        // Use the existing is_all_terms_connected_by_path method on role_graph
        let text = terms.join(" ");
        let all_connected = self.role_graph.is_all_terms_connected_by_path(&text);

        // For now, we'll create a simplified connectivity result
        // In practice, this would involve more sophisticated graph analysis
        let connectivity_result = ConnectivityResult {
            all_connected,
            paths: if all_connected {
                vec![terms.to_vec()]
            } else {
                Vec::new()
            },
            disconnected: if all_connected {
                Vec::new()
            } else {
                terms.to_vec()
            },
            strength_score: if all_connected { 1.0 } else { 0.0 },
        };

        // Cache the result
        {
            let mut cache = self.query_cache.write().await;
            cache.insert(
                cache_key.clone(),
                QueryResult {
                    query_hash: cache_key,
                    concepts: terms.to_vec(),
                    connectivity: connectivity_result.clone(),
                    cached_at: chrono::Utc::now(),
                    expires_at: chrono::Utc::now() + chrono::Duration::hours(1),
                },
            );
        }

        Ok(connectivity_result)
    }

    /// Calculate role compatibility score
    async fn calculate_role_score(
        &self,
        agent: &AgentMetadata,
        required_roles: &[String],
    ) -> RegistryResult<f64> {
        if required_roles.is_empty() {
            return Ok(1.0);
        }

        let mut total_score: f64 = 0.0;
        let mut role_count = 0;

        for required_role in required_roles {
            let mut best_score: f64 = 0.0;

            // Check exact match with primary role
            if agent.primary_role.role_id == *required_role {
                best_score = 1.0;
            } else {
                // Check secondary roles
                for secondary_role in &agent.secondary_roles {
                    if secondary_role.role_id == *required_role {
                        best_score = best_score.max(0.9);
                    }
                }

                // Check role hierarchy compatibility
                if let Some(related_roles) = self.find_related_roles(required_role).await? {
                    if related_roles.contains(&agent.primary_role.role_id) {
                        best_score = best_score.max(0.7);
                    }

                    for secondary_role in &agent.secondary_roles {
                        if related_roles.contains(&secondary_role.role_id) {
                            best_score = best_score.max(0.6);
                        }
                    }
                }
            }

            total_score += best_score;
            role_count += 1;
        }

        Ok(if role_count > 0 {
            total_score / role_count as f64
        } else {
            1.0
        })
    }

    /// Calculate capability match score
    async fn calculate_capability_score(
        &self,
        agent: &AgentMetadata,
        required_capabilities: &[String],
    ) -> RegistryResult<f64> {
        if required_capabilities.is_empty() {
            return Ok(1.0);
        }

        let mut total_score: f64 = 0.0;
        let mut capability_count = 0;

        for required_capability in required_capabilities {
            let mut best_score: f64 = 0.0;

            for agent_capability in &agent.capabilities {
                if agent_capability.capability_id == *required_capability {
                    // Exact match, weighted by performance
                    best_score = best_score.max(agent_capability.performance_metrics.success_rate);
                } else if agent_capability
                    .name
                    .to_lowercase()
                    .contains(&required_capability.to_lowercase())
                    || required_capability
                        .to_lowercase()
                        .contains(&agent_capability.name.to_lowercase())
                {
                    // Partial name match
                    best_score =
                        best_score.max(agent_capability.performance_metrics.success_rate * 0.7);
                } else if agent_capability
                    .category
                    .to_lowercase()
                    .contains(&required_capability.to_lowercase())
                {
                    // Category match
                    best_score =
                        best_score.max(agent_capability.performance_metrics.success_rate * 0.5);
                }
            }

            total_score += best_score;
            capability_count += 1;
        }

        Ok(if capability_count > 0 {
            total_score / capability_count as f64
        } else {
            1.0
        })
    }

    /// Calculate domain expertise score
    async fn calculate_domain_score(
        &self,
        agent: &AgentMetadata,
        required_domains: &[String],
        identified_domains: &[String],
    ) -> RegistryResult<f64> {
        let all_domains: HashSet<String> = required_domains
            .iter()
            .chain(identified_domains.iter())
            .cloned()
            .collect();

        if all_domains.is_empty() {
            return Ok(1.0);
        }

        let mut total_score: f64 = 0.0;
        let mut domain_count = 0;

        for domain in &all_domains {
            let mut best_score: f64 = 0.0;

            // Check if agent can handle this domain
            if agent.can_handle_domain(domain) {
                best_score = 1.0;
            } else {
                // Check for partial matches in knowledge context
                for agent_domain in &agent.knowledge_context.domains {
                    if agent_domain.to_lowercase().contains(&domain.to_lowercase())
                        || domain.to_lowercase().contains(&agent_domain.to_lowercase())
                    {
                        best_score = best_score.max(0.7);
                    }
                }
            }

            total_score += best_score;
            domain_count += 1;
        }

        Ok(if domain_count > 0 {
            total_score / domain_count as f64
        } else {
            1.0
        })
    }

    /// Calculate performance score
    async fn calculate_performance_score(
        &self,
        agent: &AgentMetadata,
        query: &AgentDiscoveryQuery,
    ) -> RegistryResult<f64> {
        let mut score = agent.get_success_rate();

        // Apply minimum success rate filter
        if let Some(min_success_rate) = query.min_success_rate
            && score < min_success_rate
        {
            score *= 0.5; // Penalize agents below minimum
        }

        // Consider resource usage if specified
        if let Some(max_resource_usage) = &query.max_resource_usage
            && let Some((_, latest_usage)) = agent.statistics.resource_history.last()
            && (latest_usage.memory_mb > max_resource_usage.memory_mb
                || latest_usage.cpu_percent > max_resource_usage.cpu_percent)
        {
            score *= 0.7; // Penalize high resource usage
        }

        Ok(score)
    }

    /// Calculate availability score
    async fn calculate_availability_score(&self, agent: &AgentMetadata) -> RegistryResult<f64> {
        match agent.status {
            crate::AgentStatus::Active => Ok(1.0),
            crate::AgentStatus::Idle => Ok(1.0),
            crate::AgentStatus::Busy => Ok(0.5),
            crate::AgentStatus::Hibernating => Ok(0.8),
            crate::AgentStatus::Initializing => Ok(0.3),
            crate::AgentStatus::Terminating => Ok(0.0),
            crate::AgentStatus::Terminated => Ok(0.0),
            crate::AgentStatus::Failed(_) => Ok(0.0),
        }
    }

    /// Generate explanation for agent match
    fn generate_match_explanation(
        &self,
        agent: &AgentMetadata,
        score_breakdown: &ScoreBreakdown,
        _query_analysis: &QueryAnalysis,
    ) -> String {
        let mut explanation = format!("Agent {} ({})", agent.agent_id, agent.primary_role.name);

        if score_breakdown.role_score > 0.8 {
            explanation.push_str(" has excellent role compatibility");
        } else if score_breakdown.role_score > 0.6 {
            explanation.push_str(" has good role compatibility");
        } else {
            explanation.push_str(" has limited role compatibility");
        }

        if score_breakdown.capability_score > 0.8 {
            explanation.push_str(" and strong capability match");
        } else if score_breakdown.capability_score > 0.6 {
            explanation.push_str(" and moderate capability match");
        } else {
            explanation.push_str(" but limited capability match");
        }

        if score_breakdown.performance_score > 0.8 {
            explanation.push_str(". Performance history is excellent");
        } else if score_breakdown.performance_score > 0.6 {
            explanation.push_str(". Performance history is good");
        } else {
            explanation.push_str(". Performance history needs improvement");
        }

        explanation.push('.');
        explanation
    }

    /// Generate suggestions for improving the query
    async fn generate_query_suggestions(
        &self,
        query: &AgentDiscoveryQuery,
        query_analysis: &QueryAnalysis,
        matches: &[AgentMatch],
    ) -> Vec<String> {
        let mut suggestions = Vec::new();

        // Suggest additional roles if connectivity analysis shows gaps
        if !query_analysis.connectivity_analysis.all_connected {
            suggestions
                .push("Consider adding related roles to improve agent connectivity".to_string());
        }

        // Suggest relaxing requirements if no good matches
        if matches.is_empty() || matches.iter().all(|m| m.match_score < 0.5) {
            suggestions.push(
                "Consider relaxing some requirements to find more suitable agents".to_string(),
            );
        }

        // Suggest additional capabilities based on identified domains
        if !query_analysis.identified_domains.is_empty() && query.required_capabilities.is_empty() {
            suggestions.push(format!(
                "Consider specifying capabilities for domains: {}",
                query_analysis.identified_domains.join(", ")
            ));
        }

        // Advise when the best available match falls below the configured
        // similarity thresholds for role or capability compatibility.
        if let Some(best) = matches.first()
            && (best.score_breakdown.role_score < self.similarity_thresholds.role_similarity
                || best.score_breakdown.capability_score
                    < self.similarity_thresholds.capability_similarity)
        {
            suggestions.push(
                "Best match falls below configured similarity thresholds; consider broadening the query"
                    .to_string(),
            );
        }

        suggestions
    }

    /// Clear expired cache entries
    pub async fn cleanup_cache(&self) {
        let mut cache = self.query_cache.write().await;
        let now = chrono::Utc::now();
        cache.retain(|_, result| result.expires_at > now);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{AgentMetadata, AgentPid, AgentRole, SupervisorId};
    use terraphim_types::{RoleName, Thesaurus};

    #[tokio::test]
    async fn test_knowledge_graph_integration_creation() {
        let role_name = RoleName::new("test_role");
        let thesaurus = Thesaurus::new("test_thesaurus".to_string());
        let role_graph = Arc::new(RoleGraph::new(role_name, thesaurus).await.unwrap());
        let automata_config = AutomataConfig::default();
        let similarity_thresholds = SimilarityThresholds::default();

        let kg_integration =
            KnowledgeGraphIntegration::new(role_graph, automata_config, similarity_thresholds);

        // Test that the integration was created successfully
        assert_eq!(kg_integration.similarity_thresholds.role_similarity, 0.8);
    }

    #[tokio::test]
    async fn test_agent_discovery_query() {
        let query = AgentDiscoveryQuery {
            required_roles: vec!["planner".to_string()],
            required_capabilities: vec!["task_planning".to_string()],
            required_domains: vec!["project_management".to_string()],
            task_description: Some(
                "Plan and coordinate a software development project".to_string(),
            ),
            min_success_rate: Some(0.8),
            max_resource_usage: None,
            preferred_tags: vec!["experienced".to_string()],
        };

        assert_eq!(query.required_roles.len(), 1);
        assert_eq!(query.required_capabilities.len(), 1);
        assert!(query.task_description.is_some());
    }

    #[tokio::test]
    async fn test_score_calculation() {
        let role_name = RoleName::new("test_role");
        let thesaurus = Thesaurus::new("test_thesaurus".to_string());
        let role_graph = Arc::new(RoleGraph::new(role_name, thesaurus).await.unwrap());
        let automata_config = AutomataConfig::default();
        let similarity_thresholds = SimilarityThresholds::default();

        let kg_integration =
            KnowledgeGraphIntegration::new(role_graph, automata_config, similarity_thresholds);

        // Create test agent
        let agent_id = AgentPid::new();
        let supervisor_id = SupervisorId::new();
        let role = AgentRole::new(
            "planner".to_string(),
            "Planning Agent".to_string(),
            "Responsible for task planning".to_string(),
        );

        let agent = AgentMetadata::new(agent_id, supervisor_id, role);

        // Test availability score calculation
        let availability_score = kg_integration
            .calculate_availability_score(&agent)
            .await
            .unwrap();
        assert!((0.0..=1.0).contains(&availability_score));
    }
}