converge-provider 3.7.4

LLM provider implementations for Converge
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
// Copyright 2024-2026 Reflective Labs
// SPDX-License-Identifier: MIT
// See LICENSE file in the project root for full license information.

//! Unified capability registry for Converge providers.
//!
//! The capability registry provides a single point for discovering and
//! selecting providers based on their capabilities. This supports the
//! Converge principle that different models excel at different tasks.
//!
//! # Example
//!
//! ```ignore
//! use converge_provider::{CapabilityRegistry, CapabilityRequirements};
//! use converge_core::capability::{CapabilityKind, Modality};
//!
//! let registry = CapabilityRegistry::from_env();
//!
//! // Find an embedder that supports images
//! let requirements = CapabilityRequirements::embedding()
//!     .with_modality(Modality::Image)
//!     .prefer_local(true);
//!
//! if let Some(embedder) = registry.select_embedder(&requirements) {
//!     // Use the embedder
//! }
//! ```

#[cfg(feature = "brave")]
use crate::brave::BraveSearchProvider;
#[cfg(feature = "_http")]
use crate::fetch::HttpFetchProvider;
use crate::search::{WebFetchBackend, WebSearchBackend};
#[cfg(feature = "tavily")]
use crate::tavily::TavilySearchProvider;
use converge_core::capability::{
    CapabilityKind, CapabilityMetadata, Embedding, GraphRecall, Modality, Reranking, VectorRecall,
};
use converge_provider_api::selection::DataSovereignty;
use std::collections::HashMap;
use std::sync::Arc;

/// Requirements for capability selection.
#[derive(Debug, Clone)]
pub struct CapabilityRequirements {
    /// Required capability kind.
    pub capability: CapabilityKind,
    /// Required modalities (for embedding/reranking).
    pub modalities: Vec<Modality>,
    /// Prefer local providers (data sovereignty).
    pub prefer_local: bool,
    /// Required data sovereignty level.
    pub data_sovereignty: DataSovereignty,
    /// Maximum acceptable latency in milliseconds.
    pub max_latency_ms: u32,
}

impl CapabilityRequirements {
    /// Requirements for LLM completion.
    #[must_use]
    pub fn completion() -> Self {
        Self {
            capability: CapabilityKind::Completion,
            modalities: vec![Modality::Text],
            prefer_local: false,
            data_sovereignty: DataSovereignty::Any,
            max_latency_ms: 30_000,
        }
    }

    /// Requirements for embedding.
    #[must_use]
    pub fn embedding() -> Self {
        Self {
            capability: CapabilityKind::Embedding,
            modalities: vec![Modality::Text],
            prefer_local: false,
            data_sovereignty: DataSovereignty::Any,
            max_latency_ms: 5_000,
        }
    }

    /// Requirements for reranking.
    #[must_use]
    pub fn reranking() -> Self {
        Self {
            capability: CapabilityKind::Reranking,
            modalities: vec![Modality::Text],
            prefer_local: false,
            data_sovereignty: DataSovereignty::Any,
            max_latency_ms: 5_000,
        }
    }

    /// Requirements for vector recall.
    #[must_use]
    pub fn vector_recall() -> Self {
        Self {
            capability: CapabilityKind::VectorRecall,
            modalities: vec![],
            prefer_local: true,
            data_sovereignty: DataSovereignty::Any,
            max_latency_ms: 100,
        }
    }

    /// Requirements for graph recall.
    #[must_use]
    pub fn graph_recall() -> Self {
        Self {
            capability: CapabilityKind::GraphRecall,
            modalities: vec![],
            prefer_local: true,
            data_sovereignty: DataSovereignty::Any,
            max_latency_ms: 100,
        }
    }

    /// Add required modality.
    #[must_use]
    pub fn with_modality(mut self, modality: Modality) -> Self {
        if !self.modalities.contains(&modality) {
            self.modalities.push(modality);
        }
        self
    }

    /// Set local preference.
    #[must_use]
    pub fn prefer_local(mut self, prefer: bool) -> Self {
        self.prefer_local = prefer;
        self
    }

    /// Set data sovereignty requirement.
    #[must_use]
    pub fn with_data_sovereignty(mut self, sovereignty: DataSovereignty) -> Self {
        self.data_sovereignty = sovereignty;
        self
    }

