use crate::cli::ConfigCommands;
use crate::error::SpriteError;
use crate::utils::git;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::UNIX_EPOCH;
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AgentConfig {
pub id: String,
pub branch: String,
pub worktree_path: String,
pub model: String,
pub description: String,
pub status: String,
pub config: AgentConfigDetails,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AgentConfigDetails {
pub env_vars: std::collections::HashMap<String, String>,
pub work_dir: Option<String>,
pub startup_commands: Vec<String>,
pub resource_limits: ResourceLimits,
pub shell: Option<String>,
pub default_timeout_secs: u64,
pub auto_sync: bool,
pub custom_settings: std::collections::HashMap<String, serde_yaml::Value>,
}
impl Default for AgentConfigDetails {
fn default() -> Self {
Self {
env_vars: std::collections::HashMap::new(),
work_dir: None,
startup_commands: Vec::new(),
resource_limits: ResourceLimits::default(),
shell: None,
default_timeout_secs: 300,
auto_sync: false,
custom_settings: std::collections::HashMap::new(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ResourceLimits {
pub max_memory_mb: u64,
pub max_cpu_percent: u64,
pub operation_timeout_secs: u64,
pub max_concurrent_ops: u64,
pub max_disk_mb: u64,
}
impl Default for ResourceLimits {
fn default() -> Self {
Self {
max_memory_mb: 1024,
max_cpu_percent: 80,
operation_timeout_secs: 300,
max_concurrent_ops: 3,
max_disk_mb: 5120,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[allow(dead_code)]
pub struct SimpleAgentConfig {
pub branch: String,
pub worktree_path: String,
pub model: String,
pub description: String,
}
impl From<&AgentConfig> for SimpleAgentConfig {
fn from(agent: &AgentConfig) -> Self {
Self {
branch: agent.branch.clone(),
worktree_path: agent.worktree_path.clone(),
model: agent.model.clone(),
description: agent.description.clone(),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ConfigMetadata {
pub last_modified: u64,
pub content_hash: String,
pub version: u64,
}
impl Default for ConfigMetadata {
fn default() -> Self {
Self {
last_modified: 0,
content_hash: String::new(),
version: 1,
}
}
}
fn find_project_config_path() -> Option<PathBuf> {
crate::utils::project::find_project_root()
.ok()
.map(|root| root.join("agents").join("agents.yaml"))
}
fn get_project_root_from_config(config_path: &Path) -> Option<PathBuf> {
config_path.parent()?.parent().map(|p| p.to_path_buf())
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SpriteConfig {
pub version: String,
pub agents: Vec<AgentConfig>,
pub session_name: String,
pub sync: SyncConfig,
pub settings: SettingsConfig,
#[serde(skip)]
metadata: ConfigMetadata,
}
impl Default for SpriteConfig {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[allow(dead_code)]
pub struct SessionConfig {
pub name: String,
pub profile: String,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SyncConfig {
pub auto_sync: bool,
pub default_interval_secs: u64,
pub conflict_resolution: String,
pub exclude_branches: Vec<String>,
pub pre_sync_hooks: Vec<String>,
pub post_sync_hooks: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SettingsConfig {
pub default_shell: String,
pub global_env_vars: std::collections::HashMap<String, String>,
pub logging: LoggingConfig,
pub performance: PerformanceConfig,
pub security: SecurityConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LoggingConfig {
pub log_file: String,
pub level: String,
pub log_to_stdout: bool,
pub rotation: LogRotationConfig,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct LogRotationConfig {
pub max_size_mb: u64,
pub max_files: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PerformanceConfig {
pub max_concurrent_ops: u64,
pub default_timeout_secs: u64,
pub enable_monitoring: bool,
pub memory_limit_mb: u64,
pub cpu_limit_percent: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SecurityConfig {
pub allowed_paths: Vec<String>,
pub blocked_commands: Vec<String>,
pub strict_path_validation: bool,
pub max_command_length: u64,
pub allow_shell_execution: bool,
}
#[allow(dead_code)]
impl SpriteConfig {
pub fn new() -> Self {
Self {
version: "1.0".to_string(),
agents: Vec::new(),
session_name: "sprite-session".to_string(),
sync: SyncConfig {
auto_sync: false,
default_interval_secs: 300,
conflict_resolution: "manual".to_string(),
exclude_branches: vec!["main".to_string(), "master".to_string()],
pre_sync_hooks: Vec::new(),
post_sync_hooks: Vec::new(),
},
settings: SettingsConfig {
default_shell: "bash".to_string(),
global_env_vars: HashMap::new(),
logging: LoggingConfig {
log_file: "agents/logs/sprite.log".to_string(),
level: "info".to_string(),
log_to_stdout: true,
rotation: LogRotationConfig {
max_size_mb: 100,
max_files: 5,
},
},
performance: PerformanceConfig {
max_concurrent_ops: 10,
default_timeout_secs: 300,
enable_monitoring: true,
memory_limit_mb: 1024,
cpu_limit_percent: 80,
},
security: SecurityConfig {
allowed_paths: vec!["agents/".to_string()],
blocked_commands: vec![
"rm -rf".to_string(),
"sudo".to_string(),
"su".to_string(),
"chmod 777".to_string(),
],
strict_path_validation: true,
max_command_length: 1000,
allow_shell_execution: false,
},
},
metadata: ConfigMetadata::default(),
}
}
pub fn load() -> Result<Self> {
let config_path = find_project_config_path()
.ok_or_else(|| SpriteError::config(
"Could not find sprite configuration file. Run 'sprite init' in the project root first."
))?;
Self::load_from_path(&config_path)
}
pub fn load_from_path(path: &PathBuf) -> Result<Self> {
if !path.exists() {
return Err(SpriteError::config(format!(
"Configuration file not found: {}",
path.display()
))
.into());
}
let content = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read configuration file: {}", path.display()))?;
let mut config: SpriteConfig = serde_yaml::from_str(&content).map_err(|e| {
SpriteError::config(format!(
"Failed to parse configuration file {}: {}",
path.display(),
e
))
})?;
config.update_metadata(path, &content)?;
Ok(config)
}
pub fn save(&self) -> Result<()> {
let config_path = find_project_config_path().ok_or_else(|| {
SpriteError::config("Could not find sprite project directory to save configuration.")
})?;
self.save_to_path(&config_path)
}
pub fn save_to_path(&self, path: &PathBuf) -> Result<()> {
self.validate()?;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).with_context(|| {
format!("Failed to create config directory: {}", parent.display())
})?;
}
let content = serde_yaml::to_string(self).map_err(|e| {
SpriteError::config(format!("Failed to serialize configuration: {}", e))
})?;
std::fs::write(path, content)
.with_context(|| format!("Failed to write configuration file: {}", path.display()))?;
Ok(())
}
pub fn validate(&self) -> Result<()> {
if self.agents.is_empty() {
return Err(SpriteError::config("At least one agent must be configured").into());
}
for agent in &self.agents {
if agent.id.is_empty() {
return Err(SpriteError::config("Agent ID cannot be empty").into());
}
if agent.branch.is_empty() {
return Err(SpriteError::config(format!(
"Agent {} branch cannot be empty",
agent.id
))
.into());
}
if agent.worktree_path.is_empty() {
return Err(SpriteError::config(format!(
"Agent {} worktree_path cannot be empty",
agent.id
))
.into());
}
if agent.model.is_empty() {
return Err(SpriteError::config(format!(
"Agent {} model cannot be empty",
agent.id
))
.into());
}
}
if self.session_name.is_empty() {
return Err(SpriteError::config("Session name cannot be empty").into());
}
Ok(())
}
pub fn agent_ids(&self) -> Vec<String> {
self.agents.iter().map(|agent| agent.id.clone()).collect()
}
pub fn get_agent(&self, agent_id: &str) -> Option<&AgentConfig> {
self.agents.iter().find(|agent| agent.id == agent_id)
}
pub fn set_agent(&mut self, agent: AgentConfig) {
self.agents.retain(|a| a.id != agent.id);
self.agents.push(agent);
}
pub fn remove_agent(&mut self, agent_id: &str) -> Option<AgentConfig> {
let index = self.agents.iter().position(|agent| agent.id == agent_id);
if let Some(index) = index {
Some(self.agents.remove(index))
} else {
None
}
}
pub fn provision_worktrees(&self) -> Result<()> {
println!(
"🔧 Provisioning worktrees for {} agents...",
self.agents.len()
);
git::validate_git_repository()?;
git::prune_worktrees().context("Failed to prune worktrees")?;
for agent in &self.agents {
println!(" 📁 Setting up Agent {}...", agent.id);
let worktree_path = PathBuf::from(&agent.worktree_path);
if !worktree_path.exists() && git::branch_exists(&agent.branch)? {
println!(" 🔧 Removing stale worktree reference...");
git::remove_worktree_reference(&worktree_path).with_context(|| {
format!("Failed to remove worktree reference for agent {}", agent.id)
})?;
}
git::create_worktree(&worktree_path, &agent.branch)
.with_context(|| format!("Failed to create worktree for agent {}", agent.id))?;
println!(" ✅ Created worktree: {}", worktree_path.display());
println!(" 🌿 Branch: {}", agent.branch);
}
println!("✅ Worktree provisioning complete!");
Ok(())
}
pub fn validate_workspaces(&self) -> Result<()> {
println!("🔍 Validating agent workspaces...");
let worktrees = git::list_worktrees().context("Failed to list existing worktrees")?;
let worktree_paths: std::collections::HashSet<_> = worktrees
.iter()
.filter_map(|w| w.path.canonicalize().ok())
.collect();
let config_path = match find_project_config_path() {
Some(path) => path,
None => {
return Err(SpriteError::config(
"Could not find sprite configuration file to determine project root.",
)
.into());
}
};
let project_root = match get_project_root_from_config(&config_path) {
Some(root) => root,
None => {
return Err(SpriteError::config(
"Could not determine project root from configuration path.",
)
.into());
}
};
for agent in &self.agents {
let worktree_path = PathBuf::from(&agent.worktree_path);
let abs_worktree_path = if worktree_path.is_absolute() {
worktree_path.clone()
} else {
project_root
.join(&worktree_path)
.canonicalize()
.unwrap_or_else(|_| {
project_root.join(&worktree_path)
})
};
if !worktree_paths.contains(&abs_worktree_path) {
return Err(SpriteError::config(format!(
"Agent {} worktree does not exist: {}",
agent.id, agent.worktree_path
))
.into());
}
if !git::branch_exists(&agent.branch)? {
return Err(SpriteError::config(format!(
"Agent {} branch does not exist: {}",
agent.id, agent.branch
))
.into());
}
println!(
" ✅ Agent {}: {} ({})",
agent.id,
worktree_path.display(),
agent.branch
);
}
println!("✅ All workspaces are valid!");
Ok(())
}
fn update_metadata(&mut self, path: &PathBuf, content: &str) -> Result<()> {
let metadata = std::fs::metadata(path)
.with_context(|| format!("Failed to read file metadata: {}", path.display()))?;
let last_modified = metadata
.modified()
.with_context(|| format!("Failed to get modification time: {}", path.display()))?
.duration_since(UNIX_EPOCH)
.with_context(|| "System time before UNIX epoch")?
.as_secs();
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
let mut hasher = DefaultHasher::new();
content.hash(&mut hasher);
let content_hash = format!("{:x}", hasher.finish());
self.metadata = ConfigMetadata {
last_modified,
content_hash,
version: self.metadata.version + 1,
};
Ok(())
}
pub fn has_changed(&self) -> Result<bool> {
let config_path = match find_project_config_path() {
Some(path) => path,
None => return Ok(false), };
if !config_path.exists() {
return Ok(false);
}
let current_metadata = std::fs::metadata(&config_path)
.with_context(|| format!("Failed to read file metadata: {}", config_path.display()))?;
let current_modified = current_metadata
.modified()
.with_context(|| format!("Failed to get modification time: {}", config_path.display()))?
.duration_since(UNIX_EPOCH)
.with_context(|| "System time before UNIX epoch")?
.as_secs();
Ok(current_modified != self.metadata.last_modified)
}
pub fn version(&self) -> u64 {
self.metadata.version
}
pub fn last_modified(&self) -> u64 {
self.metadata.last_modified
}
pub fn content_hash(&self) -> &str {
&self.metadata.content_hash
}
pub fn reload_if_changed(&mut self) -> Result<bool> {
if !self.has_changed()? {
return Ok(false);
}
println!("🔄 Configuration file changed, reloading...");
let old_version = self.metadata.version;
let config_path = match find_project_config_path() {
Some(path) => path,
None => return Ok(false), };
let content = std::fs::read_to_string(&config_path).with_context(|| {
format!(
"Failed to read configuration file: {}",
config_path.display()
)
})?;
let new_config: SpriteConfig = serde_yaml::from_str(&content).map_err(|e| {
SpriteError::config(format!(
"Failed to parse configuration file {}: {}",
config_path.display(),
e
))
})?;
self.version = new_config.version;
self.agents = new_config.agents;
self.session_name = new_config.session_name;
self.sync = new_config.sync;
self.settings = new_config.settings;
self.update_metadata(&config_path, &content)?;
println!(
"✅ Configuration reloaded (version {} → {})",
old_version, self.metadata.version
);
Ok(true)
}
pub fn detect_changes(&self) -> Result<ConfigChanges> {
let config_path = match find_project_config_path() {
Some(path) => path,
None => return Ok(ConfigChanges::new()), };
if !config_path.exists() {
return Ok(ConfigChanges::new());
}
let current_metadata = std::fs::metadata(&config_path)
.with_context(|| format!("Failed to read file metadata: {}", config_path.display()))?;
let current_modified = current_metadata
.modified()
.with_context(|| format!("Failed to get modification time: {}", config_path.display()))?
.duration_since(UNIX_EPOCH)
.with_context(|| "System time before UNIX epoch")?
.as_secs();
if current_modified == self.metadata.last_modified {
return Ok(ConfigChanges::new());
}
let current_content = std::fs::read_to_string(&config_path).with_context(|| {
format!(
"Failed to read configuration file: {}",
config_path.display()
)
})?;
let current_config: SpriteConfig = serde_yaml::from_str(¤t_content).map_err(|e| {
SpriteError::config(format!(
"Failed to parse configuration file {}: {}",
config_path.display(),
e
))
})?;
let mut changes = ConfigChanges::new();
changes.file_modified = true;
changes.old_version = self.metadata.version;
changes.new_version = self.metadata.version + 1;
for old_agent in &self.agents {
if let Some(new_agent) = current_config.agents.iter().find(|a| a.id == old_agent.id) {
if old_agent != new_agent {
changes.modified_agents.push(old_agent.id.clone());
}
} else {
changes.removed_agents.push(old_agent.id.clone());
}
}
for new_agent in ¤t_config.agents {
if !self.agents.iter().any(|a| a.id == new_agent.id) {
changes.added_agents.push(new_agent.id.clone());
}
}
if self.session_name != current_config.session_name {
changes.session_changed = true;
}
if self.sync != current_config.sync {
changes.sync_changed = true;
}
Ok(changes)
}
}
#[derive(Debug, Clone)]
pub struct ConfigChanges {
pub file_modified: bool,
pub old_version: u64,
pub new_version: u64,
pub added_agents: Vec<String>,
pub removed_agents: Vec<String>,
pub modified_agents: Vec<String>,
pub session_changed: bool,
pub sync_changed: bool,
}
impl Default for ConfigChanges {
fn default() -> Self {
Self::new()
}
}
impl ConfigChanges {
pub fn new() -> Self {
Self {
file_modified: false,
old_version: 0,
new_version: 0,
added_agents: Vec::new(),
removed_agents: Vec::new(),
modified_agents: Vec::new(),
session_changed: false,
sync_changed: false,
}
}
pub fn has_changes(&self) -> bool {
self.file_modified
|| !self.added_agents.is_empty()
|| !self.removed_agents.is_empty()
|| !self.modified_agents.is_empty()
|| self.session_changed
|| self.sync_changed
}
pub fn print_summary(&self) {
if !self.has_changes() {
println!("✅ No configuration changes detected.");
return;
}
println!(
"🔄 Configuration changes detected (v{} → v{}):",
self.old_version, self.new_version
);
if !self.added_agents.is_empty() {
println!(" ➕ Added agents: {}", self.added_agents.join(", "));
}
if !self.removed_agents.is_empty() {
println!(" ➖ Removed agents: {}", self.removed_agents.join(", "));
}
if !self.modified_agents.is_empty() {
println!(" ✏️ Modified agents: {}", self.modified_agents.join(", "));
}
if self.session_changed {
println!(" 🎮 Session configuration changed");
}
if self.sync_changed {
println!(" 🔄 Sync configuration changed");
}
}
}
pub fn execute(command: ConfigCommands) -> Result<()> {
match command {
ConfigCommands::Show => show_config(),
ConfigCommands::Validate => validate_config(),
ConfigCommands::Set { key, value } => set_config_value(key, value),
ConfigCommands::Get { key } => get_config_value(key),
ConfigCommands::Edit => edit_config(),
ConfigCommands::Status => check_config_status(),
}
}
fn show_config() -> Result<()> {
let config = SpriteConfig::load().context("Failed to load configuration")?;
println!("📋 Sprite Configuration");
println!();
println!("🤖 Agents ({} total):", config.agents.len());
for agent in &config.agents {
println!(" {}:", agent.id);
println!(" Branch: {}", agent.branch);
println!(" Workspace: {}", agent.worktree_path);
println!(" Model: {}", agent.model);
println!(" Description: {}", agent.description);
println!(" Status: {}", agent.status);
println!();
}
println!("🎮 Session:");
println!(" Name: {}", config.session_name);
println!();
println!("🔄 Sync:");
println!(" Auto-sync: {}", config.sync.auto_sync);
println!(" Conflict resolution: {}", config.sync.conflict_resolution);
println!(" Exclude branches: {:?}", config.sync.exclude_branches);
println!(" Default interval: {}s", config.sync.default_interval_secs);
Ok(())
}
fn validate_config() -> Result<()> {
println!("🔍 Validating Sprite configuration...");
let config = SpriteConfig::load().context("Failed to load configuration")?;
config
.validate()
.context("Configuration validation failed")?;
println!("✅ Configuration structure is valid!");
config
.validate_workspaces()
.context("Workspace validation failed")?;
println!("✅ Configuration is fully valid!");
Ok(())
}
fn set_config_value(key: String, value: String) -> Result<()> {
let mut config = SpriteConfig::load().context("Failed to load configuration")?;
let parts: Vec<&str> = key.split('.').collect();
let value_clone = value.clone();
match parts.as_slice() {
["session", "name"] => {
config.session_name = value;
}
["sync", "auto_sync"] => {
config.sync.auto_sync = value
.parse::<bool>()
.map_err(|_| SpriteError::config("auto_sync must be true or false"))?;
}
["sync", "conflict_resolution"] => {
config.sync.conflict_resolution = value;
}
["sync", "default_interval_secs"] => {
config.sync.default_interval_secs = value
.parse::<u64>()
.map_err(|_| SpriteError::config("default_interval_secs must be a number"))?;
}
["settings", "default_shell"] => {
config.settings.default_shell = value;
}
["agents", agent_id, field] => {
let agent_index = config.agents.iter().position(|a| a.id == *agent_id);
let agent_config = if let Some(index) = agent_index {
&mut config.agents[index]
} else {
let new_agent = AgentConfig {
id: agent_id.to_string(),
branch: format!("agents/{}", agent_id),
worktree_path: format!("agents/{}", agent_id),
model: "claude-sonnet-4".to_string(),
description: format!("Agent {} workspace", agent_id),
status: "inactive".to_string(),
config: AgentConfigDetails {
env_vars: HashMap::new(),
work_dir: None,
startup_commands: Vec::new(),
resource_limits: ResourceLimits {
max_memory_mb: 1024,
max_cpu_percent: 80,
operation_timeout_secs: 300,
max_concurrent_ops: 3,
max_disk_mb: 5120,
},
shell: None,
default_timeout_secs: 300,
auto_sync: false,
custom_settings: HashMap::new(),
},
};
config.agents.push(new_agent);
config.agents.last_mut().unwrap()
};
match *field {
"branch" => agent_config.branch = value,
"worktree_path" => agent_config.worktree_path = value,
"model" => agent_config.model = value,
"description" => agent_config.description = value,
"status" => agent_config.status = value,
_ => {
return Err(
SpriteError::config(format!("Unknown agent field: {}", field)).into(),
)
}
}
}
_ => return Err(SpriteError::config(format!("Unknown configuration key: {}", key)).into()),
}
config.save().context("Failed to save configuration")?;
println!("✅ Configuration updated: {} = {}", key, value_clone);
Ok(())
}
fn get_config_value(key: String) -> Result<()> {
let config = SpriteConfig::load().context("Failed to load configuration")?;
let parts: Vec<&str> = key.split('.').collect();
let value = match parts.as_slice() {
["session", "name"] => Some(config.session_name.clone()),
["sync", "auto_sync"] => Some(config.sync.auto_sync.to_string()),
["sync", "conflict_resolution"] => Some(config.sync.conflict_resolution.clone()),
["sync", "default_interval_secs"] => Some(config.sync.default_interval_secs.to_string()),
["settings", "default_shell"] => Some(config.settings.default_shell.clone()),
["agents", agent_id, field] => config.get_agent(agent_id).and_then(|agent| match *field {
"branch" => Some(agent.branch.clone()),
"worktree_path" => Some(agent.worktree_path.clone()),
"model" => Some(agent.model.clone()),
"description" => Some(agent.description.clone()),
"status" => Some(agent.status.clone()),
_ => None,
}),
_ => None,
};
match value {
Some(v) => println!("{}: {}", key, v),
None => {
return Err(SpriteError::config(format!("Unknown configuration key: {}", key)).into())
}
}
Ok(())
}
fn edit_config() -> Result<()> {
let config_path = find_project_config_path().ok_or_else(|| {
SpriteError::config(
"Configuration file not found. Run 'sprite init' in the project root first.",
)
})?;
if !config_path.exists() {
return Err(SpriteError::config(format!(
"Configuration file not found: {}",
config_path.display()
))
.into());
}
let editor = std::env::var("EDITOR")
.or_else(|_| std::env::var("VISUAL"))
.unwrap_or_else(|_| {
if std::path::Path::new("/usr/bin/nano").exists() {
"nano".to_string()
} else if std::path::Path::new("/usr/bin/vim").exists() {
"vim".to_string()
} else if std::path::Path::new("/usr/bin/vi").exists() {
"vi".to_string()
} else {
"emacs".to_string()
}
});
println!("📝 Opening configuration file in {}...", editor);
let status = std::process::Command::new(&editor)
.arg(&config_path)
.status()
.with_context(|| format!("Failed to open editor: {}", editor))?;
if !status.success() {
return Err(SpriteError::process(
"editor".to_string(),
status.code(),
"".to_string(),
format!("Editor exited with non-zero status: {}", status),
)
.into());
}
println!("🔍 Validating updated configuration...");
let config = SpriteConfig::load().context("Failed to load updated configuration")?;
config
.validate()
.context("Updated configuration is invalid")?;
println!("✅ Configuration updated and validated successfully!");
Ok(())
}
fn check_config_status() -> Result<()> {
println!("🔍 Checking configuration status...");
let config = SpriteConfig::load().context("Failed to load configuration")?;
println!("📋 Configuration Status:");
println!(" Version: {}", config.version());
println!(" Last Modified: {}", {
use std::time::{Duration, UNIX_EPOCH};
let datetime = UNIX_EPOCH + Duration::from_secs(config.last_modified());
let time_str = datetime
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
let hours = time_str / 3600;
let minutes = (time_str % 3600) / 60;
let seconds = time_str % 60;
format!("{:02}:{:02}:{:02}", hours, minutes, seconds)
});
println!(
" Content Hash: {}...",
&config.content_hash()[..8.min(config.content_hash().len())]
);
let changes = config
.detect_changes()
.context("Failed to detect configuration changes")?;
if changes.has_changes() {
println!();
changes.print_summary();
if !changes.added_agents.is_empty() || !changes.modified_agents.is_empty() {
println!();
println!("💡 Suggestion: Run 'sprite agents provision' to create/update workspaces");
}
if !changes.removed_agents.is_empty() {
println!();
println!("💡 Suggestion: Check if workspaces for removed agents need cleanup");
}
} else {
println!(" ✅ Configuration is up to date");
}
println!();
println!("🔧 Workspace Status:");
match config.validate_workspaces() {
Ok(_) => println!(" ✅ All workspaces are valid"),
Err(e) => println!(" ⚠️ Workspace validation failed: {}", e),
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::TempDir;
#[test]
fn test_sprite_config_new() {
let config = SpriteConfig::new();
assert!(config.agents.is_empty());
assert_eq!(config.session_name, "sprite-session");
assert!(!config.sync.auto_sync);
assert_eq!(config.sync.conflict_resolution, "manual");
assert!(!config.sync.exclude_branches.is_empty()); assert_eq!(config.sync.exclude_branches, vec!["main", "master"]);
assert_eq!(config.version(), 1);
}
#[test]
fn test_sprite_config_validation() {
let mut config = SpriteConfig::new();
assert!(config.validate().is_err());
config.agents.push(AgentConfig {
id: "test-agent".to_string(),
branch: "main".to_string(),
worktree_path: "agents/test-agent".to_string(),
model: "claude-sonnet".to_string(),
description: "Test agent".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
assert!(config.validate().is_ok());
}
#[test]
fn test_sprite_config_validation_edge_cases() {
let mut config = SpriteConfig::new();
config.agents.push(AgentConfig {
id: "".to_string(),
branch: "main".to_string(),
worktree_path: "agents/test".to_string(),
model: "claude-sonnet".to_string(),
description: "Test".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
assert!(config.validate().is_err());
config.agents.clear();
config.agents.push(AgentConfig {
id: "test".to_string(),
branch: "".to_string(),
worktree_path: "agents/test".to_string(),
model: "claude-sonnet".to_string(),
description: "Test".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
assert!(config.validate().is_err());
config.agents.clear();
config.agents.push(AgentConfig {
id: "test".to_string(),
branch: "main".to_string(),
worktree_path: "".to_string(),
model: "claude-sonnet".to_string(),
description: "Test".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
assert!(config.validate().is_err());
config.agents.clear();
config.agents.push(AgentConfig {
id: "test".to_string(),
branch: "main".to_string(),
worktree_path: "agents/test".to_string(),
model: "".to_string(),
description: "Test".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
assert!(config.validate().is_err());
}
#[test]
fn test_agent_management() {
let mut config = SpriteConfig::new();
let agent_config = AgentConfig {
id: "feature-agent".to_string(),
branch: "feature-branch".to_string(),
worktree_path: "agents/feature".to_string(),
model: "claude-opus".to_string(),
description: "Feature branch agent".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
};
config.set_agent(agent_config.clone());
assert_eq!(config.agents.len(), 1);
let retrieved = config.get_agent("feature-agent");
assert!(retrieved.is_some());
assert_eq!(retrieved.unwrap(), &agent_config);
let ids = config.agent_ids();
assert_eq!(ids.len(), 1);
assert!(ids.contains(&"feature-agent".to_string()));
let removed = config.remove_agent("feature-agent");
assert!(removed.is_some());
assert_eq!(removed.unwrap(), agent_config);
assert_eq!(config.agents.len(), 0);
}
#[test]
fn test_yaml_serialization() {
let mut config = SpriteConfig::new();
config.agents.push(AgentConfig {
id: "agent1".to_string(),
branch: "main".to_string(),
worktree_path: "agents/agent1".to_string(),
model: "claude-sonnet".to_string(),
description: "First agent".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
config.session_name = "test-session".to_string();
let yaml = serde_yaml::to_string(&config).expect("Failed to serialize config");
assert!(yaml.contains("agent1"));
assert!(yaml.contains("test-session"));
let deserialized: SpriteConfig =
serde_yaml::from_str(&yaml).expect("Failed to deserialize config");
assert_eq!(deserialized.agents.len(), 1);
assert_eq!(deserialized.session_name, "test-session");
assert_eq!(config.agents, deserialized.agents);
assert_eq!(config.session_name, deserialized.session_name);
}
#[test]
fn test_config_metadata_tracking() {
let mut config = SpriteConfig::new();
assert_eq!(config.version(), 1);
assert_eq!(config.last_modified(), 0);
config.agents.push(AgentConfig {
id: "test".to_string(),
branch: "main".to_string(),
worktree_path: "agents/test".to_string(),
model: "claude".to_string(),
description: "Test".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
assert!(config.version() >= 1);
}
#[test]
fn test_config_change_detection() {
let mut config1 = SpriteConfig::new();
config1.agents.push(AgentConfig {
id: "agent1".to_string(),
branch: "main".to_string(),
worktree_path: "agents/agent1".to_string(),
model: "claude".to_string(),
description: "Agent 1".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
let _config2 = config1.clone();
let _changes = config1.detect_changes().expect("Failed to detect changes");
let mut changes = ConfigChanges::new();
changes.file_modified = false; changes.old_version = 1;
changes.new_version = 2;
changes.modified_agents.push("agent1".to_string());
assert!(changes.has_changes());
assert!(changes.modified_agents.contains(&"agent1".to_string()));
}
#[test]
fn test_save_and_load() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let config_path = temp_dir.path().join("test_config.yaml");
let mut original_config = SpriteConfig::new();
original_config.agents.push(AgentConfig {
id: "test-agent".to_string(),
branch: "main".to_string(),
worktree_path: "agents/test".to_string(),
model: "claude-sonnet".to_string(),
description: "Test agent for save/load".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
original_config
.save_to_path(&config_path)
.expect("Failed to save config");
assert!(config_path.exists());
let loaded_config =
SpriteConfig::load_from_path(&config_path).expect("Failed to load config");
assert_eq!(loaded_config.agents.len(), 1);
assert_eq!(loaded_config.agents[0].branch, "main");
assert_eq!(loaded_config.agents[0].model, "claude-sonnet");
assert_eq!(original_config.agents, loaded_config.agents);
assert_eq!(original_config.session_name, loaded_config.session_name);
assert_eq!(original_config.sync, loaded_config.sync);
}
#[test]
fn test_config_changes_summary() {
let mut changes = ConfigChanges::new();
changes.print_summary();
changes.file_modified = true;
changes.old_version = 1;
changes.new_version = 2;
changes.added_agents.push("new-agent".to_string());
changes.removed_agents.push("old-agent".to_string());
changes.modified_agents.push("mod-agent".to_string());
changes.session_changed = true;
changes.sync_changed = true;
assert!(changes.has_changes());
changes.print_summary();
}
#[test]
fn test_default_configs() {
let metadata = ConfigMetadata::default();
assert_eq!(metadata.last_modified, 0);
assert!(metadata.content_hash.is_empty());
assert_eq!(metadata.version, 1);
let config = SpriteConfig::new();
assert!(config.agents.is_empty());
assert!(!config.session_name.is_empty());
assert!(!config.sync.conflict_resolution.is_empty());
}
#[test]
fn test_session_and_sync_configs() {
let session = SessionConfig {
name: "test-session".to_string(),
profile: "test-profile".to_string(),
};
let sync = SyncConfig {
auto_sync: true,
default_interval_secs: 300,
conflict_resolution: "auto".to_string(),
exclude_branches: vec!["main".to_string(), "dev".to_string()],
pre_sync_hooks: Vec::new(),
post_sync_hooks: Vec::new(),
};
assert_eq!(session.name, "test-session");
assert_eq!(session.profile, "test-profile");
assert!(sync.auto_sync);
assert_eq!(sync.conflict_resolution, "auto");
assert_eq!(sync.exclude_branches.len(), 2);
}
#[test]
fn test_simple_agent_config() {
let agent = SimpleAgentConfig {
branch: "feature-branch".to_string(),
worktree_path: "workspaces/feature".to_string(),
model: "claude-opus".to_string(),
description: "Feature development agent".to_string(),
};
assert_eq!(agent.branch, "feature-branch");
assert_eq!(agent.worktree_path, "workspaces/feature");
assert_eq!(agent.model, "claude-opus");
assert_eq!(agent.description, "Feature development agent");
}
#[test]
fn test_edge_cases() {
let mut config = SpriteConfig::new();
config.session_name = "".to_string();
assert!(config.validate().is_err());
config.session_name = "valid".to_string();
assert!(config.validate().is_err()); }
#[test]
fn test_reload_if_changed_not_implemented() {
let mut config = SpriteConfig::new();
let result = config.reload_if_changed();
match result {
Ok(changed) => {
println!("Config reload result: {}", changed);
}
Err(e) => {
println!("Config reload error (expected): {}", e);
}
}
}
#[test]
fn test_provision_worktrees_validation() {
let mut config = SpriteConfig::new();
config.agents.push(AgentConfig {
id: "test-agent".to_string(),
branch: "main".to_string(),
worktree_path: "agents/test-agent".to_string(),
model: "claude".to_string(),
description: "Test agent".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
let result = config.provision_worktrees();
match result {
Ok(_) => {
println!("Worktree provisioning succeeded");
}
Err(e) => {
println!("Worktree provisioning failed as expected: {}", e);
}
}
}
#[test]
fn test_workspace_operations() {
let mut config = SpriteConfig::new();
config.agents.push(AgentConfig {
id: "test-agent".to_string(),
branch: "main".to_string(),
worktree_path: "agents/test-agent".to_string(),
model: "claude".to_string(),
description: "Test agent".to_string(),
status: "inactive".to_string(),
config: AgentConfigDetails::default(),
});
let result = config.validate_workspaces();
match result {
Ok(_) => {
println!("Workspace validation succeeded (unexpected but acceptable)");
}
Err(e) => {
println!("Workspace validation failed as expected: {}", e);
}
}
let result = config.has_changed();
assert!(result.is_ok());
let _changed = result.unwrap();
}
}