1use super::{Agent, ConflictResolution, LogLevel};
4use serde::{Deserialize, Serialize};
5use std::collections::HashMap;
6use std::path::PathBuf;
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
10pub struct ProjectConfig {
11 pub version: String,
13
14 pub agents: Vec<Agent>,
16
17 pub session_name: String,
19
20 pub sync: SyncConfig,
22
23 pub settings: ProjectSettings,
25}
26
27#[allow(dead_code)]
28impl ProjectConfig {
29 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 pub fn add_agent(&mut self, agent: Agent) -> Result<(), String> {
42 if self.agents.iter().any(|a| a.id == agent.id) {
44 return Err(format!("Agent with ID '{}' already exists", agent.id));
45 }
46
47 agent.validate()?;
49 self.agents.push(agent);
50 Ok(())
51 }
52
53 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 pub fn get_agent(&self, agent_id: &str) -> Option<&Agent> {
61 self.agents.iter().find(|a| a.id == agent_id)
62 }
63
64 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 pub fn agent_count(&self) -> usize {
71 self.agents.len()
72 }
73
74 pub fn active_agents(&self) -> Vec<&Agent> {
76 self.agents.iter().filter(|a| a.is_active()).collect()
77 }
78
79 pub fn validate(&self) -> Result<(), String> {
81 if self.version.is_empty() {
83 return Err("Configuration version cannot be empty".to_string());
84 }
85
86 if self.agents.is_empty() {
88 return Err("At least one agent must be configured".to_string());
89 }
90
91 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 if self.session_name.is_empty() {
102 return Err("Session name cannot be empty".to_string());
103 }
104
105 self.sync.validate()?;
107
108 self.settings.validate()?;
110
111 Ok(())
112 }
113
114 pub fn config_path() -> PathBuf {
116 PathBuf::from("agents/agents.yaml")
117 }
118
119 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 pub fn save_to_file(&self, path: &PathBuf) -> Result<(), String> {
133 self.validate()?;
135
136 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#[derive(Debug, Clone, Serialize, Deserialize)]
160pub struct SyncConfig {
161 pub auto_sync: bool,
163
164 pub default_interval_secs: u64,
166
167 pub conflict_resolution: ConflictResolution,
169
170 pub exclude_branches: Vec<String>,
172
173 pub pre_sync_hooks: Vec<SyncHook>,
175
176 pub post_sync_hooks: Vec<SyncHook>,
178}
179
180#[allow(dead_code)]
181impl SyncConfig {
182 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 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 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, 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#[derive(Debug, Clone, Serialize, Deserialize)]
229pub struct SyncHook {
230 pub command: String,
232
233 pub args: Vec<String>,
235
236 pub work_dir: Option<PathBuf>,
238
239 pub required: bool,
241
242 pub timeout_secs: Option<u64>,
244}
245
246#[allow(dead_code)]
247impl SyncHook {
248 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
284pub struct ProjectSettings {
285 pub default_shell: String,
287
288 pub global_env_vars: HashMap<String, String>,
290
291 pub logging: LoggingConfig,
293
294 pub performance: PerformanceSettings,
296
297 pub security: SecuritySettings,
299}
300
301#[allow(dead_code)]
302impl ProjectSettings {
303 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 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#[derive(Debug, Clone, Serialize, Deserialize)]
343pub struct LoggingConfig {
344 pub log_file: Option<PathBuf>,
346
347 pub level: LogLevel,
349
350 pub log_to_stdout: bool,
352
353 pub rotation: Option<LogRotation>,
355}
356
357#[allow(dead_code)]
358impl LoggingConfig {
359 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#[derive(Debug, Clone, Serialize, Deserialize)]
388pub struct LogRotation {
389 pub max_size_mb: u64,
391
392 pub max_files: u32,
394}
395
396#[allow(dead_code)]
397impl LogRotation {
398 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, max_files: 5,
417 }
418 }
419}
420
421#[derive(Debug, Clone, Serialize, Deserialize)]
423pub struct PerformanceSettings {
424 pub max_concurrent_ops: u32,
426
427 pub default_timeout_secs: u64,
429
430 pub enable_monitoring: bool,
432
433 pub memory_limit_mb: Option<u64>,
435
436 pub cpu_limit_percent: Option<u8>,
438}
439
440#[allow(dead_code)]
441impl PerformanceSettings {
442 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, enable_monitoring: true,
468 memory_limit_mb: Some(1024), cpu_limit_percent: Some(80), }
471 }
472}
473
474#[derive(Debug, Clone, Serialize, Deserialize)]
476pub struct SecuritySettings {
477 pub allowed_paths: Vec<PathBuf>,
479
480 pub blocked_commands: Vec<String>,
482
483 pub strict_path_validation: bool,
485
486 pub max_command_length: Option<usize>,
488
489 pub allow_shell_execution: bool,
491}
492
493#[allow(dead_code)]
494impl SecuritySettings {
495 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 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 blocked == command || command.starts_with(&format!("{} ", blocked))
520 }
521 })
522 }
523
524 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; }
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 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 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 assert!(config.validate().is_err());
604
605 let agent = Agent::new("agent-1", "feature/test");
607 config.add_agent(agent).unwrap();
608
609 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}