    /// Set maximum latency.
    #[must_use]
    pub fn with_max_latency_ms(mut self, ms: u32) -> Self {
        self.max_latency_ms = ms;
        self
    }
}

/// Registered provider with its capabilities.
struct RegisteredProvider {
    /// Provider metadata.
    metadata: CapabilityMetadata,
    /// Embedding provider instance (if applicable).
    embedder: Option<Arc<dyn Embedding>>,
    /// Reranker provider instance (if applicable).
    reranker: Option<Arc<dyn Reranking>>,
}

/// Web search provider metadata for agent selection.
#[derive(Debug, Clone)]
pub struct SearchProviderMeta {
    /// Provider name (e.g., "brave", "perplexity").
    pub name: String,
    /// Whether this provider is available (API key set).
    pub available: bool,
    /// Typical latency in milliseconds.
    pub typical_latency_ms: u32,
    /// Whether this provider supports AI-powered summaries.
    pub supports_ai_summary: bool,
    /// Whether this provider supports news search.
    pub supports_news: bool,
    /// Whether this provider supports image search.
    pub supports_images: bool,
    /// Whether this provider supports local/POI search.
    pub supports_local: bool,
}

/// Requirements for selecting a web search provider.
///
/// Unlike LLM requirements, web search requirements focus on
/// search-specific capabilities like news, images, and AI summaries.
#[derive(Debug, Clone)]
pub struct WebSearchRequirements {
    /// Maximum latency in milliseconds.
    pub max_latency_ms: u32,
    /// Whether AI-powered summaries are required.
    pub requires_ai_summary: bool,
    /// Whether news search is required.
    pub requires_news: bool,
    /// Whether image search is required.
    pub requires_images: bool,
    /// Whether local/POI search is required.
    pub requires_local: bool,
    /// Data sovereignty requirement.
    pub data_sovereignty: DataSovereignty,
}

impl Default for WebSearchRequirements {
    fn default() -> Self {
        Self {
            max_latency_ms: 10_000,
            requires_ai_summary: false,
            requires_news: false,
            requires_images: false,
            requires_local: false,
            data_sovereignty: DataSovereignty::Any,
        }
    }
}

impl WebSearchRequirements {
    /// Creates default requirements for general web search.
    #[must_use]
    pub fn web_search() -> Self {
        Self::default()
    }

    /// Creates requirements for AI-grounded search (RAG).
    #[must_use]
    pub fn grounded() -> Self {
        Self {
            max_latency_ms: 15_000,
            requires_ai_summary: true,
            ..Self::default()
        }
    }

    /// Creates requirements for news search.
    #[must_use]
    pub fn news() -> Self {
        Self {
            requires_news: true,
            ..Self::default()
        }
    }

    /// Sets the maximum latency.
    #[must_use]
    pub fn with_max_latency_ms(mut self, ms: u32) -> Self {
        self.max_latency_ms = ms;
        self
    }

    /// Requires AI-powered summaries.
    #[must_use]
    pub fn with_ai_summary(mut self, required: bool) -> Self {
        self.requires_ai_summary = required;
        self
    }

    /// Sets data sovereignty requirement.
    #[must_use]
    pub fn with_data_sovereignty(mut self, sovereignty: DataSovereignty) -> Self {
        self.data_sovereignty = sovereignty;
        self
    }

    /// Requires news search support.
    #[must_use]
    pub fn with_news(mut self, required: bool) -> Self {
        self.requires_news = required;
        self
    }

    /// Requires image search support.
    #[must_use]
    pub fn with_images(mut self, required: bool) -> Self {
        self.requires_images = required;
        self
    }

    /// Requires local/POI search support.
    #[must_use]
    pub fn with_local(mut self, required: bool) -> Self {
        self.requires_local = required;
        self
    }
}

/// Unified capability registry.
///
/// Discovers and manages all available capability providers.
pub struct CapabilityRegistry {
    /// Registered providers by name.
    providers: HashMap<String, RegisteredProvider>,
    /// Vector stores by name.
    vector_stores: HashMap<String, Arc<dyn VectorRecall>>,
    /// Graph stores by name.
    graph_stores: HashMap<String, Arc<dyn GraphRecall>>,
    /// Web search providers by name.
    search_providers: HashMap<String, SearchProviderMeta>,
    /// Executable web search backends by name.
    search_backends: HashMap<String, Arc<dyn WebSearchBackend>>,
    /// Brave search provider instance (if available).
    #[cfg(feature = "brave")]
    brave_provider: Option<Arc<BraveSearchProvider>>,
    /// Tavily search provider instance (if available).
    #[cfg(feature = "tavily")]
    tavily_provider: Option<Arc<TavilySearchProvider>>,
    /// Web fetch backend (URL → content).
    fetch_backend: Option<Arc<dyn WebFetchBackend>>,
}

