Skip to main content

hyprstream_core/archetypes/
registry.rs

1//! Archetype/Domain registry with caching
2//!
3//! Provides efficient domain detection with caching to avoid
4//! repeated filesystem scans.
5
6use super::capabilities::{Capability, CapabilitySet};
7use super::{builtin_archetypes, RepoArchetype};
8use dashmap::DashMap;
9use std::collections::HashMap;
10use std::path::{Path, PathBuf};
11use std::sync::Arc;
12use std::time::{Duration, Instant};
13
14// ============================================================================
15// New Domain-based types (Phase 4)
16// ============================================================================
17
18/// Detected domains and their capabilities
19///
20/// This is the new type-safe replacement for `DetectedArchetypes`.
21/// Uses `CapabilitySet` for type-safe capability checks.
22#[derive(Debug, Clone)]
23pub struct DetectedDomains {
24    /// Names of detected domains (e.g., "HfModel", "DuckDb")
25    pub domains: Vec<&'static str>,
26    /// Combined capabilities from all detected domains
27    pub capabilities: CapabilitySet,
28    /// Per-domain capabilities
29    pub domain_capabilities: HashMap<&'static str, CapabilitySet>,
30    /// When this detection was performed
31    pub detected_at: Instant,
32}
33
34impl DetectedDomains {
35    /// Create an empty detection result
36    pub fn empty() -> Self {
37        Self {
38            domains: Vec::new(),
39            capabilities: CapabilitySet::new(),
40            domain_capabilities: HashMap::new(),
41            detected_at: Instant::now(),
42        }
43    }
44
45    /// Check if any domains were detected
46    pub fn is_empty(&self) -> bool {
47        self.domains.is_empty()
48    }
49
50    /// Type-safe capability check
51    ///
52    /// # Example
53    /// ```ignore
54    /// if detected.has::<Infer>() {
55    ///     // Can run inference
56    /// }
57    /// ```
58    pub fn has<C: Capability>(&self) -> bool {
59        self.capabilities.has::<C>()
60    }
61
62    /// String-based capability check (for Casbin integration)
63    pub fn has_str(&self, id: &str) -> bool {
64        self.capabilities.has_str(id)
65    }
66
67    /// Check if capability is available in a specific domain
68    pub fn has_in_domain<C: Capability>(&self, domain: &str) -> bool {
69        self.domain_capabilities
70            .get(domain)
71            .map(crate::archetypes::CapabilitySet::has::<C>)
72            .unwrap_or(false)
73    }
74
75    /// Get domains that provide a specific capability
76    pub fn domains_for<C: Capability>(&self) -> Vec<&'static str> {
77        self.domain_capabilities
78            .iter()
79            .filter(|(_, caps)| caps.has::<C>())
80            .map(|(domain, _)| *domain)
81            .collect()
82    }
83
84    /// Get domains that provide a capability by string ID
85    pub fn domains_for_str(&self, capability: &str) -> Vec<&'static str> {
86        self.domain_capabilities
87            .iter()
88            .filter(|(_, caps)| caps.has_str(capability))
89            .map(|(domain, _)| *domain)
90            .collect()
91    }
92
93    /// Get domain names as comma-separated string for display
94    pub fn domains_display(&self) -> String {
95        self.domains.join(",")
96    }
97}
98
99impl Default for DetectedDomains {
100    fn default() -> Self {
101        Self::empty()
102    }
103}
104
105// ============================================================================
106// DetectedArchetypes - uses CapabilitySet directly
107// ============================================================================
108
109/// Cached archetype detection result
110#[derive(Debug, Clone)]
111pub struct DetectedArchetypes {
112    /// Names of matched archetypes
113    pub archetypes: Vec<&'static str>,
114    /// Combined capabilities from all matched archetypes
115    pub capabilities: CapabilitySet,
116    /// When this detection was performed
117    pub detected_at: Instant,
118}
119
120impl DetectedArchetypes {
121    /// Check if any archetypes were detected
122    pub fn is_empty(&self) -> bool {
123        self.archetypes.is_empty()
124    }
125
126    /// Type-safe capability check
127    pub fn has<C: Capability>(&self) -> bool {
128        self.capabilities.has::<C>()
129    }
130
131    /// String-based capability check (for Casbin integration)
132    pub fn has_str(&self, id: &str) -> bool {
133        self.capabilities.has_str(id)
134    }
135
136    /// Get archetype names as comma-separated string for display
137    pub fn archetypes_display(&self) -> String {
138        self.archetypes.join(",")
139    }
140
141    /// Convert to `DetectedDomains` (with per-domain capability info)
142    pub fn to_detected_domains(&self) -> DetectedDomains {
143        DetectedDomains {
144            domains: self.archetypes.clone(),
145            capabilities: self.capabilities.clone(),
146            domain_capabilities: HashMap::new(), // Would need archetype info to populate
147            detected_at: self.detected_at,
148        }
149    }
150}
151
152/// Registry for archetype detection with caching
153///
154/// Caches detection results per-path with configurable TTL.
155pub struct ArchetypeRegistry {
156    archetypes: Vec<Box<dyn RepoArchetype>>,
157    cache: DashMap<PathBuf, DetectedArchetypes>,
158    cache_ttl: Duration,
159}
160
161impl Default for ArchetypeRegistry {
162    fn default() -> Self {
163        Self::new()
164    }
165}
166
167impl ArchetypeRegistry {
168    /// Create a new registry with built-in archetypes
169    pub fn new() -> Self {
170        Self {
171            archetypes: builtin_archetypes(),
172            cache: DashMap::new(),
173            cache_ttl: Duration::from_secs(60), // 1 minute default
174        }
175    }
176
177    /// Create a registry with custom TTL
178    pub fn with_ttl(ttl: Duration) -> Self {
179        Self {
180            archetypes: builtin_archetypes(),
181            cache: DashMap::new(),
182            cache_ttl: ttl,
183        }
184    }
185
186    /// Detect archetypes for a repository path
187    ///
188    /// Returns cached result if available and not expired.
189    pub fn detect(&self, repo_path: &Path) -> DetectedArchetypes {
190        let canonical = match repo_path.canonicalize() {
191            Ok(p) => p,
192            Err(_) => repo_path.to_path_buf(),
193        };
194
195        // Check cache
196        if let Some(cached) = self.cache.get(&canonical) {
197            if cached.detected_at.elapsed() < self.cache_ttl {
198                return cached.clone();
199            }
200        }
201
202        // Perform detection
203        let mut detected = DetectedArchetypes {
204            archetypes: Vec::new(),
205            capabilities: CapabilitySet::new(),
206            detected_at: Instant::now(),
207        };
208
209        for archetype in &self.archetypes {
210            if archetype.detect(&canonical) {
211                detected.archetypes.push(archetype.name());
212                detected.capabilities = detected.capabilities.union(&archetype.capabilities());
213            }
214        }
215
216        // Cache result
217        self.cache.insert(canonical, detected.clone());
218
219        detected
220    }
221
222    /// Get capabilities for a repository path
223    ///
224    /// Shorthand for `detect(path).capabilities`
225    pub fn capabilities(&self, repo_path: &Path) -> CapabilitySet {
226        self.detect(repo_path).capabilities
227    }
228
229    /// Check if a repository has a specific capability (type-safe)
230    pub fn has<C: Capability>(&self, repo_path: &Path) -> bool {
231        self.capabilities(repo_path).has::<C>()
232    }
233
234    /// Invalidate cache for a specific path
235    pub fn invalidate(&self, repo_path: &Path) {
236        if let Ok(canonical) = repo_path.canonicalize() {
237            self.cache.remove(&canonical);
238        }
239        self.cache.remove(&repo_path.to_path_buf());
240    }
241
242    /// Invalidate entire cache
243    pub fn invalidate_all(&self) {
244        self.cache.clear();
245    }
246
247    /// Get list of registered archetype names
248    pub fn archetype_names(&self) -> Vec<&'static str> {
249        self.archetypes.iter().map(|a| a.name()).collect()
250    }
251}
252
253/// Global archetype registry instance
254static REGISTRY: std::sync::OnceLock<Arc<ArchetypeRegistry>> = std::sync::OnceLock::new();
255
256/// Get the global archetype registry
257pub fn global_registry() -> Arc<ArchetypeRegistry> {
258    REGISTRY
259        .get_or_init(|| Arc::new(ArchetypeRegistry::new()))
260        .clone()
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266    use crate::archetypes::{Context, Infer, Query, Serve, Train};
267    use std::fs;
268    use tempfile::TempDir;
269
270    #[test]
271    fn test_detect_model() -> std::io::Result<()> {
272        let temp = TempDir::new()?;
273        // Valid model config requires model_type or architectures field
274        fs::write(
275            temp.path().join("config.json"),
276            r#"{"model_type": "llama"}"#,
277        )?;
278
279        let registry = ArchetypeRegistry::new();
280        let detected = registry.detect(temp.path());
281
282        assert!(detected.archetypes.contains(&"hf-model"));
283        assert!(detected.has::<Infer>());
284        Ok(())
285    }
286
287    #[test]
288    fn test_detect_dataset() -> std::io::Result<()> {
289        let temp = TempDir::new()?;
290        fs::write(temp.path().join("dataset_infos.json"), "{}")?;
291
292        let registry = ArchetypeRegistry::new();
293        let detected = registry.detect(temp.path());
294
295        assert!(detected.archetypes.contains(&"hf-dataset"));
296        assert!(detected.has::<Query>());
297        Ok(())
298    }
299
300    /// Create valid-sized DuckDB data (minimum 4KB)
301    fn valid_duckdb_data() -> Vec<u8> {
302        vec![0u8; 4096]
303    }
304
305    #[test]
306    fn test_detect_duckdb() -> std::io::Result<()> {
307        let temp = TempDir::new()?;
308        fs::write(temp.path().join("metrics.duckdb"), valid_duckdb_data())?;
309
310        let registry = ArchetypeRegistry::new();
311        let detected = registry.detect(temp.path());
312
313        assert!(detected.archetypes.contains(&"duckdb"));
314        assert!(detected.has::<Query>());
315        Ok(())
316    }
317
318    #[test]
319    fn test_detect_multiple() -> std::io::Result<()> {
320        let temp = TempDir::new()?;
321        // Both model and database
322        fs::write(
323            temp.path().join("config.json"),
324            r#"{"model_type": "llama"}"#,
325        )?;
326        fs::write(temp.path().join("metrics.duckdb"), valid_duckdb_data())?;
327
328        let registry = ArchetypeRegistry::new();
329        let detected = registry.detect(temp.path());
330
331        assert!(detected.archetypes.contains(&"hf-model"));
332        assert!(detected.archetypes.contains(&"duckdb"));
333        assert!(detected.has::<Infer>());
334        assert!(detected.has::<Query>());
335        Ok(())
336    }
337
338    #[test]
339    fn test_cache_invalidation() -> std::io::Result<()> {
340        let temp = TempDir::new()?;
341
342        let registry = ArchetypeRegistry::new();
343
344        // Initially empty
345        let detected = registry.detect(temp.path());
346        assert!(detected.is_empty());
347
348        // Add a valid model config
349        fs::write(
350            temp.path().join("config.json"),
351            r#"{"model_type": "llama"}"#,
352        )?;
353
354        // Still cached as empty
355        let detected = registry.detect(temp.path());
356        assert!(detected.is_empty());
357
358        // Invalidate and re-detect
359        registry.invalidate(temp.path());
360        let detected = registry.detect(temp.path());
361        assert!(!detected.is_empty());
362        assert!(detected.archetypes.contains(&"hf-model"));
363        Ok(())
364    }
365
366    #[test]
367    fn test_detect_cag_context() -> std::io::Result<()> {
368        let temp = TempDir::new()?;
369        fs::write(
370            temp.path().join("context.json"),
371            r#"{"version": 1, "store": {"type": "duckdb", "path": "ctx.db"}, "embedding": {"dimension": 384, "model": "test"}}"#,
372        )?;
373
374        let registry = ArchetypeRegistry::new();
375        let detected = registry.detect(temp.path());
376
377        assert!(detected.archetypes.contains(&"cag-context"));
378        assert!(detected.has::<Context>());
379        Ok(())
380    }
381
382    #[test]
383    fn test_detect_model_with_cag() -> std::io::Result<()> {
384        let temp = TempDir::new()?;
385        // Model + CAG context - model requires valid config
386        fs::write(
387            temp.path().join("config.json"),
388            r#"{"model_type": "llama"}"#,
389        )?;
390        fs::write(
391            temp.path().join("context.json"),
392            r#"{"version": 1, "store": {"type": "duckdb", "path": "ctx.db"}, "embedding": {"dimension": 384, "model": "test"}}"#,
393        )?;
394
395        let registry = ArchetypeRegistry::new();
396        let detected = registry.detect(temp.path());
397
398        assert!(detected.archetypes.contains(&"hf-model"));
399        assert!(detected.archetypes.contains(&"cag-context"));
400        assert!(detected.has::<Infer>());
401        assert!(detected.has::<Context>());
402        // Should show detected archetypes
403        assert!(detected.archetypes_display().contains("hf-model"));
404        assert!(detected.archetypes_display().contains("cag-context"));
405        Ok(())
406    }
407
408    // ========================================================================
409    // DetectedDomains tests (new type-safe API)
410    // ========================================================================
411
412    #[test]
413    fn test_detected_domains_type_safe_has() -> std::io::Result<()> {
414        let temp = TempDir::new()?;
415        fs::write(
416            temp.path().join("config.json"),
417            r#"{"model_type": "llama"}"#,
418        )?;
419
420        let registry = ArchetypeRegistry::new();
421        let detected = registry.detect(temp.path());
422
423        // Convert to new type
424        let domains = detected.to_detected_domains();
425
426        // Type-safe checks
427        assert!(domains.has::<Infer>());
428        assert!(domains.has::<Train>());
429        assert!(domains.has::<Serve>());
430        assert!(!domains.has::<Query>());
431        Ok(())
432    }
433
434    #[test]
435    fn test_detected_domains_string_has() -> std::io::Result<()> {
436        let temp = TempDir::new()?;
437        fs::write(
438            temp.path().join("config.json"),
439            r#"{"model_type": "llama"}"#,
440        )?;
441
442        let registry = ArchetypeRegistry::new();
443        let detected = registry.detect(temp.path()).to_detected_domains();
444
445        // String-based checks (for Casbin integration)
446        assert!(detected.has_str("infer"));
447        assert!(detected.has_str("train"));
448        assert!(!detected.has_str("query"));
449        assert!(!detected.has_str("unknown"));
450        Ok(())
451    }
452
453    #[test]
454    fn test_detected_domains_display() -> std::io::Result<()> {
455        let temp = TempDir::new()?;
456        fs::write(
457            temp.path().join("config.json"),
458            r#"{"model_type": "llama"}"#,
459        )?;
460        fs::write(
461            temp.path().join("context.json"),
462            r#"{"version": 1, "store": {"type": "duckdb", "path": "ctx.db"}, "embedding": {"dimension": 384, "model": "test"}}"#,
463        )?;
464
465        let registry = ArchetypeRegistry::new();
466        let domains = registry.detect(temp.path()).to_detected_domains();
467
468        // Display shows domain names
469        assert!(domains.domains_display().contains("hf-model"));
470        assert!(domains.domains_display().contains("cag-context"));
471        Ok(())
472    }
473
474    #[test]
475    fn test_detected_domains_empty() {
476        let domains = DetectedDomains::empty();
477        assert!(domains.is_empty());
478        assert!(!domains.has::<Infer>());
479        assert_eq!(domains.domains_display(), "");
480    }
481}