use super::{Agent, ConflictResolution, LogLevel};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectConfig {
pub version: String,
pub agents: Vec<Agent>,
pub session_name: String,
pub sync: SyncConfig,
pub settings: ProjectSettings,
}
#[allow(dead_code)]
impl ProjectConfig {
pub fn new() -> Self {
Self {
version: "1.0".to_string(),
agents: Vec::new(),
session_name: "default".to_string(),
sync: SyncConfig::default(),
settings: ProjectSettings::default(),
}
}
pub fn add_agent(&mut self, agent: Agent) -> Result<(), String> {
if self.agents.iter().any(|a| a.id == agent.id) {
return Err(format!("Agent with ID '{}' already exists", agent.id));
}
agent.validate()?;
self.agents.push(agent);
Ok(())
}
pub fn remove_agent(&mut self, agent_id: &str) -> Option<Agent> {
let index = self.agents.iter().position(|a| a.id == agent_id)?;
Some(self.agents.remove(index))
}
pub fn get_agent(&self, agent_id: &str) -> Option<&Agent> {
self.agents.iter().find(|a| a.id == agent_id)
}
pub fn get_agent_mut(&mut self, agent_id: &str) -> Option<&mut Agent> {
self.agents.iter_mut().find(|a| a.id == agent_id)
}
pub fn agent_count(&self) -> usize {
self.agents.len()
}
pub fn active_agents(&self) -> Vec<&Agent> {
self.agents.iter().filter(|a| a.is_active()).collect()
}
pub fn validate(&self) -> Result<(), String> {
if self.version.is_empty() {
return Err("Configuration version cannot be empty".to_string());
}
if self.agents.is_empty() {
return Err("At least one agent must be configured".to_string());
}
let mut agent_ids = std::collections::HashSet::new();
for agent in &self.agents {
if !agent_ids.insert(&agent.id) {
return Err(format!("Duplicate agent ID: {}", agent.id));
}
agent.validate()?;
}
if self.session_name.is_empty() {
return Err("Session name cannot be empty".to_string());
}
self.sync.validate()?;
self.settings.validate()?;
Ok(())
}
pub fn config_path() -> PathBuf {
PathBuf::from("agents/agents.yaml")
}
pub fn load_from_file(path: &PathBuf) -> Result<Self, String> {
let content = std::fs::read_to_string(path)
.map_err(|e| format!("Failed to read configuration file: {}", e))?;
let config: ProjectConfig = serde_yaml::from_str(&content)
.map_err(|e| format!("Failed to parse configuration: {}", e))?;
config.validate()?;
Ok(config)
}
pub fn save_to_file(&self, path: &PathBuf) -> Result<(), String> {
self.validate()?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create config directory: {}", e))?;
}
let content = serde_yaml::to_string(self)
.map_err(|e| format!("Failed to serialize configuration: {}", e))?;
std::fs::write(path, content)
.map_err(|e| format!("Failed to write configuration file: {}", e))?;
Ok(())
}
}
impl Default for ProjectConfig {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncConfig {
pub auto_sync: bool,
pub default_interval_secs: u64,
pub conflict_resolution: ConflictResolution,
pub exclude_branches: Vec<String>,
pub pre_sync_hooks: Vec<SyncHook>,
pub post_sync_hooks: Vec<SyncHook>,
}
#[allow(dead_code)]
impl SyncConfig {
pub fn validate(&self) -> Result<(), String> {
if self.default_interval_secs == 0 {
return Err("Sync interval must be greater than 0".to_string());
}
for (i, hook) in self.pre_sync_hooks.iter().enumerate() {
hook.validate()
.map_err(|e| format!("Pre-sync hook {}: {}", i + 1, e))?;
}
for (i, hook) in self.post_sync_hooks.iter().enumerate() {
hook.validate()
.map_err(|e| format!("Post-sync hook {}: {}", i + 1, e))?;
}
Ok(())
}
pub fn should_exclude_branch(&self, branch: &str) -> bool {
self.exclude_branches.iter().any(|excluded| {
if excluded.ends_with('*') {
branch.starts_with(&excluded[..excluded.len() - 1])
} else {
excluded == branch
}
})
}
}
impl Default for SyncConfig {
fn default() -> Self {
Self {
auto_sync: false,
default_interval_secs: 300, conflict_resolution: ConflictResolution::default(),
exclude_branches: vec!["main".to_string(), "master".to_string()],
pre_sync_hooks: Vec::new(),
post_sync_hooks: Vec::new(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SyncHook {
pub command: String,
pub args: Vec<String>,
pub work_dir: Option<PathBuf>,
pub required: bool,
pub timeout_secs: Option<u64>,
}
#[allow(dead_code)]
impl SyncHook {
pub fn validate(&self) -> Result<(), String> {
if self.command.is_empty() {
return Err("Hook command cannot be empty".to_string());
}
if let Some(ref work_dir) = self.work_dir {
if work_dir.as_os_str().is_empty() {
return Err("Hook working directory cannot be empty".to_string());
}
}
Ok(())
}
pub fn execute(&self) -> Result<std::process::Output, String> {
use std::process::Command;
let mut cmd = Command::new(&self.command);
cmd.args(&self.args);
if let Some(ref work_dir) = self.work_dir {
cmd.current_dir(work_dir);
}
let output = cmd
.output()
.map_err(|e| format!("Failed to execute hook command '{}': {}", self.command, e))?;
Ok(output)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectSettings {
pub default_shell: String,
pub global_env_vars: HashMap<String, String>,
pub logging: LoggingConfig,
pub performance: PerformanceSettings,
pub security: SecuritySettings,
}
#[allow(dead_code)]
impl ProjectSettings {
pub fn validate(&self) -> Result<(), String> {
if self.default_shell.is_empty() {
return Err("Default shell cannot be empty".to_string());
}
self.logging.validate()?;
self.performance.validate()?;
self.security.validate()?;
Ok(())
}
pub fn get_effective_env(
&self,
agent_env: &HashMap<String, String>,
) -> HashMap<String, String> {
let mut env = self.global_env_vars.clone();
for (key, value) in agent_env {
env.insert(key.clone(), value.clone());
}
env
}
}
impl Default for ProjectSettings {
fn default() -> Self {
Self {
default_shell: "bash".to_string(),
global_env_vars: HashMap::new(),
logging: LoggingConfig::default(),
performance: PerformanceSettings::default(),
security: SecuritySettings::default(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LoggingConfig {
pub log_file: Option<PathBuf>,
pub level: LogLevel,
pub log_to_stdout: bool,
pub rotation: Option<LogRotation>,
}
#[allow(dead_code)]
impl LoggingConfig {
pub fn validate(&self) -> Result<(), String> {
if let Some(ref log_file) = self.log_file {
if log_file.as_os_str().is_empty() {
return Err("Log file path cannot be empty".to_string());
}
}
if let Some(ref rotation) = self.rotation {
rotation.validate()?;
}
Ok(())
}
}
impl Default for LoggingConfig {
fn default() -> Self {
Self {
log_file: Some(PathBuf::from("agents/logs/sprite.log")),
level: LogLevel::default(),
log_to_stdout: true,
rotation: Some(LogRotation::default()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct LogRotation {
pub max_size_mb: u64,
pub max_files: u32,
}
#[allow(dead_code)]
impl LogRotation {
pub fn validate(&self) -> Result<(), String> {
if self.max_size_mb == 0 {
return Err("Maximum log file size must be greater than 0".to_string());
}
if self.max_files == 0 {
return Err("Maximum number of log files must be greater than 0".to_string());
}
Ok(())
}
}
impl Default for LogRotation {
fn default() -> Self {
Self {
max_size_mb: 100, max_files: 5,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceSettings {
pub max_concurrent_ops: u32,
pub default_timeout_secs: u64,
pub enable_monitoring: bool,
pub memory_limit_mb: Option<u64>,
pub cpu_limit_percent: Option<u8>,
}
#[allow(dead_code)]
impl PerformanceSettings {
pub fn validate(&self) -> Result<(), String> {
if self.max_concurrent_ops == 0 {
return Err("Maximum concurrent operations must be greater than 0".to_string());
}
if self.default_timeout_secs == 0 {
return Err("Default timeout must be greater than 0".to_string());
}
if let Some(cpu_limit) = self.cpu_limit_percent {
if cpu_limit == 0 || cpu_limit > 100 {
return Err("CPU limit must be between 1 and 100".to_string());
}
}
Ok(())
}
}
impl Default for PerformanceSettings {
fn default() -> Self {
Self {
max_concurrent_ops: 10,
default_timeout_secs: 300, enable_monitoring: true,
memory_limit_mb: Some(1024), cpu_limit_percent: Some(80), }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SecuritySettings {
pub allowed_paths: Vec<PathBuf>,
pub blocked_commands: Vec<String>,
pub strict_path_validation: bool,
pub max_command_length: Option<usize>,
pub allow_shell_execution: bool,
}
#[allow(dead_code)]
impl SecuritySettings {
pub fn validate(&self) -> Result<(), String> {
if let Some(max_length) = self.max_command_length {
if max_length == 0 {
return Err("Maximum command length must be greater than 0".to_string());
}
}
for path in &self.allowed_paths {
if path.as_os_str().is_empty() {
return Err("Allowed paths cannot contain empty paths".to_string());
}
}
Ok(())
}
pub fn is_command_blocked(&self, command: &str) -> bool {
self.blocked_commands.iter().any(|blocked| {
if blocked.ends_with('*') {
command.starts_with(&blocked[..blocked.len() - 1])
} else {
blocked == command || command.starts_with(&format!("{} ", blocked))
}
})
}
pub fn is_path_allowed(&self, path: &PathBuf) -> bool {
if !self.strict_path_validation {
return true;
}
if self.allowed_paths.is_empty() {
return true; }
self.allowed_paths
.iter()
.any(|allowed| path.starts_with(allowed) || path == allowed)
}
}
impl Default for SecuritySettings {
fn default() -> Self {
Self {
allowed_paths: vec![PathBuf::from("agents/")],
blocked_commands: vec![
"rm -rf".to_string(),
"sudo".to_string(),
"su".to_string(),
"chmod 777".to_string(),
],
strict_path_validation: true,
max_command_length: Some(1000),
allow_shell_execution: false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_project_config_creation() {
let config = ProjectConfig::new();
assert_eq!(config.version, "1.0");
assert_eq!(config.agents.len(), 0);
assert_eq!(config.settings.default_shell, "bash");
}
#[test]
fn test_add_agent() {
let mut config = ProjectConfig::new();
let agent = Agent::new("agent-1", "feature/test");
assert!(config.add_agent(agent.clone()).is_ok());
assert_eq!(config.agent_count(), 1);
assert!(config.add_agent(agent).is_err());
}
#[test]
fn test_remove_agent() {
let mut config = ProjectConfig::new();
let agent = Agent::new("agent-1", "feature/test");
config.add_agent(agent).unwrap();
assert_eq!(config.agent_count(), 1);
let removed = config.remove_agent("agent-1");
assert!(removed.is_some());
assert_eq!(config.agent_count(), 0);
let removed = config.remove_agent("non-existent");
assert!(removed.is_none());
}
#[test]
fn test_config_validation() {
let mut config = ProjectConfig::new();
assert!(config.validate().is_err());
let agent = Agent::new("agent-1", "feature/test");
config.add_agent(agent).unwrap();
assert!(config.validate().is_ok());
}
#[test]
fn test_sync_config() {
let sync = SyncConfig::default();
assert!(!sync.auto_sync);
assert_eq!(sync.default_interval_secs, 300);
assert!(sync.should_exclude_branch("main"));
assert!(!sync.should_exclude_branch("feature/test"));
}
#[test]
fn test_security_settings() {
let security = SecuritySettings::default();
assert!(security.is_command_blocked("rm -rf"));
assert!(security.is_command_blocked("sudo ls"));
assert!(!security.is_command_blocked("git status"));
assert!(security.is_path_allowed(&PathBuf::from("agents/agent-1")));
assert!(!security.is_path_allowed(&PathBuf::from("/etc/passwd")));
}
#[test]
fn test_sync_hook() {
let hook = SyncHook {
command: "echo".to_string(),
args: vec!["test".to_string()],
work_dir: None,
required: false,
timeout_secs: Some(30),
};
assert!(hook.validate().is_ok());
let invalid_hook = SyncHook {
command: "".to_string(),
args: vec![],
work_dir: None,
required: false,
timeout_secs: None,
};
assert!(invalid_hook.validate().is_err());
}
}