impl Default for CapabilityRegistry {
    fn default() -> Self {
        Self::new()
    }
}

impl CapabilityRegistry {
    /// Creates an empty capability registry.
    #[must_use]
    pub fn new() -> Self {
        Self {
            providers: HashMap::new(),
            vector_stores: HashMap::new(),
            graph_stores: HashMap::new(),
            search_providers: HashMap::new(),
            search_backends: HashMap::new(),
            #[cfg(feature = "brave")]
            brave_provider: None,
            #[cfg(feature = "tavily")]
            tavily_provider: None,
            fetch_backend: None,
        }
    }

    /// Creates a registry with auto-detected providers from environment.
    ///
    /// This checks for:
    /// - Ollama (local LLM and embedding)
    /// - In-memory vector store (always available)
    /// - In-memory graph store (always available)
    /// - Brave Search (if `BRAVE_API_KEY` is set)
    /// - Tavily Search (if `TAVILY_API_KEY` is set)
    #[must_use]
    pub fn with_local_defaults() -> Self {
        let mut registry = Self::new();

        // Add in-memory vector store
        registry.add_vector_store(
            "default",
            Arc::new(crate::vector::InMemoryVectorStore::new()),
        );

        // Graph store moved to organism-intelligence crate

        // Try to add Brave Search if available
        registry.try_add_brave_from_env();
        registry.try_add_tavily_from_env();

        // HTTP fetch is always available (no API key required)
        #[cfg(feature = "_http")]
        {
            registry.fetch_backend = Some(Arc::new(HttpFetchProvider::new()));
        }

        registry
    }

    /// Attempts to add Brave Search provider from environment.
    ///
    /// Returns `true` if Brave Search was added successfully.
    pub fn try_add_brave_from_env(&mut self) -> bool {
        #[cfg(feature = "brave")]
        if let Ok(provider) = BraveSearchProvider::from_env() {
            let provider = Arc::new(provider);
            self.brave_provider = Some(provider.clone());
            self.search_backends
                .insert("brave".to_string(), provider.clone());
            self.search_providers.insert(
                "brave".to_string(),
                SearchProviderMeta {
                    name: "brave".to_string(),
                    available: true,
                    typical_latency_ms: 500,
                    supports_ai_summary: false, // Requires Pro plan
                    supports_news: true,
                    supports_images: true,
                    supports_local: true,
                },
            );
            return true;
        }
        false
    }

    /// Attempts to add Tavily Search provider from environment.
    ///
    /// Returns `true` if Tavily Search was added successfully.
    pub fn try_add_tavily_from_env(&mut self) -> bool {
        #[cfg(feature = "tavily")]
        if let Ok(provider) = TavilySearchProvider::from_env() {
            let provider = Arc::new(provider);
            self.tavily_provider = Some(provider.clone());
            self.search_backends
                .insert("tavily".to_string(), provider.clone());
            self.search_providers.insert(
                "tavily".to_string(),
                SearchProviderMeta {
                    name: "tavily".to_string(),
                    available: true,
                    typical_latency_ms: 1200,
                    supports_ai_summary: true,
                    supports_news: true,
                    supports_images: true,
                    supports_local: false,
                },
            );
            return true;
        }
        false
    }

    /// Adds Brave Search provider with a specific API key.
    #[cfg(feature = "brave")]
    pub fn add_brave(&mut self, api_key: impl Into<String>) {
        let provider = Arc::new(BraveSearchProvider::new(api_key));
        self.brave_provider = Some(provider.clone());
        self.search_backends
            .insert("brave".to_string(), provider.clone());
        self.search_providers.insert(
            "brave".to_string(),
            SearchProviderMeta {
                name: "brave".to_string(),
                available: true,
                typical_latency_ms: 500,
                supports_ai_summary: false,
                supports_news: true,
                supports_images: true,
                supports_local: true,
            },
        );
    }

