Skip to main content

sprite/models/
config.rs

1//! Configuration data structures for the Sprite multi-agent workflow toolkit.
2
3use super::{Agent, ConflictResolution, LogLevel};
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::path::PathBuf;
7
8/// Top-level configuration that defines the entire multi-agent setup.
9#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct ProjectConfig {
11    /// Configuration version for migration support
12    pub version: String,
13
14    /// List of configured agents
15    pub agents: Vec<Agent>,
16
17    /// Session configuration name (references a tmux profile)
18    pub session_name: String,
19
20    /// Synchronization settings
21    pub sync: SyncConfig,
22
23    /// Global project settings
24    pub settings: ProjectSettings,
25}
26
27#[allow(dead_code)]
28impl ProjectConfig {
29    /// Create a new project configuration with default values.
30    pub fn new() -> Self {
31        Self {
32            version: "1.0".to_string(),
33            agents: Vec::new(),
34            session_name: "default".to_string(),
35            sync: SyncConfig::default(),
36            settings: ProjectSettings::default(),
37        }
38    }
39
40    /// Add an agent to the configuration.
41    pub fn add_agent(&mut self, agent: Agent) -> Result<(), String> {
42        // Check for duplicate agent IDs
43        if self.agents.iter().any(|a| a.id == agent.id) {
44            return Err(format!("Agent with ID '{}' already exists", agent.id));
45        }
46
47        // Validate the agent
48        agent.validate()?;
49        self.agents.push(agent);
50        Ok(())
51    }
52
53    /// Remove an agent by ID.
54    pub fn remove_agent(&mut self, agent_id: &str) -> Option<Agent> {
55        let index = self.agents.iter().position(|a| a.id == agent_id)?;
56        Some(self.agents.remove(index))
57    }
58
59    /// Get an agent by ID.
60    pub fn get_agent(&self, agent_id: &str) -> Option<&Agent> {
61        self.agents.iter().find(|a| a.id == agent_id)
62    }
63
64    /// Get an agent by ID (mutable).
65    pub fn get_agent_mut(&mut self, agent_id: &str) -> Option<&mut Agent> {
66        self.agents.iter_mut().find(|a| a.id == agent_id)
67    }
68
69    /// Get the number of configured agents.
70    pub fn agent_count(&self) -> usize {
71        self.agents.len()
72    }
73
74    /// Get active agents only.
75    pub fn active_agents(&self) -> Vec<&Agent> {
76        self.agents.iter().filter(|a| a.is_active()).collect()
77    }
78
79    /// Validate the entire configuration.
80    pub fn validate(&self) -> Result<(), String> {
81        // Validate version
82        if self.version.is_empty() {
83            return Err("Configuration version cannot be empty".to_string());
84        }
85
86        // Validate agents
87        if self.agents.is_empty() {
88            return Err("At least one agent must be configured".to_string());
89        }
90
91        // Check for duplicate agent IDs
92        let mut agent_ids = std::collections::HashSet::new();
93        for agent in &self.agents {
94            if !agent_ids.insert(&agent.id) {
95                return Err(format!("Duplicate agent ID: {}", agent.id));
96            }
97            agent.validate()?;
98        }
99
100        // Validate session name
101        if self.session_name.is_empty() {
102            return Err("Session name cannot be empty".to_string());
103        }
104
105        // Validate sync config
106        self.sync.validate()?;
107
108        // Validate settings
109        self.settings.validate()?;
110
111        Ok(())
112    }
113
114    /// Get the configuration file path.
115    pub fn config_path() -> PathBuf {
116        PathBuf::from("agents/agents.yaml")
117    }
118
119    /// Load configuration from a file.
120    pub fn load_from_file(path: &PathBuf) -> Result<Self, String> {
121        let content = std::fs::read_to_string(path)
122            .map_err(|e| format!("Failed to read configuration file: {}", e))?;
123
124        let config: ProjectConfig = serde_yaml::from_str(&content)
125            .map_err(|e| format!("Failed to parse configuration: {}", e))?;
126
127        config.validate()?;
128        Ok(config)
129    }
130
131    /// Save configuration to a file.
132    pub fn save_to_file(&self, path: &PathBuf) -> Result<(), String> {
133        // Validate before saving
134        self.validate()?;
135
136        // Create parent directory if it doesn't exist
137        if let Some(parent) = path.parent() {
138            std::fs::create_dir_all(parent)
139                .map_err(|e| format!("Failed to create config directory: {}", e))?;
140        }
141
142        let content = serde_yaml::to_string(self)
143            .map_err(|e| format!("Failed to serialize configuration: {}", e))?;
144
145        std::fs::write(path, content)
146            .map_err(|e| format!("Failed to write configuration file: {}", e))?;
147
148        Ok(())
149    }
150}
151
152impl Default for ProjectConfig {
153    fn default() -> Self {
154        Self::new()
155    }
156}
157
158/// Synchronization settings.
159#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct SyncConfig {
161    /// Whether to automatically sync agents
162    pub auto_sync: bool,
163
164    /// Default sync interval in seconds
165    pub default_interval_secs: u64,
166
167    /// Conflict resolution strategy
168    pub conflict_resolution: ConflictResolution,
169
170    /// Branches to exclude from auto-sync
171    pub exclude_branches: Vec<String>,
172
173    /// Pre-sync hooks
174    pub pre_sync_hooks: Vec<SyncHook>,
175
176    /// Post-sync hooks
177    pub post_sync_hooks: Vec<SyncHook>,
178}
179
180#[allow(dead_code)]
181impl SyncConfig {
182    /// Validate the sync configuration.
183    pub fn validate(&self) -> Result<(), String> {
184        if self.default_interval_secs == 0 {
185            return Err("Sync interval must be greater than 0".to_string());
186        }
187
188        // Validate hooks
189        for (i, hook) in self.pre_sync_hooks.iter().enumerate() {
190            hook.validate()
191                .map_err(|e| format!("Pre-sync hook {}: {}", i + 1, e))?;
192        }
193
194        for (i, hook) in self.post_sync_hooks.iter().enumerate() {
195            hook.validate()
196                .map_err(|e| format!("Post-sync hook {}: {}", i + 1, e))?;
197        }
198
199        Ok(())
200    }
201
202    /// Check if a branch should be excluded from sync.
203    pub fn should_exclude_branch(&self, branch: &str) -> bool {
204        self.exclude_branches.iter().any(|excluded| {
205            if excluded.ends_with('*') {
206                branch.starts_with(&excluded[..excluded.len() - 1])
207            } else {
208                excluded == branch
209            }
210        })
211    }
212}
213
214impl Default for SyncConfig {
215    fn default() -> Self {
216        Self {
217            auto_sync: false,
218            default_interval_secs: 300, // 5 minutes
219            conflict_resolution: ConflictResolution::default(),
220            exclude_branches: vec!["main".to_string(), "master".to_string()],
221            pre_sync_hooks: Vec::new(),
222            post_sync_hooks: Vec::new(),
223        }
224    }
225}
226
227/// Hook configuration for sync operations.
228#[derive(Debug, Clone, Serialize, Deserialize)]
229pub struct SyncHook {
230    /// Hook command to execute
231    pub command: String,
232
233    /// Arguments for the command
234    pub args: Vec<String>,
235
236    /// Working directory for the hook
237    pub work_dir: Option<PathBuf>,
238
239    /// Whether hook failure should stop sync
240    pub required: bool,
241
242    /// Timeout for the hook in seconds
243    pub timeout_secs: Option<u64>,
244}
245
246#[allow(dead_code)]
247impl SyncHook {
248    /// Validate the hook configuration.
249    pub fn validate(&self) -> Result<(), String> {
250        if self.command.is_empty() {
251            return Err("Hook command cannot be empty".to_string());
252        }
253
254        if let Some(ref work_dir) = self.work_dir {
255            if work_dir.as_os_str().is_empty() {
256                return Err("Hook working directory cannot be empty".to_string());
257            }
258        }
259
260        Ok(())
261    }
262
263    /// Execute the hook.
264    pub fn execute(&self) -> Result<std::process::Output, String> {
265        use std::process::Command;
266
267        let mut cmd = Command::new(&self.command);
268        cmd.args(&self.args);
269
270        if let Some(ref work_dir) = self.work_dir {
271            cmd.current_dir(work_dir);
272        }
273
274        let output = cmd
275            .output()
276            .map_err(|e| format!("Failed to execute hook command '{}': {}", self.command, e))?;
277
278        Ok(output)
279    }
280}
281
282/// Global project settings.
283#[derive(Debug, Clone, Serialize, Deserialize)]
284pub struct ProjectSettings {
285    /// Default shell for agent operations
286    pub default_shell: String,
287
288    /// Global environment variables
289    pub global_env_vars: HashMap<String, String>,
290
291    /// Logging configuration
292    pub logging: LoggingConfig,
293
294    /// Performance settings
295    pub performance: PerformanceSettings,
296
297    /// Security settings
298    pub security: SecuritySettings,
299}
300
301#[allow(dead_code)]
302impl ProjectSettings {
303    /// Validate the project settings.
304    pub fn validate(&self) -> Result<(), String> {
305        if self.default_shell.is_empty() {
306            return Err("Default shell cannot be empty".to_string());
307        }
308
309        self.logging.validate()?;
310        self.performance.validate()?;
311        self.security.validate()?;
312
313        Ok(())
314    }
315
316    /// Get effective environment variables (global + agent-specific).
317    pub fn get_effective_env(
318        &self,
319        agent_env: &HashMap<String, String>,
320    ) -> HashMap<String, String> {
321        let mut env = self.global_env_vars.clone();
322        for (key, value) in agent_env {
323            env.insert(key.clone(), value.clone());
324        }
325        env
326    }
327}
328
329impl Default for ProjectSettings {
330    fn default() -> Self {
331        Self {
332            default_shell: "bash".to_string(),
333            global_env_vars: HashMap::new(),
334            logging: LoggingConfig::default(),
335            performance: PerformanceSettings::default(),
336            security: SecuritySettings::default(),
337        }
338    }
339}
340
341/// Logging configuration.
342#[derive(Debug, Clone, Serialize, Deserialize)]
343pub struct LoggingConfig {
344    /// Log file location
345    pub log_file: Option<PathBuf>,
346
347    /// Log level
348    pub level: LogLevel,
349
350    /// Whether to log to stdout
351    pub log_to_stdout: bool,
352
353    /// Log rotation settings
354    pub rotation: Option<LogRotation>,
355}
356
357#[allow(dead_code)]
358impl LoggingConfig {
359    /// Validate the logging configuration.
360    pub fn validate(&self) -> Result<(), String> {
361        if let Some(ref log_file) = self.log_file {
362            if log_file.as_os_str().is_empty() {
363                return Err("Log file path cannot be empty".to_string());
364            }
365        }
366
367        if let Some(ref rotation) = self.rotation {
368            rotation.validate()?;
369        }
370
371        Ok(())
372    }
373}
374
375impl Default for LoggingConfig {
376    fn default() -> Self {
377        Self {
378            log_file: Some(PathBuf::from("agents/logs/sprite.log")),
379            level: LogLevel::default(),
380            log_to_stdout: true,
381            rotation: Some(LogRotation::default()),
382        }
383    }
384}
385
386/// Log rotation settings.
387#[derive(Debug, Clone, Serialize, Deserialize)]
388pub struct LogRotation {
389    /// Maximum log file size in MB
390    pub max_size_mb: u64,
391
392    /// Maximum number of log files to keep
393    pub max_files: u32,
394}
395
396#[allow(dead_code)]
397impl LogRotation {
398    /// Validate the log rotation settings.
399    pub fn validate(&self) -> Result<(), String> {
400        if self.max_size_mb == 0 {
401            return Err("Maximum log file size must be greater than 0".to_string());
402        }
403
404        if self.max_files == 0 {
405            return Err("Maximum number of log files must be greater than 0".to_string());
406        }
407
408        Ok(())
409    }
410}
411
412impl Default for LogRotation {
413    fn default() -> Self {
414        Self {
415            max_size_mb: 100, // 100MB
416            max_files: 5,
417        }
418    }
419}
420
421/// Performance settings.
422#[derive(Debug, Clone, Serialize, Deserialize)]
423pub struct PerformanceSettings {
424    /// Maximum concurrent operations
425    pub max_concurrent_ops: u32,
426
427    /// Timeout for operations in seconds
428    pub default_timeout_secs: u64,
429
430    /// Whether to enable performance monitoring
431    pub enable_monitoring: bool,
432
433    /// Memory limit in MB
434    pub memory_limit_mb: Option<u64>,
435
436    /// CPU limit as percentage
437    pub cpu_limit_percent: Option<u8>,
438}
439
440#[allow(dead_code)]
441impl PerformanceSettings {
442    /// Validate the performance settings.
443    pub fn validate(&self) -> Result<(), String> {
444        if self.max_concurrent_ops == 0 {
445            return Err("Maximum concurrent operations must be greater than 0".to_string());
446        }
447
448        if self.default_timeout_secs == 0 {
449            return Err("Default timeout must be greater than 0".to_string());
450        }
451
452        if let Some(cpu_limit) = self.cpu_limit_percent {
453            if cpu_limit == 0 || cpu_limit > 100 {
454                return Err("CPU limit must be between 1 and 100".to_string());
455            }
456        }
457
458        Ok(())
459    }
460}
461
462impl Default for PerformanceSettings {
463    fn default() -> Self {
464        Self {
465            max_concurrent_ops: 10,
466            default_timeout_secs: 300, // 5 minutes
467            enable_monitoring: true,
468            memory_limit_mb: Some(1024), // 1GB
469            cpu_limit_percent: Some(80), // 80%
470        }
471    }
472}
473
474/// Security settings.
475#[derive(Debug, Clone, Serialize, Deserialize)]
476pub struct SecuritySettings {
477    /// Allowed workspace paths
478    pub allowed_paths: Vec<PathBuf>,
479
480    /// Blocked commands
481    pub blocked_commands: Vec<String>,
482
483    /// Whether to validate paths strictly
484    pub strict_path_validation: bool,
485
486    /// Maximum command length
487    pub max_command_length: Option<usize>,
488
489    /// Whether to allow shell command execution
490    pub allow_shell_execution: bool,
491}
492
493#[allow(dead_code)]
494impl SecuritySettings {
495    /// Validate the security settings.
496    pub fn validate(&self) -> Result<(), String> {
497        if let Some(max_length) = self.max_command_length {
498            if max_length == 0 {
499                return Err("Maximum command length must be greater than 0".to_string());
500            }
501        }
502
503        for path in &self.allowed_paths {
504            if path.as_os_str().is_empty() {
505                return Err("Allowed paths cannot contain empty paths".to_string());
506            }
507        }
508
509        Ok(())
510    }
511
512    /// Check if a command is blocked.
513    pub fn is_command_blocked(&self, command: &str) -> bool {
514        self.blocked_commands.iter().any(|blocked| {
515            if blocked.ends_with('*') {
516                command.starts_with(&blocked[..blocked.len() - 1])
517            } else {
518                // Check exact match or if command starts with blocked command
519                blocked == command || command.starts_with(&format!("{} ", blocked))
520            }
521        })
522    }
523
524    /// Check if a path is allowed.
525    pub fn is_path_allowed(&self, path: &PathBuf) -> bool {
526        if !self.strict_path_validation {
527            return true;
528        }
529
530        if self.allowed_paths.is_empty() {
531            return true; // If no restrictions, allow all
532        }
533
534        self.allowed_paths
535            .iter()
536            .any(|allowed| path.starts_with(allowed) || path == allowed)
537    }
538}
539
540impl Default for SecuritySettings {
541    fn default() -> Self {
542        Self {
543            allowed_paths: vec![PathBuf::from("agents/")],
544            blocked_commands: vec![
545                "rm -rf".to_string(),
546                "sudo".to_string(),
547                "su".to_string(),
548                "chmod 777".to_string(),
549            ],
550            strict_path_validation: true,
551            max_command_length: Some(1000),
552            allow_shell_execution: false,
553        }
554    }
555}
556
557#[cfg(test)]
558mod tests {
559    use super::*;
560
561    #[test]
562    fn test_project_config_creation() {
563        let config = ProjectConfig::new();
564        assert_eq!(config.version, "1.0");
565        assert_eq!(config.agents.len(), 0);
566        assert_eq!(config.settings.default_shell, "bash");
567    }
568
569    #[test]
570    fn test_add_agent() {
571        let mut config = ProjectConfig::new();
572        let agent = Agent::new("agent-1", "feature/test");
573
574        assert!(config.add_agent(agent.clone()).is_ok());
575        assert_eq!(config.agent_count(), 1);
576
577        // Test duplicate agent
578        assert!(config.add_agent(agent).is_err());
579    }
580
581    #[test]
582    fn test_remove_agent() {
583        let mut config = ProjectConfig::new();
584        let agent = Agent::new("agent-1", "feature/test");
585
586        config.add_agent(agent).unwrap();
587        assert_eq!(config.agent_count(), 1);
588
589        let removed = config.remove_agent("agent-1");
590        assert!(removed.is_some());
591        assert_eq!(config.agent_count(), 0);
592
593        // Test removing non-existent agent
594        let removed = config.remove_agent("non-existent");
595        assert!(removed.is_none());
596    }
597
598    #[test]
599    fn test_config_validation() {
600        let mut config = ProjectConfig::new();
601
602        // Empty config should fail (no agents)
603        assert!(config.validate().is_err());
604
605        // Add an agent
606        let agent = Agent::new("agent-1", "feature/test");
607        config.add_agent(agent).unwrap();
608
609        // Now should be valid
610        assert!(config.validate().is_ok());
611    }
612
613    #[test]
614    fn test_sync_config() {
615        let sync = SyncConfig::default();
616        assert!(!sync.auto_sync);
617        assert_eq!(sync.default_interval_secs, 300);
618        assert!(sync.should_exclude_branch("main"));
619        assert!(!sync.should_exclude_branch("feature/test"));
620    }
621
622    #[test]
623    fn test_security_settings() {
624        let security = SecuritySettings::default();
625        assert!(security.is_command_blocked("rm -rf"));
626        assert!(security.is_command_blocked("sudo ls"));
627        assert!(!security.is_command_blocked("git status"));
628        assert!(security.is_path_allowed(&PathBuf::from("agents/agent-1")));
629        assert!(!security.is_path_allowed(&PathBuf::from("/etc/passwd")));
630    }
631
632    #[test]
633    fn test_sync_hook() {
634        let hook = SyncHook {
635            command: "echo".to_string(),
636            args: vec!["test".to_string()],
637            work_dir: None,
638            required: false,
639            timeout_secs: Some(30),
640        };
641
642        assert!(hook.validate().is_ok());
643
644        let invalid_hook = SyncHook {
645            command: "".to_string(),
646            args: vec![],
647            work_dir: None,
648            required: false,
649            timeout_secs: None,
650        };
651
652        assert!(invalid_hook.validate().is_err());
653    }
654}