Skip to main content

hyprstream_core/archetypes/
cag.rs

1//! CAG (Context-Augmented Generation) archetype detection
2//!
3//! Detects repositories containing a context store for context-augmented generation.
4//! Detection is based on presence of `context.json` manifest file.
5
6use super::capabilities::{CapabilitySet, Context};
7use super::RepoArchetype;
8use std::path::Path;
9
10/// CAG Context archetype
11///
12/// Detects repos with:
13/// - `context.json` (context store manifest)
14///
15/// The manifest declares the context store configuration:
16/// ```json
17/// {
18///   "version": 1,
19///   "store": {
20///     "type": "duckdb",
21///     "path": "context.duckdb"
22///   },
23///   "embedding": {
24///     "dimension": 384,
25///     "model": "sentence-transformers/all-MiniLM-L6-v2"
26///   }
27/// }
28/// ```
29///
30/// Enables: CONTEXT
31///
32/// When combined with HfModelArchetype, enables context-augmented inference.
33pub struct CagContextArchetype;
34
35impl RepoArchetype for CagContextArchetype {
36    fn name(&self) -> &'static str {
37        "cag-context"
38    }
39
40    fn description(&self) -> &'static str {
41        "Context store for context-augmented generation (CAG)"
42    }
43
44    fn detect(&self, repo_path: &Path) -> bool {
45        // Detection: context.json exists
46        let context_manifest = repo_path.join("context.json");
47        if context_manifest.exists() {
48            // Optionally validate it's valid JSON with expected structure
49            if let Ok(content) = std::fs::read_to_string(&context_manifest) {
50                // Basic validation: should be valid JSON with version field
51                if let Ok(json) = serde_json::from_str::<serde_json::Value>(&content) {
52                    return json.get("version").is_some();
53                }
54            }
55        }
56        false
57    }
58
59    fn capabilities(&self) -> CapabilitySet {
60        let mut caps = CapabilitySet::new();
61        caps.insert::<Context>();
62        caps
63    }
64}
65
66/// Configuration for a CAG context store
67#[allow(dead_code)] // Future: CAG context integration
68#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
69pub struct ContextManifest {
70    /// Manifest version
71    pub version: u32,
72    /// Context store configuration
73    pub store: StoreConfig,
74    /// Embedding configuration
75    pub embedding: EmbeddingConfig,
76}
77
78/// Context store backend configuration
79#[allow(dead_code)] // Future: CAG context integration
80#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
81pub struct StoreConfig {
82    /// Store type: "duckdb"
83    #[serde(rename = "type")]
84    pub store_type: String,
85    /// Path to store file (relative to repo root)
86    pub path: String,
87}
88
89/// Embedding model configuration
90#[allow(dead_code)] // Future: CAG context integration
91#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
92pub struct EmbeddingConfig {
93    /// Embedding dimension
94    pub dimension: u32,
95    /// Embedding model identifier (e.g., HuggingFace model ID)
96    pub model: String,
97}
98
99impl ContextManifest {
100    /// Load context manifest from a repository path
101    #[allow(dead_code)] // Future: CAG context integration
102    pub fn load(repo_path: &Path) -> Result<Self, std::io::Error> {
103        let manifest_path = repo_path.join("context.json");
104        let content = std::fs::read_to_string(&manifest_path)?;
105        serde_json::from_str(&content)
106            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113    use std::fs;
114    use tempfile::TempDir;
115
116    #[test]
117    fn test_detect_with_context_json() -> std::io::Result<()> {
118        let temp = TempDir::new()?;
119        let manifest_path = temp.path().join("context.json");
120        fs::write(
121            &manifest_path,
122            r#"{
123                "version": 1,
124                "store": {
125                    "type": "duckdb",
126                    "path": "context.duckdb"
127                },
128                "embedding": {
129                    "dimension": 384,
130                    "model": "sentence-transformers/all-MiniLM-L6-v2"
131                }
132            }"#,
133        )?;
134
135        let archetype = CagContextArchetype;
136        assert!(archetype.detect(temp.path()));
137        Ok(())
138    }
139
140    #[test]
141    fn test_no_detect_empty_dir() -> std::io::Result<()> {
142        let temp = TempDir::new()?;
143
144        let archetype = CagContextArchetype;
145        assert!(!archetype.detect(temp.path()));
146        Ok(())
147    }
148
149    #[test]
150    fn test_no_detect_invalid_json() -> std::io::Result<()> {
151        let temp = TempDir::new()?;
152        let manifest_path = temp.path().join("context.json");
153        fs::write(&manifest_path, "not valid json")?;
154
155        let archetype = CagContextArchetype;
156        assert!(!archetype.detect(temp.path()));
157        Ok(())
158    }
159
160    #[test]
161    fn test_no_detect_missing_version() -> std::io::Result<()> {
162        let temp = TempDir::new()?;
163        let manifest_path = temp.path().join("context.json");
164        fs::write(&manifest_path, r#"{"store": {}}"#)?;
165
166        let archetype = CagContextArchetype;
167        assert!(!archetype.detect(temp.path()));
168        Ok(())
169    }
170
171    #[test]
172    fn test_capabilities() {
173        use super::super::capabilities::{Infer, Query};
174
175        let archetype = CagContextArchetype;
176        let caps = archetype.capabilities();
177
178        assert!(caps.has::<Context>());
179        assert!(!caps.has::<Infer>());
180        assert!(!caps.has::<Query>());
181    }
182
183    #[test]
184    fn test_load_manifest() -> std::io::Result<()> {
185        let temp = TempDir::new()?;
186        let manifest_path = temp.path().join("context.json");
187        fs::write(
188            &manifest_path,
189            r#"{
190                "version": 1,
191                "store": {
192                    "type": "duckdb",
193                    "path": "context.duckdb"
194                },
195                "embedding": {
196                    "dimension": 384,
197                    "model": "sentence-transformers/all-MiniLM-L6-v2"
198                }
199            }"#,
200        )?;
201
202        let manifest = ContextManifest::load(temp.path())?;
203        assert_eq!(manifest.version, 1);
204        assert_eq!(manifest.store.store_type, "duckdb");
205        assert_eq!(manifest.store.path, "context.duckdb");
206        assert_eq!(manifest.embedding.dimension, 384);
207        Ok(())
208    }
209}