    /// Adds Tavily Search provider with a specific API key.
    #[cfg(feature = "tavily")]
    pub fn add_tavily(&mut self, api_key: impl Into<String>) {
        let provider = Arc::new(TavilySearchProvider::new(api_key));
        self.tavily_provider = Some(provider.clone());
        self.search_backends
            .insert("tavily".to_string(), provider.clone());
        self.search_providers.insert(
            "tavily".to_string(),
            SearchProviderMeta {
                name: "tavily".to_string(),
                available: true,
                typical_latency_ms: 1200,
                supports_ai_summary: true,
                supports_news: true,
                supports_images: true,
                supports_local: false,
            },
        );
    }

    /// Gets the Brave Search provider if available.
    #[cfg(feature = "brave")]
    #[must_use]
    pub fn brave(&self) -> Option<&BraveSearchProvider> {
        self.brave_provider.as_deref()
    }

    /// Gets the Tavily Search provider if available.
    #[cfg(feature = "tavily")]
    #[must_use]
    pub fn tavily(&self) -> Option<&TavilySearchProvider> {
        self.tavily_provider.as_deref()
    }

    /// Gets the web fetch backend if available.
    #[must_use]
    pub fn fetch_backend(&self) -> Option<Arc<dyn WebFetchBackend>> {
        self.fetch_backend.clone()
    }

    /// Sets a custom web fetch backend.
    pub fn set_fetch_backend(&mut self, backend: Arc<dyn WebFetchBackend>) {
        self.fetch_backend = Some(backend);
    }

    /// Checks if web fetch capability is available.
    #[must_use]
    pub fn has_web_fetch(&self) -> bool {
        self.fetch_backend.is_some()
    }

    /// Checks if web search capability is available.
    #[must_use]
    pub fn has_web_search(&self) -> bool {
        !self.search_providers.is_empty()
    }

    /// Gets metadata for all available search providers.
    #[must_use]
    pub fn search_providers(&self) -> Vec<&SearchProviderMeta> {
        self.search_providers.values().collect()
    }

    /// Selects the best search provider based on requirements.
    ///
    /// Currently returns Brave if available, as it's the primary search provider.
    #[must_use]
    pub fn select_search_provider(
        &self,
        requirements: &WebSearchRequirements,
    ) -> Option<&SearchProviderMeta> {
        self.search_providers
            .values()
            .filter(|p| {
                // Basic availability and latency check
                if !p.available || p.typical_latency_ms > requirements.max_latency_ms {
                    return false;
                }
                // Check required capabilities
                if requirements.requires_ai_summary && !p.supports_ai_summary {
                    return false;
                }
                if requirements.requires_news && !p.supports_news {
                    return false;
                }
                if requirements.requires_images && !p.supports_images {
                    return false;
                }
                if requirements.requires_local && !p.supports_local {
                    return false;
                }
                true
            })
            .max_by_key(|p| {
                // Score providers by capabilities the caller actually asked for.
                let mut score = 0i32;
                if requirements.requires_ai_summary && p.supports_ai_summary {
                    score += 100;
                }
                if requirements.requires_news && p.supports_news {
                    score += 30;
                }
                if requirements.requires_images && p.supports_images {
                    score += 30;
                }
                if requirements.requires_local && p.supports_local {
                    score += 20;
                }
                // Prefer lower latency
                score -= (p.typical_latency_ms / 100) as i32;
                score
            })
    }

    /// Selects an executable search backend matching the requirements.
    #[must_use]
    pub fn select_search_backend(
        &self,
        requirements: &WebSearchRequirements,
    ) -> Option<Arc<dyn WebSearchBackend>> {
        self.select_search_provider(requirements)
            .and_then(|meta| self.search_backends.get(&meta.name).cloned())
    }

    /// Registers an embedding provider.
    #[allow(clippy::needless_pass_by_value)]
    pub fn add_embedder(
        &mut self,
        name: &str,
        provider: Arc<dyn Embedding>,
        metadata: CapabilityMetadata,
    ) {
        let entry = self
            .providers
            .entry(name.to_string())
            .or_insert_with(|| RegisteredProvider {
                metadata: metadata.clone(),
                embedder: None,
                reranker: None,
            });
        entry.embedder = Some(provider);
        // Merge capabilities
        for cap in &metadata.capabilities {
            if !entry.metadata.capabilities.contains(cap) {
                entry.metadata.capabilities.push(*cap);
            }
        }
    }

