Skip to main content

codive_prompts/
composer.rs

1//! Prompt composition with layering support
2
3use chrono::{Local, Utc};
4
5use crate::loader::PromptStore;
6use crate::ProviderFamily;
7
8/// Layer type for prompt composition
9#[derive(Debug, Clone)]
10enum PromptLayer {
11    Base,
12    Provider(ProviderFamily),
13    Verification,
14    Environment(EnvironmentContext),
15    Custom(String),
16}
17
18/// Runtime environment context
19#[derive(Debug, Clone)]
20pub struct EnvironmentContext {
21    pub working_dir: String,
22    pub platform: String,
23    pub os_version: Option<String>,
24    pub is_git_repo: bool,
25    pub git_branch: Option<String>,
26}
27
28impl EnvironmentContext {
29    /// Create context from current environment
30    pub fn from_current() -> Self {
31        let working_dir = std::env::current_dir()
32            .map(|p| p.display().to_string())
33            .unwrap_or_else(|_| ".".to_string());
34
35        Self {
36            working_dir,
37            platform: std::env::consts::OS.to_string(),
38            os_version: None,
39            is_git_repo: std::path::Path::new(".git").exists(),
40            git_branch: None,
41        }
42    }
43
44    /// Set working directory
45    pub fn with_working_dir(mut self, dir: impl Into<String>) -> Self {
46        self.working_dir = dir.into();
47        self
48    }
49
50    /// Set git repository status
51    pub fn with_git_repo(mut self, is_repo: bool) -> Self {
52        self.is_git_repo = is_repo;
53        self
54    }
55
56    /// Set git branch
57    pub fn with_git_branch(mut self, branch: impl Into<String>) -> Self {
58        self.git_branch = Some(branch.into());
59        self
60    }
61
62    /// Set OS version
63    pub fn with_os_version(mut self, version: impl Into<String>) -> Self {
64        self.os_version = Some(version.into());
65        self
66    }
67
68    /// Format as prompt section
69    fn format(&self) -> String {
70        let mut lines = vec![
71            "# Environment".to_string(),
72            format!("Working directory: {}", self.working_dir),
73            format!("Platform: {}", self.platform),
74        ];
75
76        if let Some(ref version) = self.os_version {
77            lines.push(format!("OS Version: {}", version));
78        }
79
80        lines.push(format!("Is git repo: {}", if self.is_git_repo { "Yes" } else { "No" }));
81
82        if let Some(ref branch) = self.git_branch {
83            lines.push(format!("Git branch: {}", branch));
84        }
85
86        lines.push(format!("Today's date: {}", Local::now().format("%Y-%m-%d")));
87        lines.push(format!("Current time (UTC): {}", Utc::now().format("%H:%M")));
88
89        lines.join("\n")
90    }
91}
92
93impl Default for EnvironmentContext {
94    fn default() -> Self {
95        Self::from_current()
96    }
97}
98
99/// Builder for composing prompts from multiple layers
100#[derive(Debug)]
101pub struct PromptComposer<'a> {
102    store: &'a PromptStore,
103    layers: Vec<PromptLayer>,
104}
105
106impl<'a> PromptComposer<'a> {
107    /// Create a new composer with the given prompt store
108    pub fn new(store: &'a PromptStore) -> Self {
109        Self {
110            store,
111            layers: Vec::new(),
112        }
113    }
114
115    /// Add the base system prompt layer
116    pub fn with_base(mut self) -> Self {
117        self.layers.push(PromptLayer::Base);
118        self
119    }
120
121    /// Add a provider-specific prompt layer
122    pub fn with_provider(mut self, family: ProviderFamily) -> Self {
123        self.layers.push(PromptLayer::Provider(family));
124        self
125    }
126
127    /// Auto-detect provider from model ID and add layer
128    pub fn with_provider_auto(self, model_id: &str) -> Self {
129        let family = ProviderFamily::from_model_id(model_id);
130        self.with_provider(family)
131    }
132
133    /// Add verification instructions layer
134    pub fn with_verification(mut self) -> Self {
135        self.layers.push(PromptLayer::Verification);
136        self
137    }
138
139    /// Conditionally add verification layer
140    pub fn with_verification_if(self, enabled: bool) -> Self {
141        if enabled {
142            self.with_verification()
143        } else {
144            self
145        }
146    }
147
148    /// Add environment context layer
149    pub fn with_environment(mut self, context: EnvironmentContext) -> Self {
150        self.layers.push(PromptLayer::Environment(context));
151        self
152    }
153
154    /// Add current environment context layer
155    pub fn with_current_environment(self) -> Self {
156        self.with_environment(EnvironmentContext::from_current())
157    }
158
159    /// Add a custom prompt section
160    pub fn with_custom(mut self, content: impl Into<String>) -> Self {
161        self.layers.push(PromptLayer::Custom(content.into()));
162        self
163    }
164
165    /// Compose all layers into a single prompt string
166    pub fn compose(&self) -> String {
167        let sections: Vec<String> = self
168            .layers
169            .iter()
170            .map(|layer| self.render_layer(layer))
171            .collect();
172
173        sections.join("\n\n")
174    }
175
176    fn render_layer(&self, layer: &PromptLayer) -> String {
177        match layer {
178            PromptLayer::Base => self.store.base().to_string(),
179            PromptLayer::Provider(family) => self.store.provider(*family).to_string(),
180            PromptLayer::Verification => self.store.verification().to_string(),
181            PromptLayer::Environment(ctx) => ctx.format(),
182            PromptLayer::Custom(content) => content.clone(),
183        }
184    }
185}
186
187/// Quick helper to compose a standard prompt
188pub fn compose_standard(store: &PromptStore, model_id: &str, verification: bool) -> String {
189    PromptComposer::new(store)
190        .with_base()
191        .with_provider_auto(model_id)
192        .with_current_environment()
193        .with_verification_if(verification)
194        .compose()
195}
196
197#[cfg(test)]
198mod tests {
199    use super::*;
200
201    #[test]
202    fn test_compose_basic() {
203        let store = PromptStore::default();
204        let prompt = PromptComposer::new(&store)
205            .with_base()
206            .compose();
207
208        assert!(!prompt.is_empty());
209        assert!(prompt.contains("CLI tool"));
210    }
211
212    #[test]
213    fn test_compose_with_provider() {
214        let store = PromptStore::default();
215        let prompt = PromptComposer::new(&store)
216            .with_base()
217            .with_provider(ProviderFamily::Anthropic)
218            .compose();
219
220        assert!(prompt.contains("AI"));
221        // Should have provider-specific content
222        assert!(prompt.len() > store.base().len());
223    }
224
225    #[test]
226    fn test_compose_auto_provider() {
227        let store = PromptStore::default();
228
229        let claude_prompt = PromptComposer::new(&store)
230            .with_base()
231            .with_provider_auto("claude-3-opus")
232            .compose();
233
234        let gpt_prompt = PromptComposer::new(&store)
235            .with_base()
236            .with_provider_auto("gpt-4")
237            .compose();
238
239        // Different providers should produce different prompts
240        assert_ne!(claude_prompt, gpt_prompt);
241    }
242
243    #[test]
244    fn test_compose_with_environment() {
245        let store = PromptStore::default();
246        let ctx = EnvironmentContext::default()
247            .with_working_dir("/test/project")
248            .with_git_repo(true)
249            .with_git_branch("main");
250
251        let prompt = PromptComposer::new(&store)
252            .with_base()
253            .with_environment(ctx)
254            .compose();
255
256        assert!(prompt.contains("/test/project"));
257        assert!(prompt.contains("main"));
258    }
259
260    #[test]
261    fn test_compose_with_verification() {
262        let store = PromptStore::default();
263
264        let with_verify = PromptComposer::new(&store)
265            .with_base()
266            .with_verification()
267            .compose();
268
269        let without_verify = PromptComposer::new(&store)
270            .with_base()
271            .with_verification_if(false)
272            .compose();
273
274        assert!(with_verify.len() > without_verify.len());
275        assert!(with_verify.contains("verification") || with_verify.contains("Verification"));
276    }
277
278    #[test]
279    fn test_compose_with_custom() {
280        let store = PromptStore::default();
281        let prompt = PromptComposer::new(&store)
282            .with_base()
283            .with_custom("# Custom Section\nThis is custom content.")
284            .compose();
285
286        assert!(prompt.contains("Custom Section"));
287        assert!(prompt.contains("custom content"));
288    }
289
290    #[test]
291    fn test_compose_standard() {
292        let store = PromptStore::default();
293        let prompt = compose_standard(&store, "claude-3-sonnet", true);
294
295        // Should have all standard sections
296        assert!(!prompt.is_empty());
297        // Check for environment section
298        assert!(prompt.contains("Environment"));
299    }
300
301    #[test]
302    fn test_environment_context() {
303        let ctx = EnvironmentContext::default()
304            .with_working_dir("/home/user/project")
305            .with_git_repo(true)
306            .with_git_branch("feature-branch")
307            .with_os_version("Ubuntu 22.04");
308
309        let formatted = ctx.format();
310
311        assert!(formatted.contains("/home/user/project"));
312        assert!(formatted.contains("feature-branch"));
313        assert!(formatted.contains("Ubuntu 22.04"));
314        assert!(formatted.contains("Yes")); // git repo
315    }
316}