    /// Registers a reranker provider.
    #[allow(clippy::needless_pass_by_value)]
    pub fn add_reranker(
        &mut self,
        name: &str,
        provider: Arc<dyn Reranking>,
        metadata: CapabilityMetadata,
    ) {
        let entry = self
            .providers
            .entry(name.to_string())
            .or_insert_with(|| RegisteredProvider {
                metadata: metadata.clone(),
                embedder: None,
                reranker: None,
            });
        entry.reranker = Some(provider);
        // Merge capabilities
        for cap in &metadata.capabilities {
            if !entry.metadata.capabilities.contains(cap) {
                entry.metadata.capabilities.push(*cap);
            }
        }
    }

    /// Registers a vector store.
    pub fn add_vector_store(&mut self, name: &str, store: Arc<dyn VectorRecall>) {
        self.vector_stores.insert(name.to_string(), store);
    }

    /// Registers a graph store.
    pub fn add_graph_store(&mut self, name: &str, store: Arc<dyn GraphRecall>) {
        self.graph_stores.insert(name.to_string(), store);
    }

    /// Selects an embedding provider matching requirements.
    #[must_use]
    pub fn select_embedder(
        &self,
        requirements: &CapabilityRequirements,
    ) -> Option<Arc<dyn Embedding>> {
        self.providers
            .values()
            .filter(|p| {
                p.embedder.is_some() && self.matches_requirements(&p.metadata, requirements)
            })
            .max_by_key(|p| self.score_provider(&p.metadata, requirements))
            .and_then(|p| p.embedder.clone())
    }

    /// Selects a reranker provider matching requirements.
    #[must_use]
    pub fn select_reranker(
        &self,
        requirements: &CapabilityRequirements,
    ) -> Option<Arc<dyn Reranking>> {
        self.providers
            .values()
            .filter(|p| {
                p.reranker.is_some() && self.matches_requirements(&p.metadata, requirements)
            })
            .max_by_key(|p| self.score_provider(&p.metadata, requirements))
            .and_then(|p| p.reranker.clone())
    }

    /// Gets the default vector store.
    #[must_use]
    pub fn get_vector_store(&self, name: &str) -> Option<Arc<dyn VectorRecall>> {
        self.vector_stores.get(name).cloned()
    }

    /// Gets the default graph store.
    #[must_use]
    pub fn get_graph_store(&self, name: &str) -> Option<Arc<dyn GraphRecall>> {
        self.graph_stores.get(name).cloned()
    }

    /// Gets the default vector store (named "default").
    #[must_use]
    pub fn default_vector_store(&self) -> Option<Arc<dyn VectorRecall>> {
        self.get_vector_store("default")
    }

    /// Gets the default graph store (named "default").
    #[must_use]
    pub fn default_graph_store(&self) -> Option<Arc<dyn GraphRecall>> {
        self.get_graph_store("default")
    }

    /// Lists all registered provider names.
    #[must_use]
    pub fn provider_names(&self) -> Vec<&str> {
        self.providers.keys().map(String::as_str).collect()
    }

    /// Lists all registered vector store names.
    #[must_use]
    pub fn vector_store_names(&self) -> Vec<&str> {
        self.vector_stores.keys().map(String::as_str).collect()
    }

    /// Lists all registered graph store names.
    #[must_use]
    pub fn graph_store_names(&self) -> Vec<&str> {
        self.graph_stores.keys().map(String::as_str).collect()
    }

    /// Checks if a provider matches the requirements.
    #[allow(clippy::unused_self)]
    fn matches_requirements(
        &self,
        metadata: &CapabilityMetadata,
        requirements: &CapabilityRequirements,
    ) -> bool {
        // Check capability
        if !metadata.capabilities.contains(&requirements.capability) {
            return false;
        }

        // Check modalities
        for modality in &requirements.modalities {
            if !metadata.modalities.contains(modality) {
                return false;
            }
        }

        // Check data sovereignty - local providers satisfy all requirements
        #[allow(clippy::match_same_arms)]
        match (&requirements.data_sovereignty, metadata.is_local) {
            (DataSovereignty::Any, _) | (_, true) => {} // Always OK or local
            _ => {} // Remote providers must match specific sovereignty
        }

        // Check latency
        if metadata.typical_latency_ms > requirements.max_latency_ms {
            return false;
        }

        true
    }

    /// Scores a provider for selection (higher = better).
    #[allow(clippy::unused_self, clippy::cast_possible_wrap)]
    fn score_provider(
        &self,
        metadata: &CapabilityMetadata,
        requirements: &CapabilityRequirements,
    ) -> i32 {
        let mut score = 0;

        // Prefer local if requested
        if requirements.prefer_local && metadata.is_local {
            score += 100;
        }

        // Lower latency is better
        if metadata.typical_latency_ms < requirements.max_latency_ms / 2 {
            score += 50;
        }

        // More modalities is better
        score += (metadata.modalities.len() * 10) as i32;

        score
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::vector::InMemoryVectorStore;
    use converge_core::capability::{
        CapabilityError, GraphEdge, GraphNode, GraphQuery, GraphRecall, GraphResult,
    };

    struct TestGraphStore;

    impl TestGraphStore {
        fn new() -> Self {
            Self
        }
    }

    impl GraphRecall for TestGraphStore {
        fn name(&self) -> &str {
            "test-graph"
        }

        fn add_node(&self, _node: &GraphNode) -> Result<(), CapabilityError> {
            Ok(())
        }

        fn add_edge(&self, _edge: &GraphEdge) -> Result<(), CapabilityError> {
            Ok(())
        }

        fn traverse(&self, _query: &GraphQuery) -> Result<GraphResult, CapabilityError> {
            Ok(GraphResult {
                nodes: Vec::new(),
                edges: Vec::new(),
            })
        }

        fn find_nodes(
            &self,
            _label: &str,
            _properties: Option<&serde_json::Value>,
        ) -> Result<Vec<GraphNode>, CapabilityError> {
            Ok(Vec::new())
        }

        fn get_node(&self, _id: &str) -> Result<Option<GraphNode>, CapabilityError> {
            Ok(None)
        }

        fn delete_node(&self, _id: &str) -> Result<(), CapabilityError> {
            Ok(())
        }

        fn clear(&self) -> Result<(), CapabilityError> {
            Ok(())
        }
    }

    #[test]
    fn registry_with_local_defaults() {
        let registry = CapabilityRegistry::with_local_defaults();

        assert!(registry.default_vector_store().is_some());
        assert!(registry.default_graph_store().is_none());
    }

    #[test]
    fn add_and_get_stores() {
        let mut registry = CapabilityRegistry::new();

        registry.add_vector_store("test", Arc::new(InMemoryVectorStore::new()));
        registry.add_graph_store("test", Arc::new(TestGraphStore::new()));

        assert!(registry.get_vector_store("test").is_some());
        assert!(registry.get_graph_store("test").is_some());
        assert!(registry.get_vector_store("missing").is_none());
    }

    #[test]
    fn list_registered_stores() {
        let registry = CapabilityRegistry::with_local_defaults();

        let vector_stores = registry.vector_store_names();
        assert!(vector_stores.contains(&"default"));

        let graph_stores = registry.graph_store_names();
        assert!(graph_stores.is_empty());
    }

    #[test]
    fn capability_requirements_builder() {
        let reqs = CapabilityRequirements::embedding()
            .with_modality(Modality::Image)
            .prefer_local(true)
            .with_max_latency_ms(1000);

        assert_eq!(reqs.capability, CapabilityKind::Embedding);
        assert!(reqs.modalities.contains(&Modality::Image));
        assert!(reqs.prefer_local);
        assert_eq!(reqs.max_latency_ms, 1000);
    }

    #[cfg(all(feature = "brave", feature = "tavily"))]
    #[test]
    fn search_provider_selection_prefers_tavily_for_ai_summary() {
        let mut registry = CapabilityRegistry::new();
        registry.add_brave("brave-key");
        registry.add_tavily("tavily-key");

        let selected = registry
            .select_search_provider(&WebSearchRequirements::grounded())
            .unwrap();
        assert_eq!(selected.name, "tavily");

        let backend = registry
            .select_search_backend(&WebSearchRequirements::grounded())
            .unwrap();
        assert_eq!(backend.provider_name(), "tavily");
    }

    #[cfg(all(feature = "brave", feature = "tavily"))]
    #[test]
    fn search_provider_selection_prefers_brave_for_local_search() {
        let mut registry = CapabilityRegistry::new();
        registry.add_brave("brave-key");
        registry.add_tavily("tavily-key");

        let selected = registry
            .select_search_provider(&WebSearchRequirements::web_search().with_local(true))
            .unwrap();
        assert_eq!(selected.name, "brave");
